title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Networking in C#
The .NET Framework has a layered, extensible, and managed implementation of networking services. You can easily integrate them into your applications. Use the System.Net; namespace. Let us see how to acess the Uri class:.In C#, it provides object representation of a uniform resource identifier (URI) − Uri uri = new Uri("http://www.example.com/"); WebRequest w = WebRequest.Create(uri); Let us now see the System.Net class. This is used to encorypt connections using using the Secure Socket Layer (SSL). If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used. The following is an example. For SSL with FTP, set the EnableSsl property to true before calling the GetResponse() method. String uri = "https://www.example.com/"; WebRequest w = WebRequest.Create(uri); String uriServer = "ftp://ftp.example.com/new.txt" FtpWebRequest r = (FtpWebRequest)WebRequest.Create(uriServer); r.EnableSsl = true; r.Method = WebRequestMethods.Ftp.DeleteFile; The following is an example showing the usage of System.Net namespace and using the Dns.GetHostEntry, Dns.GetHostName methods and IPHostEntry property AddressList − using System; using System.Net; class Program { static void Main() { String hostName = string.Empty; hostName = Dns.GetHostName(); Console.WriteLine("Hostname: "+hostName); IPHostEntry myIP = Dns.GetHostEntry(hostName); IPAddress[] address = myIP.AddressList; for (int i = 0; i < address.Length; i++) { Console.WriteLine("IP Address {1} : ",address[i].ToString()); } Console.ReadLine(); } }
[ { "code": null, "e": 1369, "s": 1187, "text": "The .NET Framework has a layered, extensible, and managed implementation of networking services. You can easily integrate them into your applications. Use the System.Net; namespace." }, { "code": null, "e": 1490, "s": 1369, "text": "Let us see how to acess the Uri class:.In C#, it provides object representation of a uniform resource identifier (URI) −" }, { "code": null, "e": 1575, "s": 1490, "text": "Uri uri = new Uri(\"http://www.example.com/\");\nWebRequest w = WebRequest.Create(uri);" }, { "code": null, "e": 1805, "s": 1575, "text": "Let us now see the System.Net class. This is used to encorypt connections using using the Secure Socket Layer (SSL). If the URI begins with \"https:\", SSL is used; if the URI begins with \"http:\", an unencrypted connection is used." }, { "code": null, "e": 1928, "s": 1805, "text": "The following is an example. For SSL with FTP, set the EnableSsl property to true before calling the GetResponse() method." }, { "code": null, "e": 2188, "s": 1928, "text": "String uri = \"https://www.example.com/\";\nWebRequest w = WebRequest.Create(uri);\n\nString uriServer = \"ftp://ftp.example.com/new.txt\"\nFtpWebRequest r = (FtpWebRequest)WebRequest.Create(uriServer);\nr.EnableSsl = true;\nr.Method = WebRequestMethods.Ftp.DeleteFile;" }, { "code": null, "e": 2353, "s": 2188, "text": "The following is an example showing the usage of System.Net namespace and using the Dns.GetHostEntry, Dns.GetHostName methods and IPHostEntry property AddressList −" }, { "code": null, "e": 2811, "s": 2353, "text": "using System;\nusing System.Net;\n\nclass Program {\n static void Main() {\n\n String hostName = string.Empty;\n hostName = Dns.GetHostName();\n Console.WriteLine(\"Hostname: \"+hostName);\n IPHostEntry myIP = Dns.GetHostEntry(hostName);\n\n IPAddress[] address = myIP.AddressList;\n\n for (int i = 0; i < address.Length; i++) {\n Console.WriteLine(\"IP Address {1} : \",address[i].ToString());\n }\n Console.ReadLine();\n }\n}" } ]
How to make a Todo List CLI application using Python ?
17 May, 2022 In this article, we see how to make a Command Line application todo list in python. Todo list is a basic application in which users can add items. It’s a list of tasks you need to complete or things that you want to do. In to-do, list tasks are organized in order of priority. One of the most important reasons you should use a to-do list is that it will help you stay organized. In this article we make a to-do list using the command line. By Using a to-do list as a command-line application we can organize our to-do list through a command prompt, and we do not need to run any script or program explicitly. Basic Functions of todo list are: Add a new todo Delete a todo Complete a todo Show remaining todos Show statistics of todo Example Note: In Windows Command Prompt to run the application → type todo or.\todo In shell or git bash --> type ./todo To create todo list application we have to follow these steps: Create a folder named todolist Create a file todo.py in the created folder If you are a window user then Create another file todo.bat file. This is a batch file. And it is used to run the python script If you are Linux user then create a file named as todo.sh. This is used to run the python script. todo.bat: @echo off python3 todo.py %1 %2 todo.sh: python todo.py "$@" Create a symbolic link to the executable file: In Windows (In command prompt or Powershell) To create a symbolic link on Windows, you’ll need to run either the Windows Command Prompt or Windows Powershell **with administrator privileges**. To do so, right-click on the icon for Command Prompt, or Powershell, and choose the _”Run as Administrator”_ option. mklink todo todo.bat In Linux or in the shell(as git bash) $ ln -s todo.sh todo Now we have to code the functions of our to-do list. So we write the code in todo.py Python3 # module requiredimport sysimport datetime Help function: The help function is used to provide the way how a user can use the todo list. And Help function is like the documentation of todo application. Python3 # help functiondef help(): sa = """Usage :-$ ./todo add "todo item" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics""" sys.stdout.buffer.write(sa.encode('utf8')) Function to add items in todo list: Add function is used to add new items to todo list Python3 # function to add item in todo listdef add(s): f = open('todo.txt', 'a') f.write(s) f.write("\n") f.close() s = '"'+s+'"' print(f"Added todo: {s}") The function to print the todo list function is used to print the items that are present in our todo list. Todo items are printed in ascending order. Python3 # Function to print the todo list itemsdef ls(): try: nec() l = len(d) k = l for i in d: sys.stdout.buffer.write(f"[{l}] {d[l]}".encode('utf8')) sys.stdout.buffer.write("\n".encode('utf8')) l = l-1 except Exception as e: raise e Function to Complete a todo: Function defines the completed task and this completed task is added in done.txt. Python3 # Function to Complete a tododef done(no): try: nec() no = int(no) f = open('done.txt', 'a') st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no] f.write(st) f.write("\n") f.close() print(f"Marked todo #{no} as done.") with open("todo.txt", "r+") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\n') != d[no]: f.write(i) f.truncate() except: print(f"Error: todo #{no} does not exist.") Function to show the statistics of todolist: The “report” function is used to show the complete statistics. It prints total no of the completed task and total no of the pending task. Python3 # Function to show report/statistics of todo listdef report(): nec() try: nf = open('done.txt', 'r') c = 1 for line in nf: line = line.strip('\n') don.update({c: line}) c = c+1 print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') except: print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') Function to delete an item from todo list: deL function is used to delete an item from todo list. It deletes todo item based on the item number Python3 # codedef deL(no): try: no = int(no) nec() # utility function defined in main with open("todo.txt", "r+") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\n') != d[no]: f.write(i) f.truncate() print(f"Deleted todo #{no}") except Exception as e: print(f"Error: todo #{no} does not exist. Nothing deleted.") Main function and utility function Python3 # codedef nec(): # utility function used in done and report function try: f = open('todo.txt', 'r') c = 1 for line in f: line = line.strip('\n') d.update({c: line}) c = c+1 except: sys.stdout.buffer.write("There are no pending todos!".encode('utf8')) # Main programif __name__ == '__main__': try: d = {} don = {} args = sys.argv if(args[1] == 'del'): args[1] = 'deL' if(args[1] == 'add' and len(args[2:]) == 0): sys.stdout.buffer.write( "Error: Missing todo string. Nothing added!".encode('utf8')) elif(args[1] == 'done' and len(args[2:]) == 0): sys.stdout.buffer.write( "Error: Missing NUMBER for marking todo as done.".encode('utf8')) elif(args[1] == 'deL' and len(args[2:]) == 0): sys.stdout.buffer.write( "Error: Missing NUMBER for deleting todo.".encode('utf8')) else: globals()[args[1]](*args[2:]) except Exception as e: s = """Usage :-$ ./todo add "todo item" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics""" sys.stdout.buffer.write(s.encode('utf8')) Below is the implementation: Python3 # Complete codeimport sysimport datetime def help(): sa = """Usage :-$ ./todo add "todo item" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics""" sys.stdout.buffer.write(sa.encode('utf8')) def add(s): f = open('todo.txt', 'a') f.write(s) f.write("\n") f.close() s = '"'+s+'"' print(f"Added todo: {s}") def ls(): try: nec() l = len(d) k = l for i in d: sys.stdout.buffer.write(f"[{l}] {d[l]}".encode('utf8')) sys.stdout.buffer.write("\n".encode('utf8')) l = l-1 except Exception as e: raise e def deL(no): try: no = int(no) nec() with open("todo.txt", "r+") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\n') != d[no]: f.write(i) f.truncate() print(f"Deleted todo #{no}") except Exception as e: print(f"Error: todo #{no} does not exist. Nothing deleted.") def done(no): try: nec() no = int(no) f = open('done.txt', 'a') st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no] f.write(st) f.write("\n") f.close() print(f"Marked todo #{no} as done.") with open("todo.txt", "r+") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\n') != d[no]: f.write(i) f.truncate() except: print(f"Error: todo #{no} does not exist.") def report(): nec() try: nf = open('done.txt', 'r') c = 1 for line in nf: line = line.strip('\n') don.update({c: line}) c = c+1 print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') except: print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') def nec(): try: f = open('todo.txt', 'r') c = 1 for line in f: line = line.strip('\n') d.update({c: line}) c = c+1 except: sys.stdout.buffer.write("There are no pending todos!".encode('utf8')) if __name__ == '__main__': try: d = {} don = {} args = sys.argv if(args[1] == 'del'): args[1] = 'deL' if(args[1] == 'add' and len(args[2:]) == 0): sys.stdout.buffer.write( "Error: Missing todo string. Nothing added!".encode('utf8')) elif(args[1] == 'done' and len(args[2:]) == 0): sys.stdout.buffer.write( "Error: Missing NUMBER for marking todo as done.".encode('utf8')) elif(args[1] == 'deL' and len(args[2:]) == 0): sys.stdout.buffer.write( "Error: Missing NUMBER for deleting todo.".encode('utf8')) else: globals()[args[1]](*args[2:]) except Exception as e: s = """Usage :-$ ./todo add "todo item" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics""" sys.stdout.buffer.write(s.encode('utf8')) Output: sagartomar9927 Python-projects python-utility Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2022" }, { "code": null, "e": 437, "s": 52, "text": "In this article, we see how to make a Command Line application todo list in python. Todo list is a basic application in which users can add items. It’s a list of tasks you need to complete or things that you want to do. In to-do, list tasks are organized in order of priority. One of the most important reasons you should use a to-do list is that it will help you stay organized. " }, { "code": null, "e": 667, "s": 437, "text": "In this article we make a to-do list using the command line. By Using a to-do list as a command-line application we can organize our to-do list through a command prompt, and we do not need to run any script or program explicitly." }, { "code": null, "e": 701, "s": 667, "text": "Basic Functions of todo list are:" }, { "code": null, "e": 716, "s": 701, "text": "Add a new todo" }, { "code": null, "e": 730, "s": 716, "text": "Delete a todo" }, { "code": null, "e": 746, "s": 730, "text": "Complete a todo" }, { "code": null, "e": 767, "s": 746, "text": "Show remaining todos" }, { "code": null, "e": 791, "s": 767, "text": "Show statistics of todo" }, { "code": null, "e": 799, "s": 791, "text": "Example" }, { "code": null, "e": 875, "s": 799, "text": "Note: In Windows Command Prompt to run the application → type todo or.\\todo" }, { "code": null, "e": 917, "s": 875, "text": "In shell or git bash --> type ./todo" }, { "code": null, "e": 980, "s": 917, "text": "To create todo list application we have to follow these steps:" }, { "code": null, "e": 1011, "s": 980, "text": "Create a folder named todolist" }, { "code": null, "e": 1055, "s": 1011, "text": "Create a file todo.py in the created folder" }, { "code": null, "e": 1182, "s": 1055, "text": "If you are a window user then Create another file todo.bat file. This is a batch file. And it is used to run the python script" }, { "code": null, "e": 1281, "s": 1182, "text": "If you are Linux user then create a file named as todo.sh. This is used to run the python script." }, { "code": null, "e": 1414, "s": 1404, "text": "todo.bat:" }, { "code": null, "e": 1446, "s": 1414, "text": "@echo off\npython3 todo.py %1 %2" }, { "code": null, "e": 1455, "s": 1446, "text": "todo.sh:" }, { "code": null, "e": 1475, "s": 1455, "text": "python todo.py \"$@\"" }, { "code": null, "e": 1522, "s": 1475, "text": "Create a symbolic link to the executable file:" }, { "code": null, "e": 1567, "s": 1522, "text": "In Windows (In command prompt or Powershell)" }, { "code": null, "e": 1832, "s": 1567, "text": "To create a symbolic link on Windows, you’ll need to run either the Windows Command Prompt or Windows Powershell **with administrator privileges**. To do so, right-click on the icon for Command Prompt, or Powershell, and choose the _”Run as Administrator”_ option." }, { "code": null, "e": 1853, "s": 1832, "text": "mklink todo todo.bat" }, { "code": null, "e": 1891, "s": 1853, "text": "In Linux or in the shell(as git bash)" }, { "code": null, "e": 1912, "s": 1891, "text": "$ ln -s todo.sh todo" }, { "code": null, "e": 1965, "s": 1912, "text": "Now we have to code the functions of our to-do list." }, { "code": null, "e": 1997, "s": 1965, "text": "So we write the code in todo.py" }, { "code": null, "e": 2005, "s": 1997, "text": "Python3" }, { "code": "# module requiredimport sysimport datetime", "e": 2048, "s": 2005, "text": null }, { "code": null, "e": 2209, "s": 2048, "text": "Help function: The help function is used to provide the way how a user can use the todo list. And Help function is like the documentation of todo application. " }, { "code": null, "e": 2217, "s": 2209, "text": "Python3" }, { "code": "# help functiondef help(): sa = \"\"\"Usage :-$ ./todo add \"todo item\" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics\"\"\" sys.stdout.buffer.write(sa.encode('utf8'))", "e": 2563, "s": 2217, "text": null }, { "code": null, "e": 2650, "s": 2563, "text": "Function to add items in todo list: Add function is used to add new items to todo list" }, { "code": null, "e": 2658, "s": 2650, "text": "Python3" }, { "code": "# function to add item in todo listdef add(s): f = open('todo.txt', 'a') f.write(s) f.write(\"\\n\") f.close() s = '\"'+s+'\"' print(f\"Added todo: {s}\")", "e": 2827, "s": 2658, "text": null }, { "code": null, "e": 2977, "s": 2827, "text": "The function to print the todo list function is used to print the items that are present in our todo list. Todo items are printed in ascending order." }, { "code": null, "e": 2985, "s": 2977, "text": "Python3" }, { "code": "# Function to print the todo list itemsdef ls(): try: nec() l = len(d) k = l for i in d: sys.stdout.buffer.write(f\"[{l}] {d[l]}\".encode('utf8')) sys.stdout.buffer.write(\"\\n\".encode('utf8')) l = l-1 except Exception as e: raise e", "e": 3294, "s": 2985, "text": null }, { "code": null, "e": 3406, "s": 3294, "text": "Function to Complete a todo: Function defines the completed task and this completed task is added in done.txt. " }, { "code": null, "e": 3414, "s": 3406, "text": "Python3" }, { "code": "# Function to Complete a tododef done(no): try: nec() no = int(no) f = open('done.txt', 'a') st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no] f.write(st) f.write(\"\\n\") f.close() print(f\"Marked todo #{no} as done.\") with open(\"todo.txt\", \"r+\") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\\n') != d[no]: f.write(i) f.truncate() except: print(f\"Error: todo #{no} does not exist.\")", "e": 4013, "s": 3414, "text": null }, { "code": null, "e": 4196, "s": 4013, "text": "Function to show the statistics of todolist: The “report” function is used to show the complete statistics. It prints total no of the completed task and total no of the pending task." }, { "code": null, "e": 4204, "s": 4196, "text": "Python3" }, { "code": "# Function to show report/statistics of todo listdef report(): nec() try: nf = open('done.txt', 'r') c = 1 for line in nf: line = line.strip('\\n') don.update({c: line}) c = c+1 print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') except: print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')", "e": 4697, "s": 4204, "text": null }, { "code": null, "e": 4841, "s": 4697, "text": "Function to delete an item from todo list: deL function is used to delete an item from todo list. It deletes todo item based on the item number" }, { "code": null, "e": 4849, "s": 4841, "text": "Python3" }, { "code": "# codedef deL(no): try: no = int(no) nec() # utility function defined in main with open(\"todo.txt\", \"r+\") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\\n') != d[no]: f.write(i) f.truncate() print(f\"Deleted todo #{no}\") except Exception as e: print(f\"Error: todo #{no} does not exist. Nothing deleted.\")", "e": 5321, "s": 4849, "text": null }, { "code": null, "e": 5356, "s": 5321, "text": "Main function and utility function" }, { "code": null, "e": 5364, "s": 5356, "text": "Python3" }, { "code": "# codedef nec(): # utility function used in done and report function try: f = open('todo.txt', 'r') c = 1 for line in f: line = line.strip('\\n') d.update({c: line}) c = c+1 except: sys.stdout.buffer.write(\"There are no pending todos!\".encode('utf8')) # Main programif __name__ == '__main__': try: d = {} don = {} args = sys.argv if(args[1] == 'del'): args[1] = 'deL' if(args[1] == 'add' and len(args[2:]) == 0): sys.stdout.buffer.write( \"Error: Missing todo string. Nothing added!\".encode('utf8')) elif(args[1] == 'done' and len(args[2:]) == 0): sys.stdout.buffer.write( \"Error: Missing NUMBER for marking todo as done.\".encode('utf8')) elif(args[1] == 'deL' and len(args[2:]) == 0): sys.stdout.buffer.write( \"Error: Missing NUMBER for deleting todo.\".encode('utf8')) else: globals()[args[1]](*args[2:]) except Exception as e: s = \"\"\"Usage :-$ ./todo add \"todo item\" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics\"\"\" sys.stdout.buffer.write(s.encode('utf8'))", "e": 6774, "s": 5364, "text": null }, { "code": null, "e": 6803, "s": 6774, "text": "Below is the implementation:" }, { "code": null, "e": 6811, "s": 6803, "text": "Python3" }, { "code": "# Complete codeimport sysimport datetime def help(): sa = \"\"\"Usage :-$ ./todo add \"todo item\" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics\"\"\" sys.stdout.buffer.write(sa.encode('utf8')) def add(s): f = open('todo.txt', 'a') f.write(s) f.write(\"\\n\") f.close() s = '\"'+s+'\"' print(f\"Added todo: {s}\") def ls(): try: nec() l = len(d) k = l for i in d: sys.stdout.buffer.write(f\"[{l}] {d[l]}\".encode('utf8')) sys.stdout.buffer.write(\"\\n\".encode('utf8')) l = l-1 except Exception as e: raise e def deL(no): try: no = int(no) nec() with open(\"todo.txt\", \"r+\") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\\n') != d[no]: f.write(i) f.truncate() print(f\"Deleted todo #{no}\") except Exception as e: print(f\"Error: todo #{no} does not exist. Nothing deleted.\") def done(no): try: nec() no = int(no) f = open('done.txt', 'a') st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no] f.write(st) f.write(\"\\n\") f.close() print(f\"Marked todo #{no} as done.\") with open(\"todo.txt\", \"r+\") as f: lines = f.readlines() f.seek(0) for i in lines: if i.strip('\\n') != d[no]: f.write(i) f.truncate() except: print(f\"Error: todo #{no} does not exist.\") def report(): nec() try: nf = open('done.txt', 'r') c = 1 for line in nf: line = line.strip('\\n') don.update({c: line}) c = c+1 print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') except: print( f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}') def nec(): try: f = open('todo.txt', 'r') c = 1 for line in f: line = line.strip('\\n') d.update({c: line}) c = c+1 except: sys.stdout.buffer.write(\"There are no pending todos!\".encode('utf8')) if __name__ == '__main__': try: d = {} don = {} args = sys.argv if(args[1] == 'del'): args[1] = 'deL' if(args[1] == 'add' and len(args[2:]) == 0): sys.stdout.buffer.write( \"Error: Missing todo string. Nothing added!\".encode('utf8')) elif(args[1] == 'done' and len(args[2:]) == 0): sys.stdout.buffer.write( \"Error: Missing NUMBER for marking todo as done.\".encode('utf8')) elif(args[1] == 'deL' and len(args[2:]) == 0): sys.stdout.buffer.write( \"Error: Missing NUMBER for deleting todo.\".encode('utf8')) else: globals()[args[1]](*args[2:]) except Exception as e: s = \"\"\"Usage :-$ ./todo add \"todo item\" # Add a new todo$ ./todo ls # Show remaining todos$ ./todo del NUMBER # Delete a todo$ ./todo done NUMBER # Complete a todo$ ./todo help # Show usage$ ./todo report # Statistics\"\"\" sys.stdout.buffer.write(s.encode('utf8'))", "e": 10283, "s": 6811, "text": null }, { "code": null, "e": 10291, "s": 10283, "text": "Output:" }, { "code": null, "e": 10306, "s": 10291, "text": "sagartomar9927" }, { "code": null, "e": 10322, "s": 10306, "text": "Python-projects" }, { "code": null, "e": 10337, "s": 10322, "text": "python-utility" }, { "code": null, "e": 10361, "s": 10337, "text": "Technical Scripter 2020" }, { "code": null, "e": 10368, "s": 10361, "text": "Python" }, { "code": null, "e": 10387, "s": 10368, "text": "Technical Scripter" }, { "code": null, "e": 10485, "s": 10387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10517, "s": 10485, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 10544, "s": 10517, "text": "Python Classes and Objects" }, { "code": null, "e": 10565, "s": 10544, "text": "Python OOPs Concepts" }, { "code": null, "e": 10588, "s": 10565, "text": "Introduction To PYTHON" }, { "code": null, "e": 10644, "s": 10588, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 10675, "s": 10644, "text": "Python | os.path.join() method" }, { "code": null, "e": 10717, "s": 10675, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 10759, "s": 10717, "text": "Check if element exists in list in Python" }, { "code": null, "e": 10798, "s": 10759, "text": "Python | datetime.timedelta() function" } ]
Explain Prototype Inheritance in JavaScript
12 Jan, 2022 In this article, we will try to understand the facts that are required to effectively understand what exactly Prototype Inheritance in JavaScript means or what does it actually implies with the help of several examples of approaches. Let’s understand the basics behind Prototype Inheritance in JavaScript. Prototype Inheritance in JavaScript: Following bullet points will try to analyze the basics behind Prototype Inheritance in JavaScript- Under the classical inheritance phenomenon, we create a new class that actually extends or reuses the properties or functions, or methods of another class that are used by several programming languages (like C, C++, Java, etc.) JavaScript doesn’t use classical inheritance instead it uses the phenomenon called Prototype Inheritance. In Prototype Inheritance, an object uses the properties or methods of another object via the prototype linkage. All the JavaScript objects inherit properties and methods from a prototype (like Date objects inherit properties from Date.prototype and so on). Following pictorial representation, containing some sample values will help us to understand Prototype Inheritance in a much better and effective way- In the above pictorial representation, we have taken an example to illustrate the Prototype Inheritance between a rabbit and another create prototype object which is an animal. We will set the rabbit’s prototype object as an animal prototype object wherein we will store all the values of rabbit for a purpose that if in the case in while rabbit properties are missing then JavaScript will automatically take it from animal prototype object. Now that you have understood a brief detailed description of the Prototype inheritance let us see and understand Prototype Inheritance with several following approaches- Approach 1: In this approach we will use __proto__, which is the special name for the internal and hidden prototype called [[Prototype]]. We will store all the properties of the rabbit in the animal prototype object and thereafter we may access it whenever it is required. This __proto__ is a bit old as well as an outdated approach that exists for some historical reasons associated with JavaScript. Example: Javascript <script> let animal = { animalEats: true, }; let rabbit = { rabbitJumps: true, }; // Sets rabbit.[[Prototype]] = animal rabbit.__proto__ = animal; console.log(rabbit.animalEats); console.log(rabbit.rabbitJumps);</script> Output: true true Approach 2: In this approach, we will use the new JavaScript methods to implement JavaScript Prototype Inheritance. Here we will use Object.setPrototypeOf() method takes two parameters first one is the object which is to have its prototype set and the second one is the object’s new prototype. Thereafter we have declared two objects and using those two objects, we will set one of the objects as the prototype object for another object. Javascript <script> let rabbit = { rabbitJumps: true, }; let animal = { animalEats: true, }; Object.setPrototypeOf(rabbit, animal); console.log(rabbit.animalEats); console.log(rabbit.rabbitJumps);</script> Output: true true javascript-object JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jan, 2022" }, { "code": null, "e": 288, "s": 54, "text": "In this article, we will try to understand the facts that are required to effectively understand what exactly Prototype Inheritance in JavaScript means or what does it actually implies with the help of several examples of approaches." }, { "code": null, "e": 360, "s": 288, "text": "Let’s understand the basics behind Prototype Inheritance in JavaScript." }, { "code": null, "e": 496, "s": 360, "text": "Prototype Inheritance in JavaScript: Following bullet points will try to analyze the basics behind Prototype Inheritance in JavaScript-" }, { "code": null, "e": 724, "s": 496, "text": "Under the classical inheritance phenomenon, we create a new class that actually extends or reuses the properties or functions, or methods of another class that are used by several programming languages (like C, C++, Java, etc.)" }, { "code": null, "e": 830, "s": 724, "text": "JavaScript doesn’t use classical inheritance instead it uses the phenomenon called Prototype Inheritance." }, { "code": null, "e": 942, "s": 830, "text": "In Prototype Inheritance, an object uses the properties or methods of another object via the prototype linkage." }, { "code": null, "e": 1087, "s": 942, "text": "All the JavaScript objects inherit properties and methods from a prototype (like Date objects inherit properties from Date.prototype and so on)." }, { "code": null, "e": 1238, "s": 1087, "text": "Following pictorial representation, containing some sample values will help us to understand Prototype Inheritance in a much better and effective way-" }, { "code": null, "e": 1415, "s": 1238, "text": "In the above pictorial representation, we have taken an example to illustrate the Prototype Inheritance between a rabbit and another create prototype object which is an animal." }, { "code": null, "e": 1680, "s": 1415, "text": "We will set the rabbit’s prototype object as an animal prototype object wherein we will store all the values of rabbit for a purpose that if in the case in while rabbit properties are missing then JavaScript will automatically take it from animal prototype object." }, { "code": null, "e": 1850, "s": 1680, "text": "Now that you have understood a brief detailed description of the Prototype inheritance let us see and understand Prototype Inheritance with several following approaches-" }, { "code": null, "e": 1862, "s": 1850, "text": "Approach 1:" }, { "code": null, "e": 1988, "s": 1862, "text": "In this approach we will use __proto__, which is the special name for the internal and hidden prototype called [[Prototype]]." }, { "code": null, "e": 2123, "s": 1988, "text": "We will store all the properties of the rabbit in the animal prototype object and thereafter we may access it whenever it is required." }, { "code": null, "e": 2251, "s": 2123, "text": "This __proto__ is a bit old as well as an outdated approach that exists for some historical reasons associated with JavaScript." }, { "code": null, "e": 2261, "s": 2251, "text": "Example: " }, { "code": null, "e": 2272, "s": 2261, "text": "Javascript" }, { "code": "<script> let animal = { animalEats: true, }; let rabbit = { rabbitJumps: true, }; // Sets rabbit.[[Prototype]] = animal rabbit.__proto__ = animal; console.log(rabbit.animalEats); console.log(rabbit.rabbitJumps);</script>", "e": 2535, "s": 2272, "text": null }, { "code": null, "e": 2543, "s": 2535, "text": "Output:" }, { "code": null, "e": 2553, "s": 2543, "text": "true\ntrue" }, { "code": null, "e": 2566, "s": 2553, "text": "Approach 2: " }, { "code": null, "e": 2670, "s": 2566, "text": "In this approach, we will use the new JavaScript methods to implement JavaScript Prototype Inheritance." }, { "code": null, "e": 2848, "s": 2670, "text": "Here we will use Object.setPrototypeOf() method takes two parameters first one is the object which is to have its prototype set and the second one is the object’s new prototype." }, { "code": null, "e": 2992, "s": 2848, "text": "Thereafter we have declared two objects and using those two objects, we will set one of the objects as the prototype object for another object." }, { "code": null, "e": 3003, "s": 2992, "text": "Javascript" }, { "code": "<script> let rabbit = { rabbitJumps: true, }; let animal = { animalEats: true, }; Object.setPrototypeOf(rabbit, animal); console.log(rabbit.animalEats); console.log(rabbit.rabbitJumps);</script>", "e": 3233, "s": 3003, "text": null }, { "code": null, "e": 3241, "s": 3233, "text": "Output:" }, { "code": null, "e": 3251, "s": 3241, "text": "true\ntrue" }, { "code": null, "e": 3269, "s": 3251, "text": "javascript-object" }, { "code": null, "e": 3290, "s": 3269, "text": "JavaScript-Questions" }, { "code": null, "e": 3297, "s": 3290, "text": "Picked" }, { "code": null, "e": 3308, "s": 3297, "text": "JavaScript" }, { "code": null, "e": 3325, "s": 3308, "text": "Web Technologies" } ]
Python | locals() function
22 Sep, 2021 Python locals() function returns the dictionary of the current local symbol table. Symbol table: It is a data structure created by a compiler for which is used to store all information needed to execute a program. Local symbol Table: This symbol table stores all information needed for the local scope of the program and this information is accessed using python built-in function locals(). Syntax : locals() Parameters: This function does not takes any input parameter. Return Type : This returns the information stored in local symbol table. Python3 # Python program to understand about locals# here no local variable is present def demo1(): print("Here no local variable is present : ", locals()) # here local variables are presentdef demo2(): name = "Ankit" print("Here local variables are present : ", locals()) # driver codedemo1()demo2() Output; Here no local variable is present : {} Here local variables are present : {'name': 'Ankit'} Unlike globals() this function can not modify the data of the local symbol table. The below program explains it clearly. Python3 # Python program to understand about locals# here no local variable is present def demo1(): print("Here no local variable is present : ", locals()) # here local variables are presentdef demo2(): name = "Ankit" print("Here local variables are present : ", locals()) print("Before updating name is : ", name) # trying to change name value locals()['name'] = "Sri Ram" print("after updating name is : ", name) # driver codedemo1()demo2() Output: Here no local variable is present : {} Here local variables are present : {'name': 'Ankit'} Before updating name is : Ankit after updating name is : Ankit The local symbol table is the same as the global symbol table in the case of the global environment. Python3 # Python program to understand about locals # data using localsprint("This is using locals() : ", locals()) # data using globalsprint("This is using globals() : ", globals()) Output: This is using locals() : {‘__name__’: ‘__main__’, ‘__doc__’: ‘Automatically created module for IPython interactive environment’, ‘__package__’: None, ‘__loader__’: None, ‘__spec__’: None, ‘__builtin__’: <module ‘builtins’ (built-in)>, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘_ih’: [”, ‘import multiprocessing\nfrom bs4 import BeautifulSoup\nfrom queue import Queue, Empty\nfrom concurrent.futures import ThreadPoolExecutor\nfrom urllib.parse import urljoin, urlparse\nimport requests\n\n\nclass MultiThreadedCrawler:\n\n def __init__(self, seed_url):\n self.seed_url = seed_url\n self.root_url = \'{}://{}\’.format(urlparse(self.seed_url).scheme,\n urlparse(self.seed_url).netloc)\n self.pool = ThreadPoolExecutor(max_workers=5)\n self.scraped_pages = set([])\n self.crawl_queue = Queue()\n self.crawl_queu The python globals() function in Python returns the dictionary of the current global symbol table. Syntax: globals() Parameters: No parameters required. Python3 # Python3 program to demonstrate global() function # global variablea = 5 def func(): c = 10 d = c + a # Calling globals() globals()['a'] = d print (d) # Driver Code func() Output: 15 Python locals() function in Python returns the dictionary of the current local symbol table. Python3 locals() Output: {‘__name__’: ‘__main__’, ‘__doc__’: ‘Automatically created module for IPython interactive environment’, ‘__package__’: None, ‘__loader__’: None, ‘__spec__’: None, ‘__builtin__’: <module ‘builtins’ (built-in)>, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘_ih’: [”, ‘# Python program to demonstrate the use of\n# len() method \n\n# Length of below string is 5\nstring = “geeks” \nprint(len(string))\n\n# Length of below string is 15\nstring = “geeks for geeks” \nprint(len(string))’, ‘# Python program to demonstrate the use of\n# len() method \n\n# L Akanksha_Rai kumar_satyam Python-Functions 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 Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 111, "s": 28, "text": "Python locals() function returns the dictionary of the current local symbol table." }, { "code": null, "e": 242, "s": 111, "text": "Symbol table: It is a data structure created by a compiler for which is used to store all information needed to execute a program." }, { "code": null, "e": 419, "s": 242, "text": "Local symbol Table: This symbol table stores all information needed for the local scope of the program and this information is accessed using python built-in function locals()." }, { "code": null, "e": 437, "s": 419, "text": "Syntax : locals()" }, { "code": null, "e": 500, "s": 437, "text": "Parameters: This function does not takes any input parameter. " }, { "code": null, "e": 573, "s": 500, "text": "Return Type : This returns the information stored in local symbol table." }, { "code": null, "e": 581, "s": 573, "text": "Python3" }, { "code": "# Python program to understand about locals# here no local variable is present def demo1(): print(\"Here no local variable is present : \", locals()) # here local variables are presentdef demo2(): name = \"Ankit\" print(\"Here local variables are present : \", locals()) # driver codedemo1()demo2()", "e": 884, "s": 581, "text": null }, { "code": null, "e": 892, "s": 884, "text": "Output;" }, { "code": null, "e": 987, "s": 892, "text": "Here no local variable is present : {}\nHere local variables are present : {'name': 'Ankit'}" }, { "code": null, "e": 1109, "s": 987, "text": "Unlike globals() this function can not modify the data of the local symbol table. The below program explains it clearly. " }, { "code": null, "e": 1117, "s": 1109, "text": "Python3" }, { "code": "# Python program to understand about locals# here no local variable is present def demo1(): print(\"Here no local variable is present : \", locals()) # here local variables are presentdef demo2(): name = \"Ankit\" print(\"Here local variables are present : \", locals()) print(\"Before updating name is : \", name) # trying to change name value locals()['name'] = \"Sri Ram\" print(\"after updating name is : \", name) # driver codedemo1()demo2()", "e": 1577, "s": 1117, "text": null }, { "code": null, "e": 1585, "s": 1577, "text": "Output:" }, { "code": null, "e": 1746, "s": 1585, "text": "Here no local variable is present : {}\nHere local variables are present : {'name': 'Ankit'}\nBefore updating name is : Ankit\nafter updating name is : Ankit" }, { "code": null, "e": 1848, "s": 1746, "text": "The local symbol table is the same as the global symbol table in the case of the global environment. " }, { "code": null, "e": 1856, "s": 1848, "text": "Python3" }, { "code": "# Python program to understand about locals # data using localsprint(\"This is using locals() : \", locals()) # data using globalsprint(\"This is using globals() : \", globals())", "e": 2031, "s": 1856, "text": null }, { "code": null, "e": 2039, "s": 2031, "text": "Output:" }, { "code": null, "e": 2941, "s": 2039, "text": "This is using locals() : {‘__name__’: ‘__main__’, ‘__doc__’: ‘Automatically created module for IPython interactive environment’, ‘__package__’: None, ‘__loader__’: None, ‘__spec__’: None, ‘__builtin__’: <module ‘builtins’ (built-in)>, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘_ih’: [”, ‘import multiprocessing\\nfrom bs4 import BeautifulSoup\\nfrom queue import Queue, Empty\\nfrom concurrent.futures import ThreadPoolExecutor\\nfrom urllib.parse import urljoin, urlparse\\nimport requests\\n\\n\\nclass MultiThreadedCrawler:\\n\\n def __init__(self, seed_url):\\n self.seed_url = seed_url\\n self.root_url = \\'{}://{}\\’.format(urlparse(self.seed_url).scheme,\\n urlparse(self.seed_url).netloc)\\n self.pool = ThreadPoolExecutor(max_workers=5)\\n self.scraped_pages = set([])\\n self.crawl_queue = Queue()\\n self.crawl_queu" }, { "code": null, "e": 3040, "s": 2941, "text": "The python globals() function in Python returns the dictionary of the current global symbol table." }, { "code": null, "e": 3095, "s": 3040, "text": "Syntax: globals()\n\nParameters: No parameters required." }, { "code": null, "e": 3103, "s": 3095, "text": "Python3" }, { "code": "# Python3 program to demonstrate global() function # global variablea = 5 def func(): c = 10 d = c + a # Calling globals() globals()['a'] = d print (d) # Driver Code func()", "e": 3302, "s": 3103, "text": null }, { "code": null, "e": 3310, "s": 3302, "text": "Output:" }, { "code": null, "e": 3313, "s": 3310, "text": "15" }, { "code": null, "e": 3406, "s": 3313, "text": "Python locals() function in Python returns the dictionary of the current local symbol table." }, { "code": null, "e": 3414, "s": 3406, "text": "Python3" }, { "code": "locals()", "e": 3423, "s": 3414, "text": null }, { "code": null, "e": 3431, "s": 3423, "text": "Output:" }, { "code": null, "e": 3456, "s": 3431, "text": "{‘__name__’: ‘__main__’," }, { "code": null, "e": 3536, "s": 3456, "text": " ‘__doc__’: ‘Automatically created module for IPython interactive environment’," }, { "code": null, "e": 3558, "s": 3536, "text": " ‘__package__’: None," }, { "code": null, "e": 3579, "s": 3558, "text": " ‘__loader__’: None," }, { "code": null, "e": 3598, "s": 3579, "text": " ‘__spec__’: None," }, { "code": null, "e": 3646, "s": 3598, "text": " ‘__builtin__’: <module ‘builtins’ (built-in)>," }, { "code": null, "e": 3695, "s": 3646, "text": " ‘__builtins__’: <module ‘builtins’ (built-in)>," }, { "code": null, "e": 3707, "s": 3695, "text": " ‘_ih’: [”," }, { "code": null, "e": 3928, "s": 3707, "text": " ‘# Python program to demonstrate the use of\\n# len() method \\n\\n# Length of below string is 5\\nstring = “geeks” \\nprint(len(string))\\n\\n# Length of below string is 15\\nstring = “geeks for geeks” \\nprint(len(string))’," }, { "code": null, "e": 3999, "s": 3928, "text": " ‘# Python program to demonstrate the use of\\n# len() method \\n\\n# L" }, { "code": null, "e": 4012, "s": 3999, "text": "Akanksha_Rai" }, { "code": null, "e": 4025, "s": 4012, "text": "kumar_satyam" }, { "code": null, "e": 4042, "s": 4025, "text": "Python-Functions" }, { "code": null, "e": 4049, "s": 4042, "text": "Python" }, { "code": null, "e": 4147, "s": 4049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4179, "s": 4147, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4206, "s": 4179, "text": "Python Classes and Objects" }, { "code": null, "e": 4227, "s": 4206, "text": "Python OOPs Concepts" }, { "code": null, "e": 4250, "s": 4227, "text": "Introduction To PYTHON" }, { "code": null, "e": 4306, "s": 4250, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4337, "s": 4306, "text": "Python | os.path.join() method" }, { "code": null, "e": 4379, "s": 4337, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4421, "s": 4379, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4460, "s": 4421, "text": "Python | Get unique values from a list" } ]
SQL Query to Find Monthly Salary of Employee If Annual Salary is Given
13 Apr, 2021 SQL stands for Structured Query Language, which used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. Similarly, when we want any data from the database then we write the query in SQL to get that data. In this article, we are talking about how we can find the monthly salary of employees if annual salary is given. To create a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is, CREATE DATABASE database_name; For example, CREATE DATABASE GeeksforGeeks_salary; To use the database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is, USE database_name; For example: USE GeeksforGeeks_salary; To create tables in a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is, CREATE TABLE table_name( column1 type(size), column2 type(size), . . . columnN type(size) ); For example, CREATE TABLE GFG_salary( emp_ID INT, emp_name VARCHAR(50), emp_course_mentor VARCHAR(30), emp_An_salary INT ); To see the table use the below: DESC GFG_salary; If we use the Microsoft SQL server then we need to use EXEC sp_help in place of DESC. In the Microsoft SQL server, the DESC command is not an SQL command, it is used in Oracle. To add value to the table there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The command is, INSERT INTO table_name( value1, value2, value3 . . . valueN); For example, here the query will be, INSERT INTO `GFG_salary` (`emp_ID`, `emp_name`, `emp_course_mentor`, `emp_An_salary`) VALUES (1, 'EmpABC', 'C++', '480000'), (2, 'EmpDEF', 'JAVA', '540000'), (3, 'EmpXYZ', 'DSA', '600000'), (4, 'EmpIJK', 'Python', '650000'); SELECT * FROM GFG_salary; Now we have to find the monthly salary of employees from the table where the annual salary is given, To find this, we have to divide the annual salary by 12 and make an alias column as Monthly Salary to view the monthly salary o each employee. And to view other details present in the table select those columns in the select statement. SELECT emp_name, (emp_An_salary/12) AS 'Monthly Salary' , emp_An_Salary AS 'Annual Salary' FROM GFG_salary ; Now round of the salary by 2 decimal point, to do that we have used round function, see below SELECT emp_name, round(emp_An_salary/12,2) AS 'Monthly Salary' , emp_An_Salary AS 'Annual Salary' FROM GFG_salary To find the monthly salary of particular employees, then use the where clause with a condition, see below, SELECT emp_name, round(emp_An_salary/12,2) AS 'Monthly Salary' , emp_An_Salary AS 'Annual Salary' FROM gfg_salary WHERE emp_ID = 1 OR emp_name = 'EmpABC' ; Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Apr, 2021" }, { "code": null, "e": 561, "s": 53, "text": "SQL stands for Structured Query Language, which used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. Similarly, when we want any data from the database then we write the query in SQL to get that data. In this article, we are talking about how we can find the monthly salary of employees if annual salary is given." }, { "code": null, "e": 674, "s": 561, "text": "To create a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is," }, { "code": null, "e": 705, "s": 674, "text": "CREATE DATABASE database_name;" }, { "code": null, "e": 718, "s": 705, "text": "For example," }, { "code": null, "e": 756, "s": 718, "text": "CREATE DATABASE GeeksforGeeks_salary;" }, { "code": null, "e": 868, "s": 756, "text": "To use the database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is," }, { "code": null, "e": 887, "s": 868, "text": "USE database_name;" }, { "code": null, "e": 900, "s": 887, "text": "For example:" }, { "code": null, "e": 926, "s": 900, "text": "USE GeeksforGeeks_salary;" }, { "code": null, "e": 1049, "s": 926, "text": "To create tables in a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is," }, { "code": null, "e": 1142, "s": 1049, "text": "CREATE TABLE table_name(\ncolumn1 type(size),\ncolumn2 type(size),\n.\n.\n.\ncolumnN type(size)\n);" }, { "code": null, "e": 1155, "s": 1142, "text": "For example," }, { "code": null, "e": 1266, "s": 1155, "text": "CREATE TABLE GFG_salary(\nemp_ID INT,\nemp_name VARCHAR(50),\nemp_course_mentor VARCHAR(30),\nemp_An_salary INT\n);" }, { "code": null, "e": 1298, "s": 1266, "text": "To see the table use the below:" }, { "code": null, "e": 1315, "s": 1298, "text": "DESC GFG_salary;" }, { "code": null, "e": 1492, "s": 1315, "text": "If we use the Microsoft SQL server then we need to use EXEC sp_help in place of DESC. In the Microsoft SQL server, the DESC command is not an SQL command, it is used in Oracle." }, { "code": null, "e": 1612, "s": 1492, "text": "To add value to the table there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The command is," }, { "code": null, "e": 1675, "s": 1612, "text": "INSERT INTO table_name(\nvalue1,\nvalue2,\nvalue3\n.\n.\n.\n\nvalueN);" }, { "code": null, "e": 1712, "s": 1675, "text": "For example, here the query will be," }, { "code": null, "e": 1937, "s": 1712, "text": "INSERT INTO `GFG_salary` (`emp_ID`, `emp_name`, `emp_course_mentor`, `emp_An_salary`)\nVALUES\n(1, 'EmpABC', 'C++', '480000'),\n(2, 'EmpDEF', 'JAVA', '540000'),\n(3, 'EmpXYZ', 'DSA', '600000'),\n(4, 'EmpIJK', 'Python', '650000');" }, { "code": null, "e": 1963, "s": 1937, "text": "SELECT * FROM GFG_salary;" }, { "code": null, "e": 2064, "s": 1963, "text": "Now we have to find the monthly salary of employees from the table where the annual salary is given," }, { "code": null, "e": 2300, "s": 2064, "text": "To find this, we have to divide the annual salary by 12 and make an alias column as Monthly Salary to view the monthly salary o each employee. And to view other details present in the table select those columns in the select statement." }, { "code": null, "e": 2409, "s": 2300, "text": "SELECT emp_name, (emp_An_salary/12) AS 'Monthly Salary' ,\nemp_An_Salary AS 'Annual Salary' FROM GFG_salary ;" }, { "code": null, "e": 2503, "s": 2409, "text": "Now round of the salary by 2 decimal point, to do that we have used round function, see below" }, { "code": null, "e": 2617, "s": 2503, "text": "SELECT emp_name, round(emp_An_salary/12,2) AS 'Monthly Salary' ,\nemp_An_Salary AS 'Annual Salary' FROM GFG_salary" }, { "code": null, "e": 2724, "s": 2617, "text": "To find the monthly salary of particular employees, then use the where clause with a condition, see below," }, { "code": null, "e": 2882, "s": 2724, "text": "SELECT emp_name, round(emp_An_salary/12,2) AS 'Monthly Salary' , emp_An_Salary AS 'Annual Salary'\nFROM gfg_salary\nWHERE\nemp_ID = 1 \nOR\nemp_name = 'EmpABC' ;" }, { "code": null, "e": 2889, "s": 2882, "text": "Picked" }, { "code": null, "e": 2899, "s": 2889, "text": "SQL-Query" }, { "code": null, "e": 2903, "s": 2899, "text": "SQL" }, { "code": null, "e": 2907, "s": 2903, "text": "SQL" }, { "code": null, "e": 3005, "s": 2907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3071, "s": 3005, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3095, "s": 3071, "text": "Window functions in SQL" }, { "code": null, "e": 3127, "s": 3095, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3144, "s": 3127, "text": "SQL using Python" }, { "code": null, "e": 3177, "s": 3144, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3255, "s": 3177, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3285, "s": 3255, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3321, "s": 3285, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 3352, "s": 3321, "text": "SQL Query to Compare Two Dates" } ]
Rexx - Stacks
The stack is sometimes called the external data queue, but we follow common usage and refer to it as the stack. It is a block of memory that is logically external to Rexx. Instructions like push and queue place data into the stack, and instructions like pull and parse pull extract data from it. The queued built-in function reports how many items are in the stack. Let’s take a look at an example of a stack. /* STACK: */ /* */ /* This program shows how to use the Rexx Stack as either a */ /* stack or a queue. */ do j = 1 to 3 push ‘Stack: line #’ || j /* push 3 lines onto the stack */ end do j = 1 to queued() /* retrieve and display LIFO */ pull line say line end do j = 1 to 3 queue ‘Queue: line #’ || j /* queue 3 lines onto the stack */ end do queued() /* retrieve and display FIFO */ pull line say line end exit 0 The first do loop in the program places three lines of data onto the stack. It uses the push instruction to do this. We number the lines so that when they are retrieved in the LIFO order their order is apparent. The items placed into the stack by the push instruction are retrieved in the LIFO order − do j = 1 to 3 push ‘Stack: line #’ || j /* push 3 lines onto the stack */ end The next code block shows the use of the queued built-in function to discover the number of lines on the stack, as well as a loop to retrieve all the lines from the stack − do j = 1 to queued() /* retrieve and display LIFO */ pull line say line end Since the three items were placed on the stack via push, they are retrieved in the LIFO order. The output of the above program will be as follows. STACK: LINE #3 STACK: LINE #2 STACK: LINE #1
[ { "code": null, "e": 2839, "s": 2473, "text": "The stack is sometimes called the external data queue, but we follow common usage and refer to it as the stack. It is a block of memory that is logically external to Rexx. Instructions like push and queue place data into the stack, and instructions like pull and parse pull extract data from it. The queued built-in function reports how many items are in the stack." }, { "code": null, "e": 2883, "s": 2839, "text": "Let’s take a look at an example of a stack." }, { "code": null, "e": 3322, "s": 2883, "text": "/* STACK: */\n/* */ \n/* This program shows how to use the Rexx Stack as either a */ \n\n/* stack or a queue. */ \ndo j = 1 to 3 \npush ‘Stack: line #’ || j \n\n/* push 3 lines onto the stack */ \nend \ndo j = 1 to queued() \n\n/* retrieve and display LIFO */ \npull line \nsay line \nend \ndo j = 1 to 3 queue ‘Queue: line #’ || j \n\n/* queue 3 lines onto the stack */ \nend \ndo queued() \n\n/* retrieve and display FIFO */ \npull line \nsay line \nend \nexit 0" }, { "code": null, "e": 3534, "s": 3322, "text": "The first do loop in the program places three lines of data onto the stack. It uses the push instruction to do this. We number the lines so that when they are retrieved in the LIFO order their order is apparent." }, { "code": null, "e": 3624, "s": 3534, "text": "The items placed into the stack by the push instruction are retrieved in the LIFO order −" }, { "code": null, "e": 3708, "s": 3624, "text": "do j = 1 to 3 \npush ‘Stack: line #’ || j /* push 3 lines onto the stack */ \nend" }, { "code": null, "e": 3881, "s": 3708, "text": "The next code block shows the use of the queued built-in function to discover the number of lines on the stack, as well as a loop to retrieve all the lines from the stack −" }, { "code": null, "e": 3963, "s": 3881, "text": "do j = 1 to queued() /* retrieve and display LIFO */ \npull line \nsay line \nend" }, { "code": null, "e": 4058, "s": 3963, "text": "Since the three items were placed on the stack via push, they are retrieved in the LIFO order." }, { "code": null, "e": 4110, "s": 4058, "text": "The output of the above program will be as follows." } ]
DirectX - Modeling
Source assets which is required for models stored in Autodesk FBX, Wavefront OBJ or other formats. A typical build process is used for conversion which is used in run-time friendly format which is easy to load and render. For creating a model, Visual Studio includes a built-in system which includes a convert format of a Wavefront OBJ or Autodesk FBX which is considered as a part of the build process which is needed to CMO. In this chapter, we will make use of the DirectXMesh meshconvert command line tool. The developer can start this activity by saving cup.obj, cup.mtl and cup.jpg into the project directory. Following steps are required to implement the modeling − Download the Meshconvert.exe from the official site and save the executable file into the user’s project folder. Open the required command prompt and then change the project’s directory. Run the following command executed in below command prompt − meshconvert cup._obj -cmo -nodds -flipz -y With this, you can initiate a model creation. Now let us focus on updating effects settings on the mentioned model. The model class creates the required effects automatically for the loaded materials which are set to lighting parameters. The updating procedure is possible with the Model::UpdateEffects method. Following are the steps required to update effects settings in a specific model − From the drop-down menu, select Project/Properties. Set to "All Configurations"/"All Platforms". On the left-hand tree view, select C/C++ Language. Then set "Enable Run-Time Type Information" to "Yes". Click "OK". In the mentioned file Game.cpp, add the TODO of CreateDevice as shown below − m_model->UpdateEffects([](IEffect* effect){ auto lights = dynamic_cast<IEffectLights*>(effect); if (lights){ lights->SetLightingEnabled(true); lights->SetPerPixelLighting(true); lights->SetLightEnabled(0, true); lights->SetLightDiffuseColor(0, Colors::Gold); lights->SetLightEnabled(1, false); lights->SetLightEnabled(2, false); } auto fog = dynamic_cast<IEffectFog*>(effect); if (fog){ fog->SetFogEnabled(true); fog->SetFogColor(Colors::CornflowerBlue); fog->SetFogStart(3.f); fog->SetFogEnd(4.f); } }); The above code is designed to build and run our cup with the colored light, per pixel rather than vertex lighting and the fogging was enabled. Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2298, "text": "Source assets which is required for models stored in Autodesk FBX, Wavefront OBJ or other formats. A typical build process is used for conversion which is used in run-time friendly format which is easy to load and render." }, { "code": null, "e": 2725, "s": 2520, "text": "For creating a model, Visual Studio includes a built-in system which includes a convert format of a Wavefront OBJ or Autodesk FBX which is considered as a part of the build process which is needed to CMO." }, { "code": null, "e": 2914, "s": 2725, "text": "In this chapter, we will make use of the DirectXMesh meshconvert command line tool. The developer can start this activity by saving cup.obj, cup.mtl and cup.jpg into the project directory." }, { "code": null, "e": 2971, "s": 2914, "text": "Following steps are required to implement the modeling −" }, { "code": null, "e": 3084, "s": 2971, "text": "Download the Meshconvert.exe from the official site and save the executable file into the user’s project folder." }, { "code": null, "e": 3219, "s": 3084, "text": "Open the required command prompt and then change the project’s directory. Run the following command executed in below command prompt −" }, { "code": null, "e": 3263, "s": 3219, "text": "meshconvert cup._obj -cmo -nodds -flipz -y\n" }, { "code": null, "e": 3379, "s": 3263, "text": "With this, you can initiate a model creation. Now let us focus on updating effects settings on the mentioned model." }, { "code": null, "e": 3574, "s": 3379, "text": "The model class creates the required effects automatically for the loaded materials which are set to lighting parameters. The updating procedure is possible with the Model::UpdateEffects method." }, { "code": null, "e": 3656, "s": 3574, "text": "Following are the steps required to update effects settings in a specific model −" }, { "code": null, "e": 3870, "s": 3656, "text": "From the drop-down menu, select Project/Properties. Set to \"All Configurations\"/\"All Platforms\". On the left-hand tree view, select C/C++ Language. Then set \"Enable Run-Time Type Information\" to \"Yes\". Click \"OK\"." }, { "code": null, "e": 3948, "s": 3870, "text": "In the mentioned file Game.cpp, add the TODO of CreateDevice as shown below −" }, { "code": null, "e": 4531, "s": 3948, "text": "m_model->UpdateEffects([](IEffect* effect){\n auto lights = dynamic_cast<IEffectLights*>(effect);\n if (lights){\n lights->SetLightingEnabled(true);\n lights->SetPerPixelLighting(true);\n lights->SetLightEnabled(0, true);\n lights->SetLightDiffuseColor(0, Colors::Gold);\n lights->SetLightEnabled(1, false);\n lights->SetLightEnabled(2, false);\n }\n auto fog = dynamic_cast<IEffectFog*>(effect);\n if (fog){\n fog->SetFogEnabled(true);\n fog->SetFogColor(Colors::CornflowerBlue);\n fog->SetFogStart(3.f);\n fog->SetFogEnd(4.f);\n }\n});" }, { "code": null, "e": 4674, "s": 4531, "text": "The above code is designed to build and run our cup with the colored light, per pixel rather than vertex lighting and the fogging was enabled." }, { "code": null, "e": 4681, "s": 4674, "text": " Print" }, { "code": null, "e": 4692, "s": 4681, "text": " Add Notes" } ]
MySQL query to find all rows where string contains less than four characters?
Use CHAR_LENGTH() and find the count of characters in every string and then get the strings which are less than four characters. Let us first create a table − mysql> create table DemoTable -> ( -> Name varchar(100) -> ); Query OK, 0 rows affected (1.38 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Bob'); Query OK, 1 row affected (1.60 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (1.83 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.32 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------+ | Name | +-------+ | John | | Bob | | Carol | | David | | Sam | +-------+ 5 rows in set (0.00 sec) Following is the query to find all rows where string contains less than four characters − mysql> select *from DemoTable where CHAR_LENGTH(Name) < 4; This will produce the following output − +------+ | Name | +------+ | Bob | | Sam | +------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1221, "s": 1062, "text": "Use CHAR_LENGTH() and find the count of characters in every string and then get the strings which are less than four characters. Let us first create a table −" }, { "code": null, "e": 1329, "s": 1221, "text": "mysql> create table DemoTable\n -> (\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (1.38 sec)" }, { "code": null, "e": 1385, "s": 1329, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1794, "s": 1385, "text": "mysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values('Bob');\nQuery OK, 1 row affected (1.60 sec)\n\nmysql> insert into DemoTable values('Carol');\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into DemoTable values('David');\nQuery OK, 1 row affected (1.83 sec)\n\nmysql> insert into DemoTable values('Sam');\nQuery OK, 1 row affected (0.32 sec)" }, { "code": null, "e": 1854, "s": 1794, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1885, "s": 1854, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1926, "s": 1885, "text": "This will produce the following output −" }, { "code": null, "e": 2041, "s": 1926, "text": "+-------+\n| Name |\n+-------+\n| John |\n| Bob |\n| Carol |\n| David |\n| Sam |\n+-------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2131, "s": 2041, "text": "Following is the query to find all rows where string contains less than four characters −" }, { "code": null, "e": 2190, "s": 2131, "text": "mysql> select *from DemoTable where CHAR_LENGTH(Name) < 4;" }, { "code": null, "e": 2231, "s": 2190, "text": "This will produce the following output −" }, { "code": null, "e": 2310, "s": 2231, "text": "+------+\n| Name |\n+------+\n| Bob |\n| Sam |\n+------+\n2 rows in set (0.00 sec)" } ]
How to set a value in a particular JTable cell with Java?
Let’s say initially our table is the following with a specific cell [2,1] with value “Kane” − The following is an example to set a new value to the above table. Here, we will update the cell [2,1] − table.setValueAt("Guptill", 2, 1); Let us see the complete example − package my; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); table.setShowHorizontalLines(true); table.setGridColor(Color.orange); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setValueAt("Guptill", 2, 1); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } } The output is as follows with the updated value “Guptill” in the cell [2,1]. We initialized that particular table cell with value “Kane”, but using the setValueAt() method, we have updated it successfully with “Guptill” as shown below −
[ { "code": null, "e": 1156, "s": 1062, "text": "Let’s say initially our table is the following with a specific cell [2,1] with value “Kane” −" }, { "code": null, "e": 1261, "s": 1156, "text": "The following is an example to set a new value to the above table. Here, we will update the cell [2,1] −" }, { "code": null, "e": 1296, "s": 1261, "text": "table.setValueAt(\"Guptill\", 2, 1);" }, { "code": null, "e": 1330, "s": 1296, "text": "Let us see the complete example −" }, { "code": null, "e": 2561, "s": 1330, "text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.ListSelectionModel;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER,\n TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n table.setShowHorizontalLines(true);\n table.setGridColor(Color.orange);\n table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);\n table.setValueAt(\"Guptill\", 2, 1);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2798, "s": 2561, "text": "The output is as follows with the updated value “Guptill” in the cell [2,1]. We initialized that particular table cell with value “Kane”, but using the setValueAt() method, we have updated it successfully with “Guptill” as shown below −" } ]
Find the final sequence of the array after performing given operations - GeeksforGeeks
28 May, 2021 Given an array arr[] of size N, the task is to perform the following operation exactly N times, Create an empty list of integers b[] and in the ith operation, Append arr[i] to the end of b[].Reverse the elements in b[]. Append arr[i] to the end of b[]. Reverse the elements in b[]. Finally, print the contents of the list b[] after the end of all operations.Examples: Input: arr[] = {1, 2, 3, 4} Output: 4 2 1 3 Input: arr[] = {1, 2, 3} Output: 3 1 2 Approach: We need some observations to solve this problem. Suppose the number of elements in the array is even. Say our array is {4, 8, 6, 1, 7, 9}. After carefully observing, we conclude that for even size of elements in the array the numbers which are at even positions (index 1 based) are reversed and added at the beginning and the numbers which are at the odd positions are kept in same order and added in the end.While for odd-sized arrays, the elements at odd positions are reversed and added at the beginning while elements in the array at even positions are kept same and added in the end.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that generates the// array b[] when n is evenvoid solveEven(int n, int* arr, int* b){ int left = n - 1; // Fill the first half of the final array // with reversed sequence for (int i = 0; i < (n / 2); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 0; for (int i = n / 2; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function that generates the// array b[] when n is oddvoid solveOdd(int n, int* arr, int* b){ // Fill the first half of the final array // with reversed sequence int left = n - 1; for (int i = 0; i < (n / 2) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 1; for (int i = (n / 2) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function to find the final array b[]// after n operations of given typevoid solve(int n, int* arr){ // Create the array b int b[n]; // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (int i = 0; i <= n - 1; ++i) { cout << b[i] << " "; }} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); solve(n, arr); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ // Function that generates the// array b[] when n is evenstatic void solveEven(int n, int arr[], int b[]){ int left = n - 1; // Fill the first half of the final array // with reversed sequence for (int i = 0; i < (n / 2); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 0; for (int i = n / 2; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function that generates the// array b[] when n is oddstatic void solveOdd(int n, int arr[], int b[]){ // Fill the first half of the final array // with reversed sequence int left = n - 1; for (int i = 0; i < (n / 2) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 1; for (int i = (n / 2) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function to find the final array b[]// after n operations of given typestatic void solve(int n, int arr[]){ // Create the array b int b[] = new int[n]; // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (int i = 0; i <= n - 1; ++i) { System.out.print( b[i] + " "); }} // Driver codepublic static void main (String[] args){ int []arr = { 1, 2, 3, 4 }; int n = arr.length; solve(n, arr);}} // This code is contributed by anuj_67.. # Python 3 implementation of the approach # Function that generates the# array b[] when n is evendef solveEven(n, arr, b): left = n - 1 # Fill the first half of the final array # with reversed sequence for i in range((n // 2)): b[i] = arr[left] left = left - 2 if (left < 0): break # Fill the second half right = 0 for i in range(n // 2, n, 1): b[i] = arr[right] right = right + 2 if (right > n - 2): break # Function that generates the# array b[] when n is odddef solveOdd(n, arr, b): # Fill the first half of the final array # with reversed sequence left = n - 1 for i in range(n // 2 + 1): b[i] = arr[left] left = left - 2 if (left < 0): break # Fill the second half right = 1 for i in range(n // 2 + 1, n, 1): b[i] = arr[right] right = right + 2 if (right > n - 2): break # Function to find the final array b[]# after n operations of given typedef solve(n, arr): # Create the array b b = [0 for i in range(n)] # If the array size is even if (n % 2 == 0): solveEven(n, arr, b) else: solveOdd(n, arr, b) # Print the final array elements for i in range(n): print(b[i], end = " ") # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4] n = len(arr) solve(n, arr) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function that generates the// array b[] when n is evenstatic void solveEven(int n, int []arr, int []b){ int left = n - 1; // Fill the first half of the final array // with reversed sequence for (int i = 0; i < (n / 2); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 0; for (int i = n / 2; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function that generates the// array b[] when n is oddstatic void solveOdd(int n, int []arr, int []b){ // Fill the first half of the final array // with reversed sequence int left = n - 1; for (int i = 0; i < (n / 2) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 1; for (int i = (n / 2) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function to find the final array b[]// after n operations of given typestatic void solve(int n, int []arr){ // Create the array b int []b = new int[n]; // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (int i = 0; i <= n - 1; ++i) { Console.Write( b[i] + " "); }} // Driver codepublic static void Main (){ int []arr = { 1, 2, 3, 4 }; int n = arr.Length; solve(n, arr);}} // This code is contributed by anuj_67.. <script> // Javascript implementation of the approach // Function that generates the // array b[] when n is even function solveEven(n, arr, b) { let left = n - 1; // Fill the first half of the final array // with reversed sequence for (let i = 0; i < parseInt(n / 2, 10); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half let right = 0; for (let i = parseInt(n / 2, 10); i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; } } // Function that generates the // array b[] when n is odd function solveOdd(n, arr, b) { // Fill the first half of the final array // with reversed sequence let left = n - 1; for (let i = 0; i < parseInt(n / 2, 10) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half let right = 1; for (let i = parseInt(n / 2, 10) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; } } // Function to find the final array b[] // after n operations of given type function solve(n, arr) { // Create the array b let b = new Array(n); // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (let i = 0; i <= n - 1; ++i) { document.write( b[i] + " "); } } let arr = [ 1, 2, 3, 4 ]; let n = arr.length; solve(n, arr); </script> 4 2 1 3 Efficient Approach: The last Element of Array will be reversed only once. Last but one element will be reversed twice. Hence it goes to the last position in final result array ie b. Hence we can fill b array by iterating the original array from the end and placing elements at the not filled first index and not filled the last index. The same idea is implemented below. Below is the implementation of the above approach: C++ Java C# Python3 Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; int* solve(int arr[], int n){ static int b[4]; int p = 0; for (int i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr)/sizeof(arr[0]); int *b ; b = solve(arr, n); for(int i = 0; i < n; i++) cout << b[i] << " ";} // This code is contributed by Rajput-Ji // Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG { static int[] solve(int[] arr, int n) { int[] b = new int[n]; int p = 0; for (int i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b; } public static void main(String[] args) { int []arr = { 1, 2, 3, 4 }; int n = arr.length; int[] b = solve(arr, n); System.out.println(Arrays.toString(b)); }} // This code is contributed by Pramod Hosahalli // C# implementation of the approachusing System; class GFG{ static int[] solve(int[] arr, int n) { int[] b = new int[n]; int p = 0; for (int i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b; } // Driver Code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4 }; int n = arr.Length; int[] b = solve(arr, n); Console.WriteLine("[" + String.Join(",", b) + "]"); }} // This code is contributed by Princi Singh # Python3 implementation of the approachdef solve(arr, n): b = [0 for i in range(n)] p = 0 i = n - 1 while i >= 0: b[p] = arr[i] i -= 1 if (i >= 0): b[n - 1 - p] = arr[i] p += 1 i -= 1 return b # Driver Codearr = [1, 2, 3, 4]n = len(arr) b = solve(arr, n) print(b) # This code is contributed by Mohit kumar <script>// javascript implementation of the approach function solve(arr , n) { var b = Array(n).fill(0); var p = 0; for (i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b; } var arr = [ 1, 2, 3, 4 ]; var n = arr.length; var b = solve(arr, n); document.write("["+ b.toString()+ "]"); // This code contributed by aashish1995</script> [4, 2, 1, 3] vt_m PramodHosahalli SURENDRA_GANGWAR princi singh mohit kumar 29 Rajput-Ji aashish1995 divyesh072019 Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers Coin Change | DP-7
[ { "code": null, "e": 24890, "s": 24862, "text": "\n28 May, 2021" }, { "code": null, "e": 25051, "s": 24890, "text": "Given an array arr[] of size N, the task is to perform the following operation exactly N times, Create an empty list of integers b[] and in the ith operation, " }, { "code": null, "e": 25112, "s": 25051, "text": "Append arr[i] to the end of b[].Reverse the elements in b[]." }, { "code": null, "e": 25145, "s": 25112, "text": "Append arr[i] to the end of b[]." }, { "code": null, "e": 25174, "s": 25145, "text": "Reverse the elements in b[]." }, { "code": null, "e": 25262, "s": 25174, "text": "Finally, print the contents of the list b[] after the end of all operations.Examples: " }, { "code": null, "e": 25308, "s": 25262, "text": "Input: arr[] = {1, 2, 3, 4} Output: 4 2 1 3 " }, { "code": null, "e": 25349, "s": 25308, "text": "Input: arr[] = {1, 2, 3} Output: 3 1 2 " }, { "code": null, "e": 25502, "s": 25351, "text": "Approach: We need some observations to solve this problem. Suppose the number of elements in the array is even. Say our array is {4, 8, 6, 1, 7, 9}. " }, { "code": null, "e": 26004, "s": 25502, "text": "After carefully observing, we conclude that for even size of elements in the array the numbers which are at even positions (index 1 based) are reversed and added at the beginning and the numbers which are at the odd positions are kept in same order and added in the end.While for odd-sized arrays, the elements at odd positions are reversed and added at the beginning while elements in the array at even positions are kept same and added in the end.Below is the implementation of the above approach: " }, { "code": null, "e": 26008, "s": 26004, "text": "C++" }, { "code": null, "e": 26013, "s": 26008, "text": "Java" }, { "code": null, "e": 26021, "s": 26013, "text": "Python3" }, { "code": null, "e": 26024, "s": 26021, "text": "C#" }, { "code": null, "e": 26035, "s": 26024, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that generates the// array b[] when n is evenvoid solveEven(int n, int* arr, int* b){ int left = n - 1; // Fill the first half of the final array // with reversed sequence for (int i = 0; i < (n / 2); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 0; for (int i = n / 2; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function that generates the// array b[] when n is oddvoid solveOdd(int n, int* arr, int* b){ // Fill the first half of the final array // with reversed sequence int left = n - 1; for (int i = 0; i < (n / 2) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 1; for (int i = (n / 2) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function to find the final array b[]// after n operations of given typevoid solve(int n, int* arr){ // Create the array b int b[n]; // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (int i = 0; i <= n - 1; ++i) { cout << b[i] << \" \"; }} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); solve(n, arr); return 0;}", "e": 27658, "s": 26035, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function that generates the// array b[] when n is evenstatic void solveEven(int n, int arr[], int b[]){ int left = n - 1; // Fill the first half of the final array // with reversed sequence for (int i = 0; i < (n / 2); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 0; for (int i = n / 2; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function that generates the// array b[] when n is oddstatic void solveOdd(int n, int arr[], int b[]){ // Fill the first half of the final array // with reversed sequence int left = n - 1; for (int i = 0; i < (n / 2) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 1; for (int i = (n / 2) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function to find the final array b[]// after n operations of given typestatic void solve(int n, int arr[]){ // Create the array b int b[] = new int[n]; // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (int i = 0; i <= n - 1; ++i) { System.out.print( b[i] + \" \"); }} // Driver codepublic static void main (String[] args){ int []arr = { 1, 2, 3, 4 }; int n = arr.length; solve(n, arr);}} // This code is contributed by anuj_67..", "e": 29372, "s": 27658, "text": null }, { "code": "# Python 3 implementation of the approach # Function that generates the# array b[] when n is evendef solveEven(n, arr, b): left = n - 1 # Fill the first half of the final array # with reversed sequence for i in range((n // 2)): b[i] = arr[left] left = left - 2 if (left < 0): break # Fill the second half right = 0 for i in range(n // 2, n, 1): b[i] = arr[right] right = right + 2 if (right > n - 2): break # Function that generates the# array b[] when n is odddef solveOdd(n, arr, b): # Fill the first half of the final array # with reversed sequence left = n - 1 for i in range(n // 2 + 1): b[i] = arr[left] left = left - 2 if (left < 0): break # Fill the second half right = 1 for i in range(n // 2 + 1, n, 1): b[i] = arr[right] right = right + 2 if (right > n - 2): break # Function to find the final array b[]# after n operations of given typedef solve(n, arr): # Create the array b b = [0 for i in range(n)] # If the array size is even if (n % 2 == 0): solveEven(n, arr, b) else: solveOdd(n, arr, b) # Print the final array elements for i in range(n): print(b[i], end = \" \") # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4] n = len(arr) solve(n, arr) # This code is contributed by# Surendra_Gangwar", "e": 30824, "s": 29372, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function that generates the// array b[] when n is evenstatic void solveEven(int n, int []arr, int []b){ int left = n - 1; // Fill the first half of the final array // with reversed sequence for (int i = 0; i < (n / 2); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 0; for (int i = n / 2; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function that generates the// array b[] when n is oddstatic void solveOdd(int n, int []arr, int []b){ // Fill the first half of the final array // with reversed sequence int left = n - 1; for (int i = 0; i < (n / 2) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half int right = 1; for (int i = (n / 2) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; }} // Function to find the final array b[]// after n operations of given typestatic void solve(int n, int []arr){ // Create the array b int []b = new int[n]; // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (int i = 0; i <= n - 1; ++i) { Console.Write( b[i] + \" \"); }} // Driver codepublic static void Main (){ int []arr = { 1, 2, 3, 4 }; int n = arr.Length; solve(n, arr);}} // This code is contributed by anuj_67..", "e": 32544, "s": 30824, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that generates the // array b[] when n is even function solveEven(n, arr, b) { let left = n - 1; // Fill the first half of the final array // with reversed sequence for (let i = 0; i < parseInt(n / 2, 10); ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half let right = 0; for (let i = parseInt(n / 2, 10); i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; } } // Function that generates the // array b[] when n is odd function solveOdd(n, arr, b) { // Fill the first half of the final array // with reversed sequence let left = n - 1; for (let i = 0; i < parseInt(n / 2, 10) + 1; ++i) { b[i] = arr[left]; left = left - 2; if (left < 0) break; } // Fill the second half let right = 1; for (let i = parseInt(n / 2, 10) + 1; i <= n - 1; ++i) { b[i] = arr[right]; right = right + 2; if (right > n - 2) break; } } // Function to find the final array b[] // after n operations of given type function solve(n, arr) { // Create the array b let b = new Array(n); // If the array size is even if (n % 2 == 0) solveEven(n, arr, b); else solveOdd(n, arr, b); // Print the final array elements for (let i = 0; i <= n - 1; ++i) { document.write( b[i] + \" \"); } } let arr = [ 1, 2, 3, 4 ]; let n = arr.length; solve(n, arr); </script>", "e": 34425, "s": 32544, "text": null }, { "code": null, "e": 34433, "s": 34425, "text": "4 2 1 3" }, { "code": null, "e": 34859, "s": 34435, "text": "Efficient Approach: The last Element of Array will be reversed only once. Last but one element will be reversed twice. Hence it goes to the last position in final result array ie b. Hence we can fill b array by iterating the original array from the end and placing elements at the not filled first index and not filled the last index. The same idea is implemented below. Below is the implementation of the above approach: " }, { "code": null, "e": 34863, "s": 34859, "text": "C++" }, { "code": null, "e": 34868, "s": 34863, "text": "Java" }, { "code": null, "e": 34871, "s": 34868, "text": "C#" }, { "code": null, "e": 34879, "s": 34871, "text": "Python3" }, { "code": null, "e": 34890, "s": 34879, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; int* solve(int arr[], int n){ static int b[4]; int p = 0; for (int i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr)/sizeof(arr[0]); int *b ; b = solve(arr, n); for(int i = 0; i < n; i++) cout << b[i] << \" \";} // This code is contributed by Rajput-Ji", "e": 35415, "s": 34890, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG { static int[] solve(int[] arr, int n) { int[] b = new int[n]; int p = 0; for (int i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b; } public static void main(String[] args) { int []arr = { 1, 2, 3, 4 }; int n = arr.length; int[] b = solve(arr, n); System.out.println(Arrays.toString(b)); }} // This code is contributed by Pramod Hosahalli", "e": 36050, "s": 35415, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int[] solve(int[] arr, int n) { int[] b = new int[n]; int p = 0; for (int i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b; } // Driver Code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4 }; int n = arr.Length; int[] b = solve(arr, n); Console.WriteLine(\"[\" + String.Join(\",\", b) + \"]\"); }} // This code is contributed by Princi Singh", "e": 36679, "s": 36050, "text": null }, { "code": "# Python3 implementation of the approachdef solve(arr, n): b = [0 for i in range(n)] p = 0 i = n - 1 while i >= 0: b[p] = arr[i] i -= 1 if (i >= 0): b[n - 1 - p] = arr[i] p += 1 i -= 1 return b # Driver Codearr = [1, 2, 3, 4]n = len(arr) b = solve(arr, n) print(b) # This code is contributed by Mohit kumar", "e": 37047, "s": 36679, "text": null }, { "code": "<script>// javascript implementation of the approach function solve(arr , n) { var b = Array(n).fill(0); var p = 0; for (i = n - 1; i >= 0; i--) { b[p] = arr[i--]; if (i >= 0) b[n - 1 - p] = arr[i]; p++; } return b; } var arr = [ 1, 2, 3, 4 ]; var n = arr.length; var b = solve(arr, n); document.write(\"[\"+ b.toString()+ \"]\"); // This code contributed by aashish1995</script>", "e": 37548, "s": 37047, "text": null }, { "code": null, "e": 37561, "s": 37548, "text": "[4, 2, 1, 3]" }, { "code": null, "e": 37568, "s": 37563, "text": "vt_m" }, { "code": null, "e": 37584, "s": 37568, "text": "PramodHosahalli" }, { "code": null, "e": 37601, "s": 37584, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 37614, "s": 37601, "text": "princi singh" }, { "code": null, "e": 37629, "s": 37614, "text": "mohit kumar 29" }, { "code": null, "e": 37639, "s": 37629, "text": "Rajput-Ji" }, { "code": null, "e": 37651, "s": 37639, "text": "aashish1995" }, { "code": null, "e": 37665, "s": 37651, "text": "divyesh072019" }, { "code": null, "e": 37672, "s": 37665, "text": "Arrays" }, { "code": null, "e": 37685, "s": 37672, "text": "Mathematical" }, { "code": null, "e": 37692, "s": 37685, "text": "Arrays" }, { "code": null, "e": 37705, "s": 37692, "text": "Mathematical" }, { "code": null, "e": 37803, "s": 37705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37812, "s": 37803, "text": "Comments" }, { "code": null, "e": 37825, "s": 37812, "text": "Old Comments" }, { "code": null, "e": 37873, "s": 37825, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37917, "s": 37873, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37940, "s": 37917, "text": "Introduction to Arrays" }, { "code": null, "e": 37972, "s": 37940, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37986, "s": 37972, "text": "Linear Search" }, { "code": null, "e": 38016, "s": 37986, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 38031, "s": 38016, "text": "C++ Data Types" }, { "code": null, "e": 38074, "s": 38031, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 38116, "s": 38074, "text": "Program to find GCD or HCF of two numbers" } ]
How to save canvas data to file in HTML5?
A Canvas is just a rectangular area on the HTML page. We can draw graphics in this rectangular area (Canvas) with the help of JavaScript. Canvas can be created in HTML5 as − <canvas id = ”canvas1” width = ”250” height = ”150”></canvas> This creates an empty canvas with name canvas1 with width=200 and height=100. To draw graphics in it, we use JavaScript − var canvas = document.getElementById("Canvas1"); var ctx1 = canvas.getContext("2d"); ctx1.moveTo(0,0); ctx1.lineTo(300,200); ctx1.stroke(); // This method actually draw graphics as per context object To save this graphic, we need to save it as some data url like img.png or img.jpg For this, we will write − var imgurl= canvas.toDataURL( ) ; / / This method saves graphics in png document.getElementById(‘cimg’).src = imgurl; // This will set img src to dataurl(png) so that it can be saved as image. In this way, we can save canvas data to file in HTML5.
[ { "code": null, "e": 1200, "s": 1062, "text": "A Canvas is just a rectangular area on the HTML page. We can draw graphics in this rectangular area (Canvas) with the help of JavaScript." }, { "code": null, "e": 1237, "s": 1200, "text": " Canvas can be created in HTML5 as −" }, { "code": null, "e": 1332, "s": 1237, "text": "<canvas id = ”canvas1” width = ”250” height = ”150”></canvas> " }, { "code": null, "e": 1410, "s": 1332, "text": "This creates an empty canvas with name canvas1 with width=200 and height=100." }, { "code": null, "e": 1455, "s": 1410, "text": " To draw graphics in it, we use JavaScript −" }, { "code": null, "e": 1670, "s": 1455, "text": "var canvas = document.getElementById(\"Canvas1\");\n var ctx1 = canvas.getContext(\"2d\");\nctx1.moveTo(0,0); ctx1.lineTo(300,200);\n ctx1.stroke(); // This method actually draw graphics as per context object " }, { "code": null, "e": 1752, "s": 1670, "text": "To save this graphic, we need to save it as some data url like img.png or img.jpg" }, { "code": null, "e": 1778, "s": 1752, "text": "For this, we will write −" }, { "code": null, "e": 1971, "s": 1778, "text": "var imgurl= canvas.toDataURL( ) ; / / This method saves graphics in png\ndocument.getElementById(‘cimg’).src = imgurl; // This will set img src to dataurl(png)\nso that it can be saved as image." }, { "code": null, "e": 2026, "s": 1971, "text": "In this way, we can save canvas data to file in HTML5." } ]
Java Program to Find the Length/Size of an ArrayList
28 Oct, 2021 Given an ArrayList in Java, the task is to write a Java program to find the length or size of the ArrayList. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: 5 Input: ArrayList: [geeks, for, geeks] Output: 3 ArrayList – An ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. However, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The size of the ArrayList can be determined easily with the help of the size() method. This method does not take any parameters and returns an integer value which is the size of the ArrayList. Syntax: int size = ArrayList.size(); Below is the implementation of the above approach: Example 1 – Java Program to determine the size of an Integer ArrayList Java // Java program to find the size// of an ArrayList import java.util.*; public class GFG { public static void main(String[] args) throws Exception { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println("ArrayList: " + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println("Size of ArrayList = " + size); }} ArrayList: [1, 2, 3, 4, 5] Size of ArrayList = 5 Example 2 – Java Program to determine the size of a String ArrayList Java // Java program to find the size// of an String ArrayList import java.util.*; public class GFG { public static void main(String[] args) throws Exception { // Creating object of ArrayList<Integer> ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist arrlist.add("GeeksforGeeks"); arrlist.add("a"); arrlist.add("computer"); arrlist.add("science"); arrlist.add("portal"); arrlist.add("for"); arrlist.add("geeks"); // print arrlist System.out.println("ArrayList: " + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println("Size of ArrayList = " + size); }} ArrayList: [GeeksforGeeks, a, computer, science, portal, for, geeks] Size of ArrayList = 7 nishkarshgandhi Java-ArrayList Java-Collections Java-List-Programs Java Java Java-Collections 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 ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Set in Java Singleton Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 137, "s": 28, "text": "Given an ArrayList in Java, the task is to write a Java program to find the length or size of the ArrayList." }, { "code": null, "e": 148, "s": 137, "text": "Examples: " }, { "code": null, "e": 241, "s": 148, "text": "Input: ArrayList: [1, 2, 3, 4, 5]\nOutput: 5\n\nInput: ArrayList: [geeks, for, geeks]\nOutput: 3" }, { "code": null, "e": 514, "s": 241, "text": "ArrayList – An ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. However, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed." }, { "code": null, "e": 707, "s": 514, "text": "The size of the ArrayList can be determined easily with the help of the size() method. This method does not take any parameters and returns an integer value which is the size of the ArrayList." }, { "code": null, "e": 716, "s": 707, "text": "Syntax: " }, { "code": null, "e": 745, "s": 716, "text": "int size = ArrayList.size();" }, { "code": null, "e": 796, "s": 745, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 867, "s": 796, "text": "Example 1 – Java Program to determine the size of an Integer ArrayList" }, { "code": null, "e": 872, "s": 867, "text": "Java" }, { "code": "// Java program to find the size// of an ArrayList import java.util.*; public class GFG { public static void main(String[] args) throws Exception { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println(\"ArrayList: \" + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println(\"Size of ArrayList = \" + size); }}", "e": 1642, "s": 872, "text": null }, { "code": null, "e": 1691, "s": 1642, "text": "ArrayList: [1, 2, 3, 4, 5]\nSize of ArrayList = 5" }, { "code": null, "e": 1760, "s": 1691, "text": "Example 2 – Java Program to determine the size of a String ArrayList" }, { "code": null, "e": 1765, "s": 1760, "text": "Java" }, { "code": "// Java program to find the size// of an String ArrayList import java.util.*; public class GFG { public static void main(String[] args) throws Exception { // Creating object of ArrayList<Integer> ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist arrlist.add(\"GeeksforGeeks\"); arrlist.add(\"a\"); arrlist.add(\"computer\"); arrlist.add(\"science\"); arrlist.add(\"portal\"); arrlist.add(\"for\"); arrlist.add(\"geeks\"); // print arrlist System.out.println(\"ArrayList: \" + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println(\"Size of ArrayList = \" + size); }}", "e": 2642, "s": 1765, "text": null }, { "code": null, "e": 2733, "s": 2642, "text": "ArrayList: [GeeksforGeeks, a, computer, science, portal, for, geeks]\nSize of ArrayList = 7" }, { "code": null, "e": 2749, "s": 2733, "text": "nishkarshgandhi" }, { "code": null, "e": 2764, "s": 2749, "text": "Java-ArrayList" }, { "code": null, "e": 2781, "s": 2764, "text": "Java-Collections" }, { "code": null, "e": 2800, "s": 2781, "text": "Java-List-Programs" }, { "code": null, "e": 2805, "s": 2800, "text": "Java" }, { "code": null, "e": 2810, "s": 2805, "text": "Java" }, { "code": null, "e": 2827, "s": 2810, "text": "Java-Collections" }, { "code": null, "e": 2925, "s": 2827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2976, "s": 2925, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3007, "s": 2976, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3026, "s": 3007, "text": "Interfaces in Java" }, { "code": null, "e": 3056, "s": 3026, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3074, "s": 3056, "text": "ArrayList in Java" }, { "code": null, "e": 3094, "s": 3074, "text": "Collections in Java" }, { "code": null, "e": 3126, "s": 3094, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3141, "s": 3126, "text": "Stream In Java" }, { "code": null, "e": 3153, "s": 3141, "text": "Set in Java" } ]
MathWorks Interview Experience for Internship (On-Campus)
06 Oct, 2020 MathWorks visited our college for summer internship 2021. Students from CSE/ECE/EE with CGPA>=7 were eligible to give the online test. Round 1: It consisted of 12 MCQ questions and 2 coding questions and a duration of 60 minutes. The test was conducted on HackerRank. The MCQ questions mainly focussed on time complexities, data structures, and OOPS concepts with an easy to medium level of difficulty. We were asked to choose 2 different languages (C/C++/Java) for the two coding questions. The questions were as follows: Given an array S, generate two subsets A and B such that the intersection of A and B is an empty set and their union gives the original array S. In addition, the sum of elements of A has to be greater than the sum of elements of B and number of elements in A is minimum. Return the sorted array A. If multiple such A’s are possible, return the sorted set A that has a maximal sum.Input : n=5 3 7 5 6 2 Output: 6 7 Explanation: One possibility is A=[5,7] and B=[3,6,2]. Another possibility is A=[6,7] and B=[2,3,5]. Since the sum of A is maximum in the second case, return the array [6,7]. Input : n=5 3 7 5 6 2 Output: 6 7 Explanation: One possibility is A=[5,7] and B=[3,6,2]. Another possibility is A=[6,7] and B=[2,3,5]. Since the sum of A is maximum in the second case, return the array [6,7]. The minimum number of moves to make all array elements equal. The shortlisted students were called for the interview rounds the next day. The interviews were held on MS Teams. There were two rounds(Managerial and HR rounds) and the order of rounds can be different for each candidate. Round 2 (HR Round): I was asked to start with my introduction and then I was asked the standard HR questions and a few questions on my projects. This was for around 30 minutes. Round 3 (Managerial Round): There were many questions like how I can be a good team player, etc and for each question, the interviewer expected me to support it with real-life instances. I was not prepared in advance about any of these questions but I answered them very genuinely. (It is advisable to be prepared well in advance for such questions but even if you’re not, be confident and answer them genuinely). I was asked in detail about the projects that I had and the challenges I faced. This round went on for more than 30 minutes. Tips : Be confident during the interviews. Refer to GFG interview experiences which will be super helpful if you are sitting for any interviews. Be calm and even if you are rejected, learn from your mistakes, and most importantly, never give up. Marketing MathWorks On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2020" }, { "code": null, "e": 164, "s": 28, "text": "MathWorks visited our college for summer internship 2021. Students from CSE/ECE/EE with CGPA>=7 were eligible to give the online test. " }, { "code": null, "e": 553, "s": 164, "text": "Round 1: It consisted of 12 MCQ questions and 2 coding questions and a duration of 60 minutes. The test was conducted on HackerRank. The MCQ questions mainly focussed on time complexities, data structures, and OOPS concepts with an easy to medium level of difficulty. We were asked to choose 2 different languages (C/C++/Java) for the two coding questions. The questions were as follows:" }, { "code": null, "e": 1163, "s": 553, "text": "Given an array S, generate two subsets A and B such that the intersection of A and B is an empty set and their union gives the original array S. In addition, the sum of elements of A has to be greater than the sum of elements of B and number of elements in A is minimum. Return the sorted array A. If multiple such A’s are possible, return the sorted set A that has a maximal sum.Input : n=5\n 3 7 5 6 2\n \nOutput: 6 7\nExplanation: One possibility is A=[5,7] and B=[3,6,2]. Another possibility is A=[6,7] and B=[2,3,5]. Since the sum of A is maximum in the second case, return the array [6,7]." }, { "code": null, "e": 1207, "s": 1163, "text": "Input : n=5\n 3 7 5 6 2\n \nOutput: 6 7\n" }, { "code": null, "e": 1394, "s": 1207, "text": "Explanation: One possibility is A=[5,7] and B=[3,6,2]. Another possibility is A=[6,7] and B=[2,3,5]. Since the sum of A is maximum in the second case, return the array [6,7]." }, { "code": null, "e": 1456, "s": 1394, "text": "The minimum number of moves to make all array elements equal." }, { "code": null, "e": 1679, "s": 1456, "text": "The shortlisted students were called for the interview rounds the next day. The interviews were held on MS Teams. There were two rounds(Managerial and HR rounds) and the order of rounds can be different for each candidate." }, { "code": null, "e": 1699, "s": 1679, "text": "Round 2 (HR Round):" }, { "code": null, "e": 1824, "s": 1699, "text": "I was asked to start with my introduction and then I was asked the standard HR questions and a few questions on my projects." }, { "code": null, "e": 1856, "s": 1824, "text": "This was for around 30 minutes." }, { "code": null, "e": 1884, "s": 1856, "text": "Round 3 (Managerial Round):" }, { "code": null, "e": 2270, "s": 1884, "text": "There were many questions like how I can be a good team player, etc and for each question, the interviewer expected me to support it with real-life instances. I was not prepared in advance about any of these questions but I answered them very genuinely. (It is advisable to be prepared well in advance for such questions but even if you’re not, be confident and answer them genuinely)." }, { "code": null, "e": 2350, "s": 2270, "text": "I was asked in detail about the projects that I had and the challenges I faced." }, { "code": null, "e": 2395, "s": 2350, "text": "This round went on for more than 30 minutes." }, { "code": null, "e": 2403, "s": 2395, "text": "Tips : " }, { "code": null, "e": 2439, "s": 2403, "text": "Be confident during the interviews." }, { "code": null, "e": 2541, "s": 2439, "text": "Refer to GFG interview experiences which will be super helpful if you are sitting for any interviews." }, { "code": null, "e": 2642, "s": 2541, "text": "Be calm and even if you are rejected, learn from your mistakes, and most importantly, never give up." }, { "code": null, "e": 2652, "s": 2642, "text": "Marketing" }, { "code": null, "e": 2662, "s": 2652, "text": "MathWorks" }, { "code": null, "e": 2672, "s": 2662, "text": "On-Campus" }, { "code": null, "e": 2694, "s": 2672, "text": "Interview Experiences" } ]
Implementing JOI Module in ReactJS
21 Sep, 2021 Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data. Advantages of Using JOI over Javascript validations: It’s easy to get started and easy to use. It is widely used and popular module for data validation. It supports schema based validation. Step 1: Create react app using the following command. npx create-react-app my-first-app Step 2: Change directory to that folder by executing command : cd my-first-app Step 3: Install the necessary dependencies. Go to the directory ‘src’ and execute command prompt there and run command npm install joi File Structure: It will look like the following. Step 4: Now we will create a form for a customer and add validations to it. Customer Form will contain fields like: In the below file, we will create a form containing various fields like firstName, lastName, Pin, Date of Birth, and email. Then create a schema then defined Joi validations. If any error is caught, then various div are created to display error. CustomerForm.jsx import React, { useState } from "react";import Joi from "joi-browser";import { toast } from "react-toastify";function CustomerForm(props) { const [customer, setCustomer] = useState({ firstName: "", lastName: "", email: "", pin: 0, birthdate: "", }); const [errors, setErrors] = useState({}); const schema = { firstName: Joi.string().min(1).max(20).required(), lastName: Joi.string().required(), email: Joi.string().email().required(), pin: Joi.number().min(1000).max(9999).required(), birthdate: Joi.date().min("2001-01-01").required(), }; const validateForm = (event) => { event.preventDefault(); const result = Joi.validate(customer, schema, { abortEarly: false }); console.log(result); const { error } = result; if (!error) { return null; } else { const errorData = {}; for (let item of error.details) { const name = item.path[0]; const message = item.message; errorData[name] = message; } console.log(errors); setErrors(errorData); return errorData; } }; const handleSave = (event) => { const { name, value } = event.target; let errorData = { ...errors }; const errorMessage = validateProperty(event); if (errorMessage) { errorData[name] = errorMessage; } else { delete errorData[name]; } let customerData = { ...customer }; customerData[name] = value; setCustomer(customerData); setErrors(errorData); }; const validateProperty = (event) => { const { name, value } = event.target; const obj = { [name]: value }; const subSchema = { [name]: schema[name] }; const result = Joi.validate(obj, subSchema); const { error } = result; return error ? error.details[0].message : null; }; const clearState = () => { setCustomer({ firstName: "", lastName: "", email: "", pin: 0, birthdate: "", }); }; return ( <div> <h3>Add Customer</h3> <hr /> <form className="ui form"> <div className="form-group"> <label>First Name</label> <input type="text" name="firstName" className="form-control" value={customer.firstName} onChange={handleSave} /> </div> {errors.firstName && ( <div className="alert alert-danger"> {errors.firstName} </div> )} <div className="form-group"> <label>Last Name</label> <input type="text" name="lastName" className="form-control" value={customer.lastName} onChange={handleSave} /> </div> {errors.lastName && ( <div className="alert alert-danger"> {errors.lastName} </div> )} <div className="form-group"> <label>Email</label> <input type="email" name="email" className="form-control" value={customer.email} onChange={handleSave} /> </div> {errors.email && ( <div className="alert alert-danger"> {errors.email} </div> )} <div className="form-group"> <label>PIN</label> <input type="number" name="pin" className="form-control" value={customer.pin} onChange={handleSave} /> </div> <div className="form-group"> <label>Date of Birth</label> <input type="date" name="dob" className="form-control" value={customer.dob} onChange={handleSave} /> </div> {errors.birthdate && ( <div className="alert alert-danger"> {errors.birthdate} </div> )} <div className="btn"> <button type="submit" onClick={validateForm} className="btn btn-success" > Add customer </button> </div> </form> </div> );} export default CustomerForm; Step 5: Create ValidationJoiHome component and import CustomerForm here. In this component, simply CustomerForm is imported. ValidationJoiHome.jsx import React from "react";import CustomerForm from "./CustomerForm";function ValidationJoiHome() { return ( <div> GeeksforGeeks: Validation Joi Home <CustomerForm /> </div> );}export default ValidationJoiHome; Step 6: Add ValidationJoiHome component in App.js Name:App.js import ValidationJoiHome from "./ValidationJoi/ValidationJoiHome"; function App() { return ( <div className="App"> <ValidationJoiHome /> </div> );} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Blogathon-2021 React-Questions Blogathon ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 282, "s": 28, "text": "Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data." }, { "code": null, "e": 336, "s": 282, "text": "Advantages of Using JOI over Javascript validations: " }, { "code": null, "e": 378, "s": 336, "text": "It’s easy to get started and easy to use." }, { "code": null, "e": 436, "s": 378, "text": "It is widely used and popular module for data validation." }, { "code": null, "e": 473, "s": 436, "text": "It supports schema based validation." }, { "code": null, "e": 527, "s": 473, "text": "Step 1: Create react app using the following command." }, { "code": null, "e": 561, "s": 527, "text": "npx create-react-app my-first-app" }, { "code": null, "e": 624, "s": 561, "text": "Step 2: Change directory to that folder by executing command :" }, { "code": null, "e": 640, "s": 624, "text": "cd my-first-app" }, { "code": null, "e": 761, "s": 642, "text": "Step 3: Install the necessary dependencies. Go to the directory ‘src’ and execute command prompt there and run command" }, { "code": null, "e": 777, "s": 761, "text": "npm install joi" }, { "code": null, "e": 827, "s": 777, "text": "File Structure: It will look like the following. " }, { "code": null, "e": 944, "s": 827, "text": "Step 4: Now we will create a form for a customer and add validations to it. Customer Form will contain fields like:" }, { "code": null, "e": 1190, "s": 944, "text": "In the below file, we will create a form containing various fields like firstName, lastName, Pin, Date of Birth, and email. Then create a schema then defined Joi validations. If any error is caught, then various div are created to display error." }, { "code": null, "e": 1207, "s": 1190, "text": "CustomerForm.jsx" }, { "code": "import React, { useState } from \"react\";import Joi from \"joi-browser\";import { toast } from \"react-toastify\";function CustomerForm(props) { const [customer, setCustomer] = useState({ firstName: \"\", lastName: \"\", email: \"\", pin: 0, birthdate: \"\", }); const [errors, setErrors] = useState({}); const schema = { firstName: Joi.string().min(1).max(20).required(), lastName: Joi.string().required(), email: Joi.string().email().required(), pin: Joi.number().min(1000).max(9999).required(), birthdate: Joi.date().min(\"2001-01-01\").required(), }; const validateForm = (event) => { event.preventDefault(); const result = Joi.validate(customer, schema, { abortEarly: false }); console.log(result); const { error } = result; if (!error) { return null; } else { const errorData = {}; for (let item of error.details) { const name = item.path[0]; const message = item.message; errorData[name] = message; } console.log(errors); setErrors(errorData); return errorData; } }; const handleSave = (event) => { const { name, value } = event.target; let errorData = { ...errors }; const errorMessage = validateProperty(event); if (errorMessage) { errorData[name] = errorMessage; } else { delete errorData[name]; } let customerData = { ...customer }; customerData[name] = value; setCustomer(customerData); setErrors(errorData); }; const validateProperty = (event) => { const { name, value } = event.target; const obj = { [name]: value }; const subSchema = { [name]: schema[name] }; const result = Joi.validate(obj, subSchema); const { error } = result; return error ? error.details[0].message : null; }; const clearState = () => { setCustomer({ firstName: \"\", lastName: \"\", email: \"\", pin: 0, birthdate: \"\", }); }; return ( <div> <h3>Add Customer</h3> <hr /> <form className=\"ui form\"> <div className=\"form-group\"> <label>First Name</label> <input type=\"text\" name=\"firstName\" className=\"form-control\" value={customer.firstName} onChange={handleSave} /> </div> {errors.firstName && ( <div className=\"alert alert-danger\"> {errors.firstName} </div> )} <div className=\"form-group\"> <label>Last Name</label> <input type=\"text\" name=\"lastName\" className=\"form-control\" value={customer.lastName} onChange={handleSave} /> </div> {errors.lastName && ( <div className=\"alert alert-danger\"> {errors.lastName} </div> )} <div className=\"form-group\"> <label>Email</label> <input type=\"email\" name=\"email\" className=\"form-control\" value={customer.email} onChange={handleSave} /> </div> {errors.email && ( <div className=\"alert alert-danger\"> {errors.email} </div> )} <div className=\"form-group\"> <label>PIN</label> <input type=\"number\" name=\"pin\" className=\"form-control\" value={customer.pin} onChange={handleSave} /> </div> <div className=\"form-group\"> <label>Date of Birth</label> <input type=\"date\" name=\"dob\" className=\"form-control\" value={customer.dob} onChange={handleSave} /> </div> {errors.birthdate && ( <div className=\"alert alert-danger\"> {errors.birthdate} </div> )} <div className=\"btn\"> <button type=\"submit\" onClick={validateForm} className=\"btn btn-success\" > Add customer </button> </div> </form> </div> );} export default CustomerForm;", "e": 5317, "s": 1207, "text": null }, { "code": null, "e": 5443, "s": 5317, "text": "Step 5: Create ValidationJoiHome component and import CustomerForm here. In this component, simply CustomerForm is imported." }, { "code": null, "e": 5465, "s": 5443, "text": "ValidationJoiHome.jsx" }, { "code": "import React from \"react\";import CustomerForm from \"./CustomerForm\";function ValidationJoiHome() { return ( <div> GeeksforGeeks: Validation Joi Home <CustomerForm /> </div> );}export default ValidationJoiHome;", "e": 5693, "s": 5465, "text": null }, { "code": null, "e": 5743, "s": 5693, "text": "Step 6: Add ValidationJoiHome component in App.js" }, { "code": null, "e": 5755, "s": 5743, "text": "Name:App.js" }, { "code": "import ValidationJoiHome from \"./ValidationJoi/ValidationJoiHome\"; function App() { return ( <div className=\"App\"> <ValidationJoiHome /> </div> );} export default App;", "e": 5946, "s": 5755, "text": null }, { "code": null, "e": 6025, "s": 5946, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 6035, "s": 6025, "text": "npm start" }, { "code": null, "e": 6043, "s": 6035, "text": "Output:" }, { "code": null, "e": 6058, "s": 6043, "text": "Blogathon-2021" }, { "code": null, "e": 6074, "s": 6058, "text": "React-Questions" }, { "code": null, "e": 6084, "s": 6074, "text": "Blogathon" }, { "code": null, "e": 6092, "s": 6084, "text": "ReactJS" }, { "code": null, "e": 6109, "s": 6092, "text": "Web Technologies" }, { "code": null, "e": 6207, "s": 6109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6248, "s": 6207, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 6286, "s": 6248, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 6330, "s": 6286, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 6390, "s": 6330, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 6457, "s": 6390, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 6500, "s": 6457, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 6545, "s": 6500, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 6583, "s": 6545, "text": "Axios in React: A Guide for Beginners" } ]
scipy.fftshift() in Python
29 Aug, 2020 With the help of scipy.fftshift() method, we can shift the lower and upper half of vector by using fast fourier transformation and return the shifted vector by using this method. Syntax : scipy.fft.fftshift(x) Return : Return the transformed vector. Example #1 : In this example we can see that by using scipy.fftshift() method, we are able to shift the lower half and upper half of the vector by using fast fourier transformation and return the shifted vector. Python3 # import scipy and numpyimport scipyimport numpy as np x = np.arange(6)# Using scipy.fftfreq() methodgfg = scipy.fft.fftshift(x) print(gfg) Output : [3 4 5 0 1 2] Example #2 : Python3 # import scipy and numpyimport scipyimport numpy as np x = np.arange(11)# Using scipy.fftfreq() methodgfg = scipy.fft.fftshift(x) print(gfg) Output : [ 6 7 8 9 10 0 1 2 3 4 5] Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Python Dictionary Python OOPs Concepts Different ways to create Pandas Dataframe *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Stack in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 207, "s": 28, "text": "With the help of scipy.fftshift() method, we can shift the lower and upper half of vector by using fast fourier transformation and return the shifted vector by using this method." }, { "code": null, "e": 238, "s": 207, "text": "Syntax : scipy.fft.fftshift(x)" }, { "code": null, "e": 278, "s": 238, "text": "Return : Return the transformed vector." }, { "code": null, "e": 291, "s": 278, "text": "Example #1 :" }, { "code": null, "e": 490, "s": 291, "text": "In this example we can see that by using scipy.fftshift() method, we are able to shift the lower half and upper half of the vector by using fast fourier transformation and return the shifted vector." }, { "code": null, "e": 498, "s": 490, "text": "Python3" }, { "code": "# import scipy and numpyimport scipyimport numpy as np x = np.arange(6)# Using scipy.fftfreq() methodgfg = scipy.fft.fftshift(x) print(gfg)", "e": 640, "s": 498, "text": null }, { "code": null, "e": 649, "s": 640, "text": "Output :" }, { "code": null, "e": 663, "s": 649, "text": "[3 4 5 0 1 2]" }, { "code": null, "e": 676, "s": 663, "text": "Example #2 :" }, { "code": null, "e": 684, "s": 676, "text": "Python3" }, { "code": "# import scipy and numpyimport scipyimport numpy as np x = np.arange(11)# Using scipy.fftfreq() methodgfg = scipy.fft.fftshift(x) print(gfg)", "e": 827, "s": 684, "text": null }, { "code": null, "e": 836, "s": 827, "text": "Output :" }, { "code": null, "e": 871, "s": 836, "text": "[ 6 7 8 9 10 0 1 2 3 4 5]" }, { "code": null, "e": 900, "s": 871, "text": "Python scipy-stats-functions" }, { "code": null, "e": 913, "s": 900, "text": "Python-scipy" }, { "code": null, "e": 920, "s": 913, "text": "Python" }, { "code": null, "e": 1018, "s": 920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1048, "s": 1018, "text": "Iterate over a list in Python" }, { "code": null, "e": 1093, "s": 1048, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1115, "s": 1093, "text": "Enumerate() in Python" }, { "code": null, "e": 1133, "s": 1115, "text": "Python Dictionary" }, { "code": null, "e": 1154, "s": 1133, "text": "Python OOPs Concepts" }, { "code": null, "e": 1196, "s": 1154, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1225, "s": 1196, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1252, "s": 1225, "text": "Python Classes and Objects" }, { "code": null, "e": 1275, "s": 1252, "text": "Introduction To PYTHON" } ]
Introduction in deep learning with julia
16 Aug, 2021 A new transition in Data Science is Julia since it is fast and easy to learn and work with. Julia being a promising language is mainly focused on the scientific computing domain. It provides good execution speed which is comparable to C/C++. It also supports parallelism. Julia is good for writing codes in Deep Learning because deep learning frameworks majorly use C++ at the backend(performance matters) and Python at the frontend(ease of use). Parallelism plays a big part in writing non-trivial deep learning code. It ensures syntax similar to MATLAB to which many coders will be able to have a transition. The main deep learning libraries for Julia is Flux.jl. PyTorch or TensorFlow are written in C++ or Cuda for good CPU performance. But if we want to write custom codes for experimental purposes it gets difficult here. So, in this Julia comes into picture providing us with some custom loss function. We will import Flux, Statistics, and MLDatasets. The Model: model = Chain( # 28x28 => 14x14 Conv((5, 5), 1=>8, pad=2, stride=2, relu), # 14x14 => 7x7 Conv((3, 3), 8=>16, pad=1, stride=2, relu), # 7x7 => 4x4 Conv((3, 3), 16=>32, pad=1, stride=2, relu), # 4x4 => 2x2 Conv((3, 3), 32=>32, pad=1, stride=2, relu), # Width x height feature map average pooling GlobalMeanPool(), flatten, Dense(32, 10), softmax) Now,we can use onecold() function to decode the predictions # Fetching the predictions y = model(x_train) # Decode the predictions y = onecold(y) println("Predict my Image1: $(y[1])") Training The Model: number_epochs = 10 @epochs number_epochs Flux.train!(loss, ps, train_data, opt) accuracy(model(x_train), y_train) @epochs-number of times to be executed. Multiple frameworks can be used to work on Julia as per the user’s needs. Some of the most commonly used frameworks are: Flux It is a deep learning and machine learning library. It provides a single and intuitive way to define models the same as a mathematical notation. The existing Julia libraries are differentiable, and they can be incorporated directly into the Flux models. Mocha.jl It is a deep learning library for Julia.Mocha.jl is completely written for Julia. The library considers Julia interfaces and it is capable of interacting with core Julia functionality and packages.This library includes minimum dependencies to use Julia in the backend. There is no need for root privileges or installing any external dependencies.Promotes modularity and correctness It is a deep learning library for Julia. Mocha.jl is completely written for Julia. The library considers Julia interfaces and it is capable of interacting with core Julia functionality and packages. This library includes minimum dependencies to use Julia in the backend. There is no need for root privileges or installing any external dependencies. Promotes modularity and correctness Knet Knet is a deep learning framework. It is implemented in Julia. Knet allows describing their forward computation in plain Julia. It allows the use of conditionals, loops, recursion, tuples, closures, dictionaries, array indexing, concatenation, and high-level language features. The library supports GPU operations and automates differentiation using dynamic computational graphs for models defined in plain Julia. Knet documentation has detailed instructions for handling major deep learning building blocks, some of which are listed below: BackpropagationConvolutional Neural NetworksRNNReinforcement learning Backpropagation Convolutional Neural Networks RNN Reinforcement learning TensorFlow.jl TensorFlow.jl is also a Julia wrapper for popular open-source machine learning TensorFlow. This wrapper can be used for various purposes such as fast ingestion of data, especially data in uncommon formats, fast post-processing of inference results, such as calculating various statistics and visualizations that do not have a canned vectorized implementation. ScikitLearn.jl ScikitLearn.jl is a Julia wrapper for the popular Python library Scikit-learn. It implements the Scikit-learn interface and algorithms in Julia. It provides a uniform interface for training and using models, as well as a set of tools for chaining (pipelines), evaluating, and tuning model hyper parameters. It supports both models from the Julia ecosystem and those of the Scikit-learn library. The major features of ScikitLearn.jl are listed below: Support for DataFramesHyper parameter tuningFeature unions and pipelinesCross-validation Support for DataFrames Hyper parameter tuning Feature unions and pipelines Cross-validation MXNet.jl MXNet.jl is the Apache MXNet Julia package that brings flexible and efficient GPU computing and state-of-art deep learning to Julia. The features of this library include efficient tensor and matrix computation across multiple devices, including multiple CPUs, GPUs, and distributed server nodes. It also has flexible symbolic manipulation to composite and construction of state-of-the-art deep learning models. MLBase.jl MLBase.jl is a Julia package that provides useful tools for machine learning applications. It provides a collection of useful tools to support machine learning programs, including data manipulation and preprocessing, score-based classification, performance evaluation, cross-validation, and model tuning. The MLBase.jl may be used for the following tasks: Preprocessing and data manipulationPerformance evaluationCross-validationModel tuning Preprocessing and data manipulation Performance evaluation Cross-validation Model tuning Merlin Merlin is a deep learning framework written in Julia. The library aims to provide a fast, flexible, and compact deep learning library for machine learning. The requirements of this library are Julia 0.6 and g++ for OSX or Linux. The library runs on CPUs and CUDA GPUs. Strada Strada is an open-source deep-learning library for Julia, based on the popular Caffe framework. The library supports convolutional and recurrent neural network training, both on CPUs and GPUs. Some features of this library include flexibility, support for Caffe features, integration with Julia, and other such. Parallel Supercomputing for Astronomy: The Celeste research team spent three years developing and testing a new parallel computing method that was used to process the Sloan Digital Sky Survey dataset and produce the most accurate catalog of 188 million astronomical objects in just 14.6 minutes with state-of-the-art point and uncertainty estimates.Tangent Works-Tangent Works uses Julia to build a comprehensive analytics solution that blurs the barrier between prototyping done by data scientists and product development done by developers.Diabetic Retinopathy-Diabetic retinopathy is an eye disease that affects more than 126 million diabetics and accounts for more than 5% of blindness cases worldwide. Timely screening and diagnosis can help prevent vision loss for millions of diabetics worldwide. IBM and Julia Computing analyzed eye fundus images provided by Drishti Eye Hospitals, and a built a deep learning solution that provides eye diagnosis and care to thousands of rural Indians.Julia in artificial plays an amazing role since:-It is one of the best ways of performing Deep Learning. Designed to quickly implement basic mathematical and scientific queries. Parallel Supercomputing for Astronomy: The Celeste research team spent three years developing and testing a new parallel computing method that was used to process the Sloan Digital Sky Survey dataset and produce the most accurate catalog of 188 million astronomical objects in just 14.6 minutes with state-of-the-art point and uncertainty estimates. Tangent Works-Tangent Works uses Julia to build a comprehensive analytics solution that blurs the barrier between prototyping done by data scientists and product development done by developers. Diabetic Retinopathy-Diabetic retinopathy is an eye disease that affects more than 126 million diabetics and accounts for more than 5% of blindness cases worldwide. Timely screening and diagnosis can help prevent vision loss for millions of diabetics worldwide. IBM and Julia Computing analyzed eye fundus images provided by Drishti Eye Hospitals, and a built a deep learning solution that provides eye diagnosis and care to thousands of rural Indians. Julia in artificial plays an amazing role since:-It is one of the best ways of performing Deep Learning. Designed to quickly implement basic mathematical and scientific queries. It is one of the best ways of performing Deep Learning. Designed to quickly implement basic mathematical and scientific queries. sharmaanushka Julia Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Exception handling in Julia Get array dimensions and size of a dimension in Julia - size() Method Get number of elements of array in Julia - length() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) NamedTuple in Julia Naive Bayes Classifiers ML | Linear Regression Linear Regression (Python Implementation)
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 639, "s": 28, "text": "A new transition in Data Science is Julia since it is fast and easy to learn and work with. Julia being a promising language is mainly focused on the scientific computing domain. It provides good execution speed which is comparable to C/C++. It also supports parallelism. Julia is good for writing codes in Deep Learning because deep learning frameworks majorly use C++ at the backend(performance matters) and Python at the frontend(ease of use). Parallelism plays a big part in writing non-trivial deep learning code. It ensures syntax similar to MATLAB to which many coders will be able to have a transition." }, { "code": null, "e": 938, "s": 639, "text": "The main deep learning libraries for Julia is Flux.jl. PyTorch or TensorFlow are written in C++ or Cuda for good CPU performance. But if we want to write custom codes for experimental purposes it gets difficult here. So, in this Julia comes into picture providing us with some custom loss function." }, { "code": null, "e": 987, "s": 938, "text": "We will import Flux, Statistics, and MLDatasets." }, { "code": null, "e": 998, "s": 987, "text": "The Model:" }, { "code": null, "e": 1408, "s": 998, "text": "model = Chain(\n \n # 28x28 => 14x14\n Conv((5, 5), 1=>8, pad=2, stride=2, relu),\n \n # 14x14 => 7x7\n Conv((3, 3), 8=>16, pad=1, stride=2, relu),\n \n # 7x7 => 4x4\n Conv((3, 3), 16=>32, pad=1, stride=2, relu),\n \n # 4x4 => 2x2\n Conv((3, 3), 32=>32, pad=1, stride=2, relu),\n \n # Width x height feature map average pooling \n GlobalMeanPool(),\n flatten,\n \n Dense(32, 10),\n softmax)" }, { "code": null, "e": 1468, "s": 1408, "text": "Now,we can use onecold() function to decode the predictions" }, { "code": null, "e": 1593, "s": 1468, "text": "# Fetching the predictions\ny = model(x_train)\n\n# Decode the predictions\ny = onecold(y)\nprintln(\"Predict my Image1: $(y[1])\")" }, { "code": null, "e": 1613, "s": 1593, "text": "Training The Model:" }, { "code": null, "e": 1727, "s": 1613, "text": "number_epochs = 10\n@epochs number_epochs Flux.train!(loss, ps, train_data, opt)\naccuracy(model(x_train), y_train)" }, { "code": null, "e": 1767, "s": 1727, "text": "@epochs-number of times to be executed." }, { "code": null, "e": 1888, "s": 1767, "text": "Multiple frameworks can be used to work on Julia as per the user’s needs. Some of the most commonly used frameworks are:" }, { "code": null, "e": 1893, "s": 1888, "text": "Flux" }, { "code": null, "e": 2148, "s": 1893, "text": "It is a deep learning and machine learning library. It provides a single and intuitive way to define models the same as a mathematical notation. The existing Julia libraries are differentiable, and they can be incorporated directly into the Flux models. " }, { "code": null, "e": 2157, "s": 2148, "text": "Mocha.jl" }, { "code": null, "e": 2539, "s": 2157, "text": "It is a deep learning library for Julia.Mocha.jl is completely written for Julia. The library considers Julia interfaces and it is capable of interacting with core Julia functionality and packages.This library includes minimum dependencies to use Julia in the backend. There is no need for root privileges or installing any external dependencies.Promotes modularity and correctness" }, { "code": null, "e": 2580, "s": 2539, "text": "It is a deep learning library for Julia." }, { "code": null, "e": 2738, "s": 2580, "text": "Mocha.jl is completely written for Julia. The library considers Julia interfaces and it is capable of interacting with core Julia functionality and packages." }, { "code": null, "e": 2888, "s": 2738, "text": "This library includes minimum dependencies to use Julia in the backend. There is no need for root privileges or installing any external dependencies." }, { "code": null, "e": 2924, "s": 2888, "text": "Promotes modularity and correctness" }, { "code": null, "e": 2929, "s": 2924, "text": "Knet" }, { "code": null, "e": 3345, "s": 2929, "text": "Knet is a deep learning framework. It is implemented in Julia. Knet allows describing their forward computation in plain Julia. It allows the use of conditionals, loops, recursion, tuples, closures, dictionaries, array indexing, concatenation, and high-level language features. The library supports GPU operations and automates differentiation using dynamic computational graphs for models defined in plain Julia. " }, { "code": null, "e": 3472, "s": 3345, "text": "Knet documentation has detailed instructions for handling major deep learning building blocks, some of which are listed below:" }, { "code": null, "e": 3542, "s": 3472, "text": "BackpropagationConvolutional Neural NetworksRNNReinforcement learning" }, { "code": null, "e": 3558, "s": 3542, "text": "Backpropagation" }, { "code": null, "e": 3588, "s": 3558, "text": "Convolutional Neural Networks" }, { "code": null, "e": 3592, "s": 3588, "text": "RNN" }, { "code": null, "e": 3615, "s": 3592, "text": "Reinforcement learning" }, { "code": null, "e": 3629, "s": 3615, "text": "TensorFlow.jl" }, { "code": null, "e": 3991, "s": 3629, "text": "TensorFlow.jl is also a Julia wrapper for popular open-source machine learning TensorFlow. This wrapper can be used for various purposes such as fast ingestion of data, especially data in uncommon formats, fast post-processing of inference results, such as calculating various statistics and visualizations that do not have a canned vectorized implementation. " }, { "code": null, "e": 4006, "s": 3991, "text": "ScikitLearn.jl" }, { "code": null, "e": 4404, "s": 4006, "text": "ScikitLearn.jl is a Julia wrapper for the popular Python library Scikit-learn. It implements the Scikit-learn interface and algorithms in Julia. It provides a uniform interface for training and using models, as well as a set of tools for chaining (pipelines), evaluating, and tuning model hyper parameters. It supports both models from the Julia ecosystem and those of the Scikit-learn library. " }, { "code": null, "e": 4459, "s": 4404, "text": "The major features of ScikitLearn.jl are listed below:" }, { "code": null, "e": 4548, "s": 4459, "text": "Support for DataFramesHyper parameter tuningFeature unions and pipelinesCross-validation" }, { "code": null, "e": 4571, "s": 4548, "text": "Support for DataFrames" }, { "code": null, "e": 4594, "s": 4571, "text": "Hyper parameter tuning" }, { "code": null, "e": 4623, "s": 4594, "text": "Feature unions and pipelines" }, { "code": null, "e": 4640, "s": 4623, "text": "Cross-validation" }, { "code": null, "e": 4649, "s": 4640, "text": "MXNet.jl" }, { "code": null, "e": 5061, "s": 4649, "text": "MXNet.jl is the Apache MXNet Julia package that brings flexible and efficient GPU computing and state-of-art deep learning to Julia. The features of this library include efficient tensor and matrix computation across multiple devices, including multiple CPUs, GPUs, and distributed server nodes. It also has flexible symbolic manipulation to composite and construction of state-of-the-art deep learning models. " }, { "code": null, "e": 5071, "s": 5061, "text": "MLBase.jl" }, { "code": null, "e": 5380, "s": 5071, "text": "MLBase.jl is a Julia package that provides useful tools for machine learning applications. It provides a collection of useful tools to support machine learning programs, including data manipulation and preprocessing, score-based classification, performance evaluation, cross-validation, and model tuning. " }, { "code": null, "e": 5431, "s": 5380, "text": "The MLBase.jl may be used for the following tasks:" }, { "code": null, "e": 5517, "s": 5431, "text": "Preprocessing and data manipulationPerformance evaluationCross-validationModel tuning" }, { "code": null, "e": 5553, "s": 5517, "text": "Preprocessing and data manipulation" }, { "code": null, "e": 5576, "s": 5553, "text": "Performance evaluation" }, { "code": null, "e": 5593, "s": 5576, "text": "Cross-validation" }, { "code": null, "e": 5606, "s": 5593, "text": "Model tuning" }, { "code": null, "e": 5613, "s": 5606, "text": "Merlin" }, { "code": null, "e": 5882, "s": 5613, "text": "Merlin is a deep learning framework written in Julia. The library aims to provide a fast, flexible, and compact deep learning library for machine learning. The requirements of this library are Julia 0.6 and g++ for OSX or Linux. The library runs on CPUs and CUDA GPUs." }, { "code": null, "e": 5891, "s": 5882, "text": "Strada " }, { "code": null, "e": 6205, "s": 5891, "text": "Strada is an open-source deep-learning library for Julia, based on the popular Caffe framework. The library supports convolutional and recurrent neural network training, both on CPUs and GPUs. Some features of this library include flexibility, support for Caffe features, integration with Julia, and other such. " }, { "code": null, "e": 7434, "s": 6205, "text": "Parallel Supercomputing for Astronomy: The Celeste research team spent three years developing and testing a new parallel computing method that was used to process the Sloan Digital Sky Survey dataset and produce the most accurate catalog of 188 million astronomical objects in just 14.6 minutes with state-of-the-art point and uncertainty estimates.Tangent Works-Tangent Works uses Julia to build a comprehensive analytics solution that blurs the barrier between prototyping done by data scientists and product development done by developers.Diabetic Retinopathy-Diabetic retinopathy is an eye disease that affects more than 126 million diabetics and accounts for more than 5% of blindness cases worldwide. Timely screening and diagnosis can help prevent vision loss for millions of diabetics worldwide. IBM and Julia Computing analyzed eye fundus images provided by Drishti Eye Hospitals, and a built a deep learning solution that provides eye diagnosis and care to thousands of rural Indians.Julia in artificial plays an amazing role since:-It is one of the best ways of performing Deep Learning. Designed to quickly implement basic mathematical and scientific queries." }, { "code": null, "e": 7784, "s": 7434, "text": "Parallel Supercomputing for Astronomy: The Celeste research team spent three years developing and testing a new parallel computing method that was used to process the Sloan Digital Sky Survey dataset and produce the most accurate catalog of 188 million astronomical objects in just 14.6 minutes with state-of-the-art point and uncertainty estimates." }, { "code": null, "e": 7978, "s": 7784, "text": "Tangent Works-Tangent Works uses Julia to build a comprehensive analytics solution that blurs the barrier between prototyping done by data scientists and product development done by developers." }, { "code": null, "e": 8431, "s": 7978, "text": "Diabetic Retinopathy-Diabetic retinopathy is an eye disease that affects more than 126 million diabetics and accounts for more than 5% of blindness cases worldwide. Timely screening and diagnosis can help prevent vision loss for millions of diabetics worldwide. IBM and Julia Computing analyzed eye fundus images provided by Drishti Eye Hospitals, and a built a deep learning solution that provides eye diagnosis and care to thousands of rural Indians." }, { "code": null, "e": 8666, "s": 8431, "text": "Julia in artificial plays an amazing role since:-It is one of the best ways of performing Deep Learning. Designed to quickly implement basic mathematical and scientific queries." }, { "code": null, "e": 8780, "s": 8666, "text": "It is one of the best ways of performing Deep Learning. " }, { "code": null, "e": 8853, "s": 8780, "text": "Designed to quickly implement basic mathematical and scientific queries." }, { "code": null, "e": 8867, "s": 8853, "text": "sharmaanushka" }, { "code": null, "e": 8873, "s": 8867, "text": "Julia" }, { "code": null, "e": 8890, "s": 8873, "text": "Machine Learning" }, { "code": null, "e": 8907, "s": 8890, "text": "Machine Learning" }, { "code": null, "e": 9005, "s": 8907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9033, "s": 9005, "text": "Exception handling in Julia" }, { "code": null, "e": 9103, "s": 9033, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 9162, "s": 9103, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 9235, "s": 9162, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 9255, "s": 9235, "text": "NamedTuple in Julia" }, { "code": null, "e": 9279, "s": 9255, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 9302, "s": 9279, "text": "ML | Linear Regression" } ]
Python | Get Unique values from list of dictionary
26 Jul, 2019 Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let’s discuss certain ways in which this task can be performed. Method #1 : Using set() + values() + dictionary comprehensionThe combination of these methods can together help us achieve the task of getting the unique values. The values function helps us get the values of dictionary, set helps us to get the unique of them, and dictionary comprehension to iterate through the list. # Python3 code to demonstrate working of# Get Unique values from list of dictionary# Using set() + values() + dictionary comprehension # Initialize list test_list = [{'gfg' : 1, 'is' : 2}, {'best' : 1, 'for' : 3}, {'CS' : 2}] # printing original listprint("The original list : " + str(test_list)) # Using set() + values() + dictionary comprehension# Get Unique values from list of dictionaryres = list(set(val for dic in test_list for val in dic.values())) # printing result print("The unique values in list are : " + str(res)) The original list : [{‘gfg’: 1, ‘is’: 2}, {‘best’: 1, ‘for’: 3}, {‘CS’: 2}]The unique values in list are : [1, 2, 3] Method #2 : Using set() + values() + from_iterable()The combination of above functions can be used to perform this particular task. It is just as the above method, but the iteration part is done by the from_iterable function. # Python3 code to demonstrate working of# Get Unique values from list of dictionary# Using set() + values() + from_iterable()from itertools import chain # Initialize list test_list = [{'gfg' : 1, 'is' : 2}, {'best' : 1, 'for' : 3}, {'CS' : 2}] # printing original listprint("The original list : " + str(test_list)) # Using set() + values() + from_iterable()# Get Unique values from list of dictionaryres = list(set(chain.from_iterable(sub.values() for sub in test_list))) # printing result print("The unique values in list are : " + str(res)) The original list : [{‘gfg’: 1, ‘is’: 2}, {‘best’: 1, ‘for’: 3}, {‘CS’: 2}]The unique values in list are : [1, 2, 3] Python dictionary-programs Python Python Programs 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 | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 356, "s": 28, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 675, "s": 356, "text": "Method #1 : Using set() + values() + dictionary comprehensionThe combination of these methods can together help us achieve the task of getting the unique values. The values function helps us get the values of dictionary, set helps us to get the unique of them, and dictionary comprehension to iterate through the list." }, { "code": "# Python3 code to demonstrate working of# Get Unique values from list of dictionary# Using set() + values() + dictionary comprehension # Initialize list test_list = [{'gfg' : 1, 'is' : 2}, {'best' : 1, 'for' : 3}, {'CS' : 2}] # printing original listprint(\"The original list : \" + str(test_list)) # Using set() + values() + dictionary comprehension# Get Unique values from list of dictionaryres = list(set(val for dic in test_list for val in dic.values())) # printing result print(\"The unique values in list are : \" + str(res))", "e": 1212, "s": 675, "text": null }, { "code": null, "e": 1329, "s": 1212, "text": "The original list : [{‘gfg’: 1, ‘is’: 2}, {‘best’: 1, ‘for’: 3}, {‘CS’: 2}]The unique values in list are : [1, 2, 3]" }, { "code": null, "e": 1557, "s": 1331, "text": "Method #2 : Using set() + values() + from_iterable()The combination of above functions can be used to perform this particular task. It is just as the above method, but the iteration part is done by the from_iterable function." }, { "code": "# Python3 code to demonstrate working of# Get Unique values from list of dictionary# Using set() + values() + from_iterable()from itertools import chain # Initialize list test_list = [{'gfg' : 1, 'is' : 2}, {'best' : 1, 'for' : 3}, {'CS' : 2}] # printing original listprint(\"The original list : \" + str(test_list)) # Using set() + values() + from_iterable()# Get Unique values from list of dictionaryres = list(set(chain.from_iterable(sub.values() for sub in test_list))) # printing result print(\"The unique values in list are : \" + str(res))", "e": 2109, "s": 1557, "text": null }, { "code": null, "e": 2226, "s": 2109, "text": "The original list : [{‘gfg’: 1, ‘is’: 2}, {‘best’: 1, ‘for’: 3}, {‘CS’: 2}]The unique values in list are : [1, 2, 3]" }, { "code": null, "e": 2253, "s": 2226, "text": "Python dictionary-programs" }, { "code": null, "e": 2260, "s": 2253, "text": "Python" }, { "code": null, "e": 2276, "s": 2260, "text": "Python Programs" }, { "code": null, "e": 2374, "s": 2276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2416, "s": 2374, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2438, "s": 2416, "text": "Enumerate() in Python" }, { "code": null, "e": 2464, "s": 2438, "text": "Python String | replace()" }, { "code": null, "e": 2496, "s": 2464, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2525, "s": 2496, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2547, "s": 2525, "text": "Defaultdict in Python" }, { "code": null, "e": 2585, "s": 2547, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2622, "s": 2585, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 2671, "s": 2622, "text": "Python | Convert string dictionary to dictionary" } ]
Matplotlib.pyplot.xcorr() in Python
22 Apr, 2021 Matplotlib is built on NumPy and sideby framework that’s why it is fast and efficient. It is open-source and has huge community support. It possesses the ability to work well with many operating systems and graphic backends. To get what matplotlib.pyplot.xcorr() do we need to understand Cross-Correlation. The correlation coefficient is a statistical measure of the strength of the relationship between the relative movements of two variables.For example: Let us take two real valued functions f and g. g is at x is the difference along x axis. Now to calculate x ne use Cross Correlation. matplotlib.pyplot.xcorr() function plots cross correlation between two array lists.Parameters : Return : Example 1: Python3 # import matplotlib libraryimport matplotlib.pyplot as pltimport numpy as np # float lists for cross# correlationx=[11.37, 14.23, 16.3, 12.36, 6.54, 4.23, 19.11, 12.13, 19.91, 11.00] y=[15.21, 12.23, 4.76, 9.89, 8.96, 19.26, 12.24, 11.54, 13.39, 18.96] # Plot graphfig = plt.figure()ax1 = fig.add_subplot(211) # cross correlation using# xcorr() functionax1.xcorr(x, y, usevlines=True, maxlags=5, normed=True, lw=2)# adding grid to the graphax1.grid(True)ax1.axhline(0, color='blue', lw=2) # show final plotted graphplt.show() Output : Example 2: Python3 # import matplotlib libraryimport matplotlib.pyplot as pltimport numpy as np # float lists for cross# correlationx, y = np.random.randn(2, 100) # Plot graphfig = plt.figure()ax1 = fig.add_subplot(211) # cross correlation using xcorr()# functionax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2) # adding grid to the graphax1.grid(True)ax1.axhline(0, color='blue', lw=2) # show final plotted graphplt.show() Output : simmytarika5 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2021" }, { "code": null, "e": 336, "s": 28, "text": "Matplotlib is built on NumPy and sideby framework that’s why it is fast and efficient. It is open-source and has huge community support. It possesses the ability to work well with many operating systems and graphic backends. To get what matplotlib.pyplot.xcorr() do we need to understand Cross-Correlation. " }, { "code": null, "e": 622, "s": 336, "text": "The correlation coefficient is a statistical measure of the strength of the relationship between the relative movements of two variables.For example: Let us take two real valued functions f and g. g is at x is the difference along x axis. Now to calculate x ne use Cross Correlation. " }, { "code": null, "e": 720, "s": 624, "text": "matplotlib.pyplot.xcorr() function plots cross correlation between two array lists.Parameters :" }, { "code": null, "e": 731, "s": 722, "text": "Return :" }, { "code": null, "e": 746, "s": 733, "text": "Example 1: " }, { "code": null, "e": 754, "s": 746, "text": "Python3" }, { "code": "# import matplotlib libraryimport matplotlib.pyplot as pltimport numpy as np # float lists for cross# correlationx=[11.37, 14.23, 16.3, 12.36, 6.54, 4.23, 19.11, 12.13, 19.91, 11.00] y=[15.21, 12.23, 4.76, 9.89, 8.96, 19.26, 12.24, 11.54, 13.39, 18.96] # Plot graphfig = plt.figure()ax1 = fig.add_subplot(211) # cross correlation using# xcorr() functionax1.xcorr(x, y, usevlines=True, maxlags=5, normed=True, lw=2)# adding grid to the graphax1.grid(True)ax1.axhline(0, color='blue', lw=2) # show final plotted graphplt.show()", "e": 1306, "s": 754, "text": null }, { "code": null, "e": 1317, "s": 1306, "text": "Output : " }, { "code": null, "e": 1330, "s": 1317, "text": "Example 2: " }, { "code": null, "e": 1338, "s": 1330, "text": "Python3" }, { "code": "# import matplotlib libraryimport matplotlib.pyplot as pltimport numpy as np # float lists for cross# correlationx, y = np.random.randn(2, 100) # Plot graphfig = plt.figure()ax1 = fig.add_subplot(211) # cross correlation using xcorr()# functionax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2) # adding grid to the graphax1.grid(True)ax1.axhline(0, color='blue', lw=2) # show final plotted graphplt.show()", "e": 1775, "s": 1338, "text": null }, { "code": null, "e": 1786, "s": 1775, "text": "Output : " }, { "code": null, "e": 1801, "s": 1788, "text": "simmytarika5" }, { "code": null, "e": 1819, "s": 1801, "text": "Python-matplotlib" }, { "code": null, "e": 1826, "s": 1819, "text": "Python" }, { "code": null, "e": 1924, "s": 1826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1942, "s": 1924, "text": "Python Dictionary" }, { "code": null, "e": 1984, "s": 1942, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2006, "s": 1984, "text": "Enumerate() in Python" }, { "code": null, "e": 2041, "s": 2006, "text": "Read a file line by line in Python" }, { "code": null, "e": 2067, "s": 2041, "text": "Python String | replace()" }, { "code": null, "e": 2099, "s": 2067, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2128, "s": 2099, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2155, "s": 2128, "text": "Python Classes and Objects" }, { "code": null, "e": 2185, "s": 2155, "text": "Iterate over a list in Python" } ]
Pandas DataFrames
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns. Create a simple Pandas DataFrame: calories duration 0 420 50 1 380 40 2 390 45 As you can see from the result above, the DataFrame is like a table with rows and columns. Pandas use the loc attribute to return one or more specified row(s) Return row 0: calories 420 duration 50 Name: 0, dtype: int64 Note: This example returns a Pandas Series. Return row 0 and 1: calories duration 0 420 50 1 380 40 Note: When using [], the result is a Pandas DataFrame. With the index argument, you can name your own indexes. Add a list of names to give each row a name: calories duration day1 420 50 day2 380 40 day3 390 45 Use the named index in the loc attribute to return the specified row(s). Return "day2": calories 380 duration 40 Name: 0, dtype: int64 If your data sets are stored in a file, Pandas can load them into a DataFrame. Load a comma separated file (CSV file) into a DataFrame: You will learn more about importing files in the next chapters. Insert the correct Pandas method to create a DataFrame. pd.(data) Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 117, "s": 0, "text": "A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional \narray, or a table with rows and columns." }, { "code": null, "e": 151, "s": 117, "text": "Create a simple Pandas DataFrame:" }, { "code": null, "e": 250, "s": 151, "text": "\n calories duration\n 0 420 50\n 1 380 40\n 2 390 45\n\n" }, { "code": null, "e": 341, "s": 250, "text": "As you can see from the result above, the DataFrame is like a table with rows and columns." }, { "code": null, "e": 411, "s": 341, "text": "Pandas use the loc attribute to return \none or more specified row(s)" }, { "code": null, "e": 425, "s": 411, "text": "Return row 0:" }, { "code": null, "e": 488, "s": 425, "text": "\n calories 420\n duration 50\n Name: 0, dtype: int64\n\n" }, { "code": null, "e": 532, "s": 488, "text": "Note: This example returns a Pandas Series." }, { "code": null, "e": 552, "s": 532, "text": "Return row 0 and 1:" }, { "code": null, "e": 627, "s": 552, "text": "\n calories duration\n 0 420 50\n 1 380 40\n\n" }, { "code": null, "e": 685, "s": 627, "text": "Note: When using [], the \n result is a Pandas DataFrame." }, { "code": null, "e": 741, "s": 685, "text": "With the index argument, you can name your own indexes." }, { "code": null, "e": 786, "s": 741, "text": "Add a list of names to give each row a name:" }, { "code": null, "e": 897, "s": 786, "text": "\n calories duration\n day1 420 50\n day2 380 40\n day3 390 45\n\n" }, { "code": null, "e": 972, "s": 897, "text": "\nUse the named index in the loc attribute to return the specified row(s).\n" }, { "code": null, "e": 987, "s": 972, "text": "Return \"day2\":" }, { "code": null, "e": 1050, "s": 987, "text": "\n calories 380\n duration 40\n Name: 0, dtype: int64\n\n" }, { "code": null, "e": 1129, "s": 1050, "text": "If your data sets are stored in a file, Pandas can load them into a DataFrame." }, { "code": null, "e": 1186, "s": 1129, "text": "Load a comma separated file (CSV file) into a DataFrame:" }, { "code": null, "e": 1250, "s": 1186, "text": "You will learn more about importing files in the next chapters." }, { "code": null, "e": 1306, "s": 1250, "text": "Insert the correct Pandas method to create a DataFrame." }, { "code": null, "e": 1317, "s": 1306, "text": "pd.(data)\n" }, { "code": null, "e": 1336, "s": 1317, "text": "Start the Exercise" }, { "code": null, "e": 1369, "s": 1336, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1411, "s": 1369, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1518, "s": 1411, "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": 1537, "s": 1518, "text": "help@w3schools.com" } ]
A guide to Collaborative Topic Modeling recommender systems | by Mario Damiano Russo | Towards Data Science
Recommender Systems are a broad class of machine learning models with the aim of forecasting the unobserved rating that a user u would give to an item i. In this guide, we will discuss Collaborative Topic Modeling/Regression (CTM/CTR) as introduced by Wang and Blei (2011) [3], a recommender system for text-based items with enhanced accuracy and out-of-matrix prediction capabilities. We will also provide a Python3 implementation for those who are not concerned with the mathematical details behind the model. CTM builds upon two well-known models, namely Probabilistic Matrix Factorization (PMF) [1] and Latent Dirichlet Allocation (LDA) [2], therefore preliminary knowledge of said models is required. For those unfamiliar with them, there are plenty of very good guides available online, among which: Latent Dirichlet Allocation, by Thushan Gangedara Probabilistic Matrix Factorization, by Benjamin Draves Probabilistic Matrix Factorization (PMF) is a very simple yet powerful approach, that allows us to infer item and user latent features when our only available data is a (U X I) sparse ratings matrix. Unfortunately, the simplicity of such approach is also its demise, since PMF is unable to generalize the recommendations for new, completely unrated items: since no ratings are observed for item j, the model cannot derive its latent vector of qualities. In technical jargon, we say that PMF is unable to do out-of-matrix prediction.This issue is particularly troublesome in contexts where unrated items do not get recommended since they have no ratings, and they keep having no ratings because they do not get recommended. An example of such scenario is the sector of scientific publications, where new papers from lesser-known authors, despite being qualitatively good, are unable to reach potentially interested readers. The core idea behind CTM is that we can represent the latent qualities vector of document i, Qi, as: Where θi is the (K X 1) vector of topic proportions for item i obtained from traditional LDA estimates, and εi is a (K X 1) offset vector that adjusts topic proportions. The rationale for the offset vector is that it adjusts the topic proportions by incorporating informations from the observed ratings. For example: suppose you have two scientific papers, and both of them are 50% about “Machine Learning” and 50% about “Biology”. Now, it might be that according to the observed ratings the first paper appeals more to Machine Learning researchers, whereas the second one appeals more to Biology researchers. Using the offset vector εi we are able to calibrate the topic proportions to reflect how much the different topics appeal to different individuals. Just like PMF and LDA, on which it is built upon, CTM also has its own generative process: Where σ2_P and σ2_Q represent the variance we impose a priori on the distribution of the elements of the vectors in P and Q. Similarly, σ2 represents the variance we impose a priori on the distribution of the ratings. For those unfamiliar with bayesian statistics, these values can be simplistically viewed as regularizing hyperparameters for our model. By representing the generative process using plate notation, we can clearly see that CTM is nothing more than a stacked version of an LDA model on top of a PMF one, where the vector of topic proportions θi is used as the mean of the generative distribution of Qi. In a Recommender System setting, we are interested in obtaining estimates of all the latent variables that contribute to determining the rating rui. Therefore, we will be interested in θi, Qi, and Pu. Since the full posterior P(θ, Q, P) is analytically intractable, we resort to estimation via Maximum Likelihood, where the likelihood of our data is defined as: Like in most MLE scenarios, it is convenient to work with the log-likelihood: It is convienient to derive each one of the four components individually. First part: Second part: Thirth part: Imposing α=1 for convenience, the above distribution becomes: Fourth part: Our log-likelihood will be: The strategy initially pursued in the paper was to use Coordinate Ascent, iteratively alternating between the optimization of [P, Q] and θ. But as the same authors pointed out, using estimates for θ obtained via standard LDA estimation and then optimizing only for [P, Q] gives comparable results and saves a lot of time during the training. We will therefore assume we already got our θ estimates from vanilla LDA, and we will optimize [P, Q] via gradient ascent. It is easy to derive the gradient of our log-likelihood with respect to [P, Q] as: The formula above is the main result of this section, and we will implement it in the following one in Python3. In this section, we will create a recommender system for Steam games. We will use two datasets: Steam 200k, containing information about per-game playtime for over 200k user-game interactions; Steam games complete dataset, containing various information for over 40k different Steam games, including title and description NOTE: The codes reported here are not exhaustive and should be intended as a reference. You can access the full, functional Notebook with all the codes HERE. First of all, we start by opening the Steam games complete dataset, keeping only the name and descriptions of each game. We also drop the games for which we have no textual description. games = pd.read_csv("steam_games.csv")# keep only the columns of interestgames = games.loc[:, ["name", "game_description"]]# Drop NaN game descriptions and namesgames = games[~games.game_description.isna()]games = games[~games.name.isna()]# Drop the introductory " About This Game " textgames.game_description = games.game_description.apply(lambda x: x.replace(" About This Game ", ""))# drop single-space descriptionsgames = games[games.game_description != " "]games.head(5) Then, we open the Steam 200k dataset. The rating variable we will try to forecast is the total playtime in hours, which will be scaled to be between 0 and 1. ratings = pd.read_csv("steam-200k.csv", header = None)# drop last empty columnratings.drop(4, axis = 1, inplace=True)# rename columnsratings.columns = ["UserID", "Title", "Action", "Value"]# keep only "play" variablesratings = ratings[ratings.Action != "purchase"]# and drop the "Action" column, as now it is all "play"sratings.drop("Action", axis = 1, inplace = True)# to ease computations, constrain PlayTime to be between 0 and 1pt = ratings.Valuept_scaled = (pt - pt.min()) / (pt.max() - pt.min())ratings.Value = pt_scaledratings.head(3) At this point, we need to find the games for which we have both a sparse vector of observed ratings and the description. We lowercase all titles and remove special characters [!,.-”?: ] in both datasets to increase compatibility between titles. We also drop all games with non-unique titles to avoid mismatching. We end up with 1982 titles for which we have both rating and description. We now turn our head to creating the (U X I) ratings matrix by combining the two datasets we preprocessed. R = pd.pivot_table(data=ratings, values = ["Value"], index=["UserID"], columns=["Title"])# remove the level on top of game names called "Value"R.columns = R.columns.droplevel()# remove leftover columns name from pivot operationR.columns.name = ""# lastly, fill in the NaNs with 0'sR.fillna(0, inplace=True)R.head(3) From this matrix, we hold out the vector of ratings for “need for speed undercover”, the 1105th game in our dataset. We will use this to test the validity of our out-of-matrix predictive power. Our final ratings matrix will be of shape 10058 users by 1981 games, with only 0.23% of the ratings being observed. Before training our CTM model, we need to extract the topics and their proportions in each game description by training an LDA model. The first thing we do is to lemmatize game descriptions to reduce variance in the vocabulary and improve LDA estimates. nlp = spacy.load("en")# lemmatize game descriptionsgames["lemmas"] = [[[token.lemma_ if token.lemma_ != "-PRON-" else token.text.lower() for token in sentence if token.pos_ in {"NOUN", "VERB", "ADJ", "ADV", "X"}] for sentence in nlp(speech).sents] for speech in games.game_description] We then train our LDA model to find K=15 topics across all of our game descriptions, and determine in which percentage each topic appears in each description. ## Train LDA model ##ldacorpus = [dictionary.doc2bow(text) for text in instances]tfidfmodel = TfidfModel(ldacorpus)model_corpus = tfidfmodel[ldacorpus]num_topics = 15num_passes = 30chunk_size = len(model_corpus) * num_passes/200model = LdaMulticore(num_topics=num_topics, corpus=model_corpus, id2word=dictionary, workers=multiprocessing.cpu_count()-1, chunksize=chunk_size, passes=num_passes, alpha=0.1)## #### obtain the matrix of topic proportions per document ##all_topics = model.get_document_topics(model_corpus, per_word_topics=True, minimum_probability=0.0)corpus_topics = []for doc_topics, word_topics, phi_values in all_topics: corpus_topics.append([topic[1] for topic in doc_topics]) corpus_topics = np.array(corpus_topics)theta = corpus_topics.copy().T## #### remove the heldout game from the theta matrix ##thet = pd.DataFrame(theta)heldout_topics = thet.iloc[:, heldout_idx]thet.drop(heldout_idx, axis = 1, inplace=True)theta = thet.values## ## Where theta is the (K X I) matrix that tells us the proportions of each one of the K=15 topics appears in each one of the I games. Once we have our ratings matrix and our matrix of per-item topic proportions, we can build our CTM model. We start by splitting our ratings matrix in X_train and X_val. # train - test splitdef train_test_split(ratings, percs = [0.8, 0.2]): validation = np.zeros(ratings.shape) train = ratings.copy() for user in np.arange(ratings.shape[0]): val_ratings = np.random.choice(ratings[user,:].nonzero()[0], size = round(len(ratings[user,:].nonzero()[0]) * percs[1]), replace=False ) train[user, val_ratings] = 0 validation[user, val_ratings] = ratings[user, val_ratings] return train, validationX_train, X_val = train_test_split(R.values) We also define a MSE function for our predicted ratings. from sklearn.metrics import mean_squared_errordef mse(prediction, ground_truth): prediction = prediction[ground_truth.nonzero()].flatten() ground_truth = ground_truth[ground_truth.nonzero()].flatten() return mean_squared_error(prediction, ground_truth) Lastly, we build our CTM model: from tqdm import trangeimport sysclass CTR(): """ Collaborative Topic Regression Model as developed by Wang and Blei (2012). Leverages topic proportions obtained from LDA model to improve predictions and allow for out-of-matrix predictions. Parameters: - sigma2: expected variance of ratings (variance of the ratings Normal prior) - sigma2_P: expected variance of the elements of the preference vector - sigma2_Q: expected variance of the elements of the quality vector """ def __init__(self, epochs=200, learning_rate=0.001, sigma2=10, sigma2_P=10, sigma2_Q=10): self.epochs = epochs self.learning_rate = learning_rate self.sigma2 = sigma2 self.sigma2_P = sigma2_P self.sigma2_Q = sigma2_Q def fit(self, theta, X_train, X_val): """ Fit a CTR model. Parameters: - theta: (K X I) matrix of topic proportions obtained via LDA. - X_train: (U X I) ratings matrix to train the model on. - X_test: (U X I) ratings matrix to validate the model on. """ K = theta.shape[0] U, I = X_train.shape #initialize P and Q matrices. # P is initialized randomly self.P = np.random.randint(0, 10) * np.random.rand(K, U) # Q is initialized to be equal to theta self.Q = theta.copy() self.train_error = [] self.val_error = [] # obtain the pairs of (u, i) indices for which we observe a rating users, items = X_train.nonzero() # begin training for iteration in trange(self.epochs, file=sys.stdout, desc='CTR'): for u, i in zip(users, items): error = X_train[u, i] - np.dot(self.P[:, u].T, self.Q[:, i])# we are MAXIMIZING the likelihood via gradient ascent self.P[:, u] += self.learning_rate * (-self.P[:, u]/self.sigma2_P + (self.P[:, u] * error)/self.sigma2) self.Q[:, i] += self.learning_rate * (-(self.Q[:, i] - theta[:, i])/self.sigma2_Q + (self.Q[:, i] * error)/self.sigma2)self.train_error.append(mse(np.dot(self.P.T, self.Q), X_train)) self.val_error.append(mse(np.dot(self.P.T, self.Q), X_val)) def predict_ratings(self): """ Returns the matrix of predicted ratings. """ return np.dot(self.P.T, self.Q) def predict_out_of_matrix(self, topics): """ Returns the (U X 1) vector of predicted ratings for an unrated item, using the item's topic proportions. Parameters: - topics: (K X 1) array of topic proportions for the unrated item. """ return np.dot(self.P.T, topics) And train the model: ctr = ctr = CTR(sigma2_P=5, sigma2_Q=5, sigma2=1)ctr.fit(theta, X_train, X_val) At the end of the training, our ctr object will have learned the latent matrices P and Q and will be able to predict the missing values in the ratings matrix via their dot product. Below is the MSE performance throughout the training for 100 epochs, with a 0.126 MSE on the validation set recorded during the last training epoch. The performance on the single held-out observation had a MSE of 0.35. Of course, this is not as high as the one recorded for in-matrix prediction, but it is quite impressive if we consider we are recommending an out-of-matrix item. We are satisfied with our results, but how well does Collaborative Topic Regression compare to traditional Probabilistic Matrix Factorization in this scenario? Quite well apparently. The vanilla factorization approach reaches a 0.32 MSE versus the 0.126 achieved by CTM. The latent topic structure that characterizes CTM adds a further layer of interpretability to make inference on. First of all, the added benefit of CTM over traditional PMF is that we are able to label the learned latent dimensions, seeing how prominent each topic truly is in each item. Note: these are not the topic proportions learned from LDA, but the topic relevances that are learned by the CTM model! We can also study the distribution of user preferences across the K latent dimensions via a simple horizontal sum of the P matrix: The same can be done for items instead of users, to see how are the genres distributed across our items: In this article, we presented Collaborative Topic Modeling as explained in Wang and Blei (2011), an improved matrix factorization recommender system for text-based items. The model performs generally better than vanilla matrix factorization methods, and presents additional benefits such as out-of-matrix prediciton and latent dimensions interpretability. In general, the highest challenge of calibrating a CTM model is finding the optimal combination of hyperparameters that gives the best performance on our data. In fact, we need to tune: alpha, from the LDA model. number of topics K learning rate sigma2, sigma2_P, sigma2_Q, hyperparameters on the prior distributions of R, P, and Q respectively. Secondly, there can be a lot of variability in the performance of the model across separate trainings due to the stochastic nature of the model, both in the LDA phase and in the CTM training phase. Despite not being a guaranteed improvement over PMF, CTM is indeed a method that should be considered when dealing with the task of recommending text-based documents, thanks to its generally higher performance and the out-of-matrix predictions capabilities. [1] Mnih, Andriy, and Russ R. Salakhutdinov. “Probabilistic matrix factorization.” Advances in neural information processing systems. 2008. [2] Blei, David M., Andrew Y. Ng, and Michael I. Jordan. “Latent dirichlet allocation.” Journal of machine Learning research 3.Jan (2003): 993–1022. [3] Wang, Chong, and David M. Blei. “Collaborative topic modeling for recommending scientific articles.” Proceedings of the 17th ACM SIGKDD international conference on Knowledge discovery and data mining. 2011.
[ { "code": null, "e": 326, "s": 172, "text": "Recommender Systems are a broad class of machine learning models with the aim of forecasting the unobserved rating that a user u would give to an item i." }, { "code": null, "e": 684, "s": 326, "text": "In this guide, we will discuss Collaborative Topic Modeling/Regression (CTM/CTR) as introduced by Wang and Blei (2011) [3], a recommender system for text-based items with enhanced accuracy and out-of-matrix prediction capabilities. We will also provide a Python3 implementation for those who are not concerned with the mathematical details behind the model." }, { "code": null, "e": 978, "s": 684, "text": "CTM builds upon two well-known models, namely Probabilistic Matrix Factorization (PMF) [1] and Latent Dirichlet Allocation (LDA) [2], therefore preliminary knowledge of said models is required. For those unfamiliar with them, there are plenty of very good guides available online, among which:" }, { "code": null, "e": 1028, "s": 978, "text": "Latent Dirichlet Allocation, by Thushan Gangedara" }, { "code": null, "e": 1083, "s": 1028, "text": "Probabilistic Matrix Factorization, by Benjamin Draves" }, { "code": null, "e": 1283, "s": 1083, "text": "Probabilistic Matrix Factorization (PMF) is a very simple yet powerful approach, that allows us to infer item and user latent features when our only available data is a (U X I) sparse ratings matrix." }, { "code": null, "e": 2006, "s": 1283, "text": "Unfortunately, the simplicity of such approach is also its demise, since PMF is unable to generalize the recommendations for new, completely unrated items: since no ratings are observed for item j, the model cannot derive its latent vector of qualities. In technical jargon, we say that PMF is unable to do out-of-matrix prediction.This issue is particularly troublesome in contexts where unrated items do not get recommended since they have no ratings, and they keep having no ratings because they do not get recommended. An example of such scenario is the sector of scientific publications, where new papers from lesser-known authors, despite being qualitatively good, are unable to reach potentially interested readers." }, { "code": null, "e": 2107, "s": 2006, "text": "The core idea behind CTM is that we can represent the latent qualities vector of document i, Qi, as:" }, { "code": null, "e": 2865, "s": 2107, "text": "Where θi is the (K X 1) vector of topic proportions for item i obtained from traditional LDA estimates, and εi is a (K X 1) offset vector that adjusts topic proportions. The rationale for the offset vector is that it adjusts the topic proportions by incorporating informations from the observed ratings. For example: suppose you have two scientific papers, and both of them are 50% about “Machine Learning” and 50% about “Biology”. Now, it might be that according to the observed ratings the first paper appeals more to Machine Learning researchers, whereas the second one appeals more to Biology researchers. Using the offset vector εi we are able to calibrate the topic proportions to reflect how much the different topics appeal to different individuals." }, { "code": null, "e": 2956, "s": 2865, "text": "Just like PMF and LDA, on which it is built upon, CTM also has its own generative process:" }, { "code": null, "e": 3310, "s": 2956, "text": "Where σ2_P and σ2_Q represent the variance we impose a priori on the distribution of the elements of the vectors in P and Q. Similarly, σ2 represents the variance we impose a priori on the distribution of the ratings. For those unfamiliar with bayesian statistics, these values can be simplistically viewed as regularizing hyperparameters for our model." }, { "code": null, "e": 3574, "s": 3310, "text": "By representing the generative process using plate notation, we can clearly see that CTM is nothing more than a stacked version of an LDA model on top of a PMF one, where the vector of topic proportions θi is used as the mean of the generative distribution of Qi." }, { "code": null, "e": 3936, "s": 3574, "text": "In a Recommender System setting, we are interested in obtaining estimates of all the latent variables that contribute to determining the rating rui. Therefore, we will be interested in θi, Qi, and Pu. Since the full posterior P(θ, Q, P) is analytically intractable, we resort to estimation via Maximum Likelihood, where the likelihood of our data is defined as:" }, { "code": null, "e": 4014, "s": 3936, "text": "Like in most MLE scenarios, it is convenient to work with the log-likelihood:" }, { "code": null, "e": 4088, "s": 4014, "text": "It is convienient to derive each one of the four components individually." }, { "code": null, "e": 4100, "s": 4088, "text": "First part:" }, { "code": null, "e": 4113, "s": 4100, "text": "Second part:" }, { "code": null, "e": 4126, "s": 4113, "text": "Thirth part:" }, { "code": null, "e": 4188, "s": 4126, "text": "Imposing α=1 for convenience, the above distribution becomes:" }, { "code": null, "e": 4201, "s": 4188, "text": "Fourth part:" }, { "code": null, "e": 4229, "s": 4201, "text": "Our log-likelihood will be:" }, { "code": null, "e": 4777, "s": 4229, "text": "The strategy initially pursued in the paper was to use Coordinate Ascent, iteratively alternating between the optimization of [P, Q] and θ. But as the same authors pointed out, using estimates for θ obtained via standard LDA estimation and then optimizing only for [P, Q] gives comparable results and saves a lot of time during the training. We will therefore assume we already got our θ estimates from vanilla LDA, and we will optimize [P, Q] via gradient ascent. It is easy to derive the gradient of our log-likelihood with respect to [P, Q] as:" }, { "code": null, "e": 4889, "s": 4777, "text": "The formula above is the main result of this section, and we will implement it in the following one in Python3." }, { "code": null, "e": 4985, "s": 4889, "text": "In this section, we will create a recommender system for Steam games. We will use two datasets:" }, { "code": null, "e": 5082, "s": 4985, "text": "Steam 200k, containing information about per-game playtime for over 200k user-game interactions;" }, { "code": null, "e": 5211, "s": 5082, "text": "Steam games complete dataset, containing various information for over 40k different Steam games, including title and description" }, { "code": null, "e": 5369, "s": 5211, "text": "NOTE: The codes reported here are not exhaustive and should be intended as a reference. You can access the full, functional Notebook with all the codes HERE." }, { "code": null, "e": 5555, "s": 5369, "text": "First of all, we start by opening the Steam games complete dataset, keeping only the name and descriptions of each game. We also drop the games for which we have no textual description." }, { "code": null, "e": 6031, "s": 5555, "text": "games = pd.read_csv(\"steam_games.csv\")# keep only the columns of interestgames = games.loc[:, [\"name\", \"game_description\"]]# Drop NaN game descriptions and namesgames = games[~games.game_description.isna()]games = games[~games.name.isna()]# Drop the introductory \" About This Game \" textgames.game_description = games.game_description.apply(lambda x: x.replace(\" About This Game \", \"\"))# drop single-space descriptionsgames = games[games.game_description != \" \"]games.head(5)" }, { "code": null, "e": 6189, "s": 6031, "text": "Then, we open the Steam 200k dataset. The rating variable we will try to forecast is the total playtime in hours, which will be scaled to be between 0 and 1." }, { "code": null, "e": 6731, "s": 6189, "text": "ratings = pd.read_csv(\"steam-200k.csv\", header = None)# drop last empty columnratings.drop(4, axis = 1, inplace=True)# rename columnsratings.columns = [\"UserID\", \"Title\", \"Action\", \"Value\"]# keep only \"play\" variablesratings = ratings[ratings.Action != \"purchase\"]# and drop the \"Action\" column, as now it is all \"play\"sratings.drop(\"Action\", axis = 1, inplace = True)# to ease computations, constrain PlayTime to be between 0 and 1pt = ratings.Valuept_scaled = (pt - pt.min()) / (pt.max() - pt.min())ratings.Value = pt_scaledratings.head(3)" }, { "code": null, "e": 7118, "s": 6731, "text": "At this point, we need to find the games for which we have both a sparse vector of observed ratings and the description. We lowercase all titles and remove special characters [!,.-”?: ] in both datasets to increase compatibility between titles. We also drop all games with non-unique titles to avoid mismatching. We end up with 1982 titles for which we have both rating and description." }, { "code": null, "e": 7225, "s": 7118, "text": "We now turn our head to creating the (U X I) ratings matrix by combining the two datasets we preprocessed." }, { "code": null, "e": 7541, "s": 7225, "text": "R = pd.pivot_table(data=ratings, values = [\"Value\"], index=[\"UserID\"], columns=[\"Title\"])# remove the level on top of game names called \"Value\"R.columns = R.columns.droplevel()# remove leftover columns name from pivot operationR.columns.name = \"\"# lastly, fill in the NaNs with 0'sR.fillna(0, inplace=True)R.head(3)" }, { "code": null, "e": 7735, "s": 7541, "text": "From this matrix, we hold out the vector of ratings for “need for speed undercover”, the 1105th game in our dataset. We will use this to test the validity of our out-of-matrix predictive power." }, { "code": null, "e": 7851, "s": 7735, "text": "Our final ratings matrix will be of shape 10058 users by 1981 games, with only 0.23% of the ratings being observed." }, { "code": null, "e": 8105, "s": 7851, "text": "Before training our CTM model, we need to extract the topics and their proportions in each game description by training an LDA model. The first thing we do is to lemmatize game descriptions to reduce variance in the vocabulary and improve LDA estimates." }, { "code": null, "e": 8391, "s": 8105, "text": "nlp = spacy.load(\"en\")# lemmatize game descriptionsgames[\"lemmas\"] = [[[token.lemma_ if token.lemma_ != \"-PRON-\" else token.text.lower() for token in sentence if token.pos_ in {\"NOUN\", \"VERB\", \"ADJ\", \"ADV\", \"X\"}] for sentence in nlp(speech).sents] for speech in games.game_description]" }, { "code": null, "e": 8550, "s": 8391, "text": "We then train our LDA model to find K=15 topics across all of our game descriptions, and determine in which percentage each topic appears in each description." }, { "code": null, "e": 9628, "s": 8550, "text": "## Train LDA model ##ldacorpus = [dictionary.doc2bow(text) for text in instances]tfidfmodel = TfidfModel(ldacorpus)model_corpus = tfidfmodel[ldacorpus]num_topics = 15num_passes = 30chunk_size = len(model_corpus) * num_passes/200model = LdaMulticore(num_topics=num_topics, corpus=model_corpus, id2word=dictionary, workers=multiprocessing.cpu_count()-1, chunksize=chunk_size, passes=num_passes, alpha=0.1)## #### obtain the matrix of topic proportions per document ##all_topics = model.get_document_topics(model_corpus, per_word_topics=True, minimum_probability=0.0)corpus_topics = []for doc_topics, word_topics, phi_values in all_topics: corpus_topics.append([topic[1] for topic in doc_topics]) corpus_topics = np.array(corpus_topics)theta = corpus_topics.copy().T## #### remove the heldout game from the theta matrix ##thet = pd.DataFrame(theta)heldout_topics = thet.iloc[:, heldout_idx]thet.drop(heldout_idx, axis = 1, inplace=True)theta = thet.values## ##" }, { "code": null, "e": 9759, "s": 9628, "text": "Where theta is the (K X I) matrix that tells us the proportions of each one of the K=15 topics appears in each one of the I games." }, { "code": null, "e": 9865, "s": 9759, "text": "Once we have our ratings matrix and our matrix of per-item topic proportions, we can build our CTM model." }, { "code": null, "e": 9928, "s": 9865, "text": "We start by splitting our ratings matrix in X_train and X_val." }, { "code": null, "e": 10555, "s": 9928, "text": "# train - test splitdef train_test_split(ratings, percs = [0.8, 0.2]): validation = np.zeros(ratings.shape) train = ratings.copy() for user in np.arange(ratings.shape[0]): val_ratings = np.random.choice(ratings[user,:].nonzero()[0], size = round(len(ratings[user,:].nonzero()[0]) * percs[1]), replace=False ) train[user, val_ratings] = 0 validation[user, val_ratings] = ratings[user, val_ratings] return train, validationX_train, X_val = train_test_split(R.values)" }, { "code": null, "e": 10612, "s": 10555, "text": "We also define a MSE function for our predicted ratings." }, { "code": null, "e": 10874, "s": 10612, "text": "from sklearn.metrics import mean_squared_errordef mse(prediction, ground_truth): prediction = prediction[ground_truth.nonzero()].flatten() ground_truth = ground_truth[ground_truth.nonzero()].flatten() return mean_squared_error(prediction, ground_truth)" }, { "code": null, "e": 10906, "s": 10874, "text": "Lastly, we build our CTM model:" }, { "code": null, "e": 13724, "s": 10906, "text": "from tqdm import trangeimport sysclass CTR(): \"\"\" Collaborative Topic Regression Model as developed by Wang and Blei (2012). Leverages topic proportions obtained from LDA model to improve predictions and allow for out-of-matrix predictions. Parameters: - sigma2: expected variance of ratings (variance of the ratings Normal prior) - sigma2_P: expected variance of the elements of the preference vector - sigma2_Q: expected variance of the elements of the quality vector \"\"\" def __init__(self, epochs=200, learning_rate=0.001, sigma2=10, sigma2_P=10, sigma2_Q=10): self.epochs = epochs self.learning_rate = learning_rate self.sigma2 = sigma2 self.sigma2_P = sigma2_P self.sigma2_Q = sigma2_Q def fit(self, theta, X_train, X_val): \"\"\" Fit a CTR model. Parameters: - theta: (K X I) matrix of topic proportions obtained via LDA. - X_train: (U X I) ratings matrix to train the model on. - X_test: (U X I) ratings matrix to validate the model on. \"\"\" K = theta.shape[0] U, I = X_train.shape #initialize P and Q matrices. # P is initialized randomly self.P = np.random.randint(0, 10) * np.random.rand(K, U) # Q is initialized to be equal to theta self.Q = theta.copy() self.train_error = [] self.val_error = [] # obtain the pairs of (u, i) indices for which we observe a rating users, items = X_train.nonzero() # begin training for iteration in trange(self.epochs, file=sys.stdout, desc='CTR'): for u, i in zip(users, items): error = X_train[u, i] - np.dot(self.P[:, u].T, self.Q[:, i])# we are MAXIMIZING the likelihood via gradient ascent self.P[:, u] += self.learning_rate * (-self.P[:, u]/self.sigma2_P + (self.P[:, u] * error)/self.sigma2) self.Q[:, i] += self.learning_rate * (-(self.Q[:, i] - theta[:, i])/self.sigma2_Q + (self.Q[:, i] * error)/self.sigma2)self.train_error.append(mse(np.dot(self.P.T, self.Q), X_train)) self.val_error.append(mse(np.dot(self.P.T, self.Q), X_val)) def predict_ratings(self): \"\"\" Returns the matrix of predicted ratings. \"\"\" return np.dot(self.P.T, self.Q) def predict_out_of_matrix(self, topics): \"\"\" Returns the (U X 1) vector of predicted ratings for an unrated item, using the item's topic proportions. Parameters: - topics: (K X 1) array of topic proportions for the unrated item. \"\"\" return np.dot(self.P.T, topics)" }, { "code": null, "e": 13745, "s": 13724, "text": "And train the model:" }, { "code": null, "e": 13825, "s": 13745, "text": "ctr = ctr = CTR(sigma2_P=5, sigma2_Q=5, sigma2=1)ctr.fit(theta, X_train, X_val)" }, { "code": null, "e": 14006, "s": 13825, "text": "At the end of the training, our ctr object will have learned the latent matrices P and Q and will be able to predict the missing values in the ratings matrix via their dot product." }, { "code": null, "e": 14155, "s": 14006, "text": "Below is the MSE performance throughout the training for 100 epochs, with a 0.126 MSE on the validation set recorded during the last training epoch." }, { "code": null, "e": 14387, "s": 14155, "text": "The performance on the single held-out observation had a MSE of 0.35. Of course, this is not as high as the one recorded for in-matrix prediction, but it is quite impressive if we consider we are recommending an out-of-matrix item." }, { "code": null, "e": 14658, "s": 14387, "text": "We are satisfied with our results, but how well does Collaborative Topic Regression compare to traditional Probabilistic Matrix Factorization in this scenario? Quite well apparently. The vanilla factorization approach reaches a 0.32 MSE versus the 0.126 achieved by CTM." }, { "code": null, "e": 15066, "s": 14658, "text": "The latent topic structure that characterizes CTM adds a further layer of interpretability to make inference on. First of all, the added benefit of CTM over traditional PMF is that we are able to label the learned latent dimensions, seeing how prominent each topic truly is in each item. Note: these are not the topic proportions learned from LDA, but the topic relevances that are learned by the CTM model!" }, { "code": null, "e": 15197, "s": 15066, "text": "We can also study the distribution of user preferences across the K latent dimensions via a simple horizontal sum of the P matrix:" }, { "code": null, "e": 15302, "s": 15197, "text": "The same can be done for items instead of users, to see how are the genres distributed across our items:" }, { "code": null, "e": 15658, "s": 15302, "text": "In this article, we presented Collaborative Topic Modeling as explained in Wang and Blei (2011), an improved matrix factorization recommender system for text-based items. The model performs generally better than vanilla matrix factorization methods, and presents additional benefits such as out-of-matrix prediciton and latent dimensions interpretability." }, { "code": null, "e": 15844, "s": 15658, "text": "In general, the highest challenge of calibrating a CTM model is finding the optimal combination of hyperparameters that gives the best performance on our data. In fact, we need to tune:" }, { "code": null, "e": 15871, "s": 15844, "text": "alpha, from the LDA model." }, { "code": null, "e": 15890, "s": 15871, "text": "number of topics K" }, { "code": null, "e": 15904, "s": 15890, "text": "learning rate" }, { "code": null, "e": 16004, "s": 15904, "text": "sigma2, sigma2_P, sigma2_Q, hyperparameters on the prior distributions of R, P, and Q respectively." }, { "code": null, "e": 16202, "s": 16004, "text": "Secondly, there can be a lot of variability in the performance of the model across separate trainings due to the stochastic nature of the model, both in the LDA phase and in the CTM training phase." }, { "code": null, "e": 16460, "s": 16202, "text": "Despite not being a guaranteed improvement over PMF, CTM is indeed a method that should be considered when dealing with the task of recommending text-based documents, thanks to its generally higher performance and the out-of-matrix predictions capabilities." }, { "code": null, "e": 16600, "s": 16460, "text": "[1] Mnih, Andriy, and Russ R. Salakhutdinov. “Probabilistic matrix factorization.” Advances in neural information processing systems. 2008." }, { "code": null, "e": 16749, "s": 16600, "text": "[2] Blei, David M., Andrew Y. Ng, and Michael I. Jordan. “Latent dirichlet allocation.” Journal of machine Learning research 3.Jan (2003): 993–1022." } ]
Creating a Stack in Javascript
Though Arrays in JavaScript provide all the functionality of a Stack, let us implement our own Stack class. Our class will have the following functions − push(element): Function to push elements on top of the stack. pop(): Function that removes an element from the top and returns it. peek(): Returns the element on top of the stack. isFull(): Checks if we reached the element limit on the stack. isEmpty(): checks if the stack is empty. clear(): Remove all elements. display(): display all contents of the array Let's start by defining a simple class with a constructor that takes the max size of the stack and a helper function display() that'll help us when we implement the other functions for this class. We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty. The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly. The isEmpty function checks if a size of the container is 0. These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Stack class. class Stack { constructor(maxSize) { // Set default max size if not provided if (isNaN(maxSize)) { maxSize = 10; } this.maxSize = maxSize; // Init an array that'll contain the stack values. this.container = []; } // A method just to see the contents while we develop this class display() { console.log(this.container); } // Checking if the array is empty isEmpty() { return this.container.length === 0; } // Check if array is full isFull() { return this.container.length >= maxSize; } push(element) { // Check if stack is full if (this.isFull()) { console.log("Stack Overflow!"); return; } this.container.push(element); } }
[ { "code": null, "e": 1216, "s": 1062, "text": "Though Arrays in JavaScript provide all the functionality of a Stack, let us implement our own Stack class. Our class will have the following functions −" }, { "code": null, "e": 1278, "s": 1216, "text": "push(element): Function to push elements on top of the stack." }, { "code": null, "e": 1347, "s": 1278, "text": "pop(): Function that removes an element from the top and returns it." }, { "code": null, "e": 1396, "s": 1347, "text": "peek(): Returns the element on top of the stack." }, { "code": null, "e": 1459, "s": 1396, "text": "isFull(): Checks if we reached the element limit on the stack." }, { "code": null, "e": 1501, "s": 1459, "text": " isEmpty(): checks if the stack is empty." }, { "code": null, "e": 1531, "s": 1501, "text": "clear(): Remove all elements." }, { "code": null, "e": 1576, "s": 1531, "text": "display(): display all contents of the array" }, { "code": null, "e": 1871, "s": 1576, "text": "Let's start by defining a simple class with a constructor that takes the max size of the stack and a helper function display() that'll help us when we implement the other functions for this class. We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty." }, { "code": null, "e": 1992, "s": 1871, "text": "The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly." }, { "code": null, "e": 2053, "s": 1992, "text": "The isEmpty function checks if a size of the container is 0." }, { "code": null, "e": 2192, "s": 2053, "text": "These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Stack class." }, { "code": null, "e": 2994, "s": 2192, "text": "class Stack {\n\n constructor(maxSize) {\n\n // Set default max size if not provided\n\n if (isNaN(maxSize)) {\n\n maxSize = 10;\n\n }\n\n this.maxSize = maxSize; // Init an array that'll contain the stack values.\n\n this.container = [];\n\n }\n\n\n\n // A method just to see the contents while we develop this class\n\n display() {\n\n console.log(this.container);\n\n }\n\n\n\n // Checking if the array is empty\n\n isEmpty() {\n\n return this.container.length === 0;\n\n }\n\n \n\n // Check if array is full\n\n isFull() {\n\n return this.container.length >= maxSize;\n\n }\n\n\n\n push(element) {\n\n // Check if stack is full\n\n if (this.isFull()) {\n\n console.log(\"Stack Overflow!\");\n\n return;\n\n }\n\n this.container.push(element);\n\n }\n\n}" } ]
MySQLi Procedural Functions - GeeksforGeeks
28 Jan, 2022 MySQLi (MySQL Improved) provides procedural and object oriented interface to data and its management. The i extension MySQL functions allows the user to access its database servers. The MySQL improved extension is specially designed to work with MySQL version 4.1.13 and new versions.Advantages of using prepared statements: Prepared statements are highly efficient specially to avoid SQL injection attacks.The prepared statements are used repeatedly. It also reduces parsing time and overheads as the preparation of query is done only once.The database parses, compiles, optimizes the query statement and stores the result.Binding parameters with the query minimizes overall bandwidth as the parameters are sent whenever required, instead of sending the whole query.Binding parameters with placeholders are safer and easier as the proper formatting is automatically done.By sending the placeholder values to MySQL Server, it follows the client-server protocol.It executes a particular query statement multiple times with different set of variables effectively reducing the cost.It also saves on data copying and conversion.Prepared statements are less prone to errors as the statement is parsed at first and then the parsed values are used by the server. Prepared statements are highly efficient specially to avoid SQL injection attacks. The prepared statements are used repeatedly. It also reduces parsing time and overheads as the preparation of query is done only once. The database parses, compiles, optimizes the query statement and stores the result. Binding parameters with the query minimizes overall bandwidth as the parameters are sent whenever required, instead of sending the whole query. Binding parameters with placeholders are safer and easier as the proper formatting is automatically done. By sending the placeholder values to MySQL Server, it follows the client-server protocol. It executes a particular query statement multiple times with different set of variables effectively reducing the cost. It also saves on data copying and conversion. Prepared statements are less prone to errors as the statement is parsed at first and then the parsed values are used by the server. We cannot cover everything under this topic, but let us look into some of the important procedural functions of MySQLi .1. mysqli_connect(): As you know, before doing any database related operations, you need to establish a connection to the MySQL database server. If the connection is established successfully, then it returns a database connection resource identifier. If the connection encounters failure, then it just throws an error. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connectionmysqli_connect($host, $dbuser, $dbpass, $dbname); // Check connectionif(mysqli_connect_error()){ echo "Connection establishing failed!";}else{ echo "Connection established successfully.";}?> Output: Connection established successfully. 2. mysqli_connect_error(): The MySQLi function throws an error when the connection is not made successfully and the function stores the error in previous call to mysqli_connect(). If no error is encountered , it returns NULL. If any error is encountered , then it returns an error message.Note: To test mysqli_connect_error(), stop the MySQL server in XAMPP control panel and then call the above PHP code having mysqli_connect(). If display_errors are enabled in PHP configuration, you can see an error of mysqli_connect_error() which returns the following message. Connection failed as the target machine actively refused it. Note: In good programming practice , its better NOT to show any error messages. For troubleshooting purpose, use mysqli_connect_error() to log the error as mentioned in the below code . php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connectionmysqli_connect($host, $dbuser, $dbpass, $dbname); // Check connectionif(mysqli_connect_error()){ echo "Connection establishing failed!";}else{ echo "Connection established successfully.";}?> 3. mysqli_select_db(): This mySQLi function is used to change the default database for making a connection. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG";$dbtest = "GFG_TEST"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); //write some code for database "GFG" // Change database to "GFG_TEST" mysqli_select_db($conn,$dbtest); // PHP code for database "GFG_TEST"... mysqli_close($conn);?> Result: This will change the current database to GFG_TEST4. mysqli_debug(): Every web developer needs to refer to log files to start troubleshooting for improving the application performance. The above mySQLi function is used in the code for all debugging purposes. php <?php//create a trace file in the localhostmysqli_debug("d:t:o,/temp/client.trace");?> Note: The user should compile the MySQL client library to make use of the above function to support debugging. This function on success will return TRUE.5. mysqli_close(): This MySQLi function is used to close a previously connected database. This function will return TRUE on successful closing, otherwise it will return FALSE. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);//some php codeif(mysqli_close($conn))echo "Connection closed successfully.";?> Output: Connection closed successfully. 6. mysqli_prepare(): The above MySQLi function is used to prepare a MySQL query for execution. It returns a statement object for further operations and returns FALSE if some error occurs. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // prepare the mysql query statement and bind parameters$query = mysqli_prepare("INSERT INTO items_info (item_name, description) VALUES (?, ?)");$query->bind_param("ss", $itemname, $description); // set parameters and execute$itemname = "Shampoo";$description = "Hairfall preventing protein shampoo"; $query->execute();echo "New record inserted successfully";mysqli_close();?> Output: New record inserted successfully 7. mysqli_query(): This MySQLi function performs or executes the query on the given database. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // performs the insert querymysqli_query($conn,"INSERT INTO items_info (item_name, description) VALUES ('Nailpolish', 'Colorbar Pink one')"); echo "Inserted successfully";mysqli_close($conn);?> Output: Inserted successfully 8. mysqli_rollback(): The mysqli function rollsback the current transaction for the given database connection. Turn OFF the auto-commit, execute the query, then again commit the query and then rollback the current transaction. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // Set autocommit to offmysqli_autocommit($conn,FALSE); // performs the insert querymysqli_query($conn,"INSERT INTO items_info (item_name, description) VALUES ('Shoes', 'Adidas Brand')"); echo "Inserted successfully";// Commit transactionmysqli_commit($conn); // Rollback transactionmysqli_rollback($conn);mysqli_close($conn);?> 9. mysqli_fetch_row(): The above MySQLi function is used to fetch one row from the result-set as an enumerated array. Each call to the above function will return the next row from the result set. If no rows are fetched, then it returns FALSE. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "SELECT item_name,description from items_info"; if ($result=mysqli_query($conn,$query)){ // Fetch one and one row while ($row=mysqli_fetch_row($result)) { echo " Item name :".$row[0]." , "; echo " Description : ".$row[1]; echo nl2br (" \n "); }//end while // Free result set mysqli_free_result($result);}// end ifmysqli_close($conn);?> Result: It will show all the rows with Item name , Description 10. mysqli_field_count(): The above MySQLi function is used to return the number of columns for the most recent query. It returns total number of columns in the result set. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "SELECT * from items_info";mysqli_query($conn,$query);$total_columns = mysqli_field_count($conn);echo $total_columns;mysqli_close($conn);?> Output: 4 11. mysqli_fetch_array(): The above MySQLi function is used to fetch a row as an associative, numeric array or both types of array from the result set. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "SELECT item_name,description from items_info"; $result=mysqli_query($conn,$query);// Gets the Numeric array$row=mysqli_fetch_array($result,MYSQLI_NUM);echo " Item name :".$row[0];echo ",";echo " Description : ".$row[1];echo nl2br (" \n ");// Gets the Associative array$row=mysqli_fetch_array($result,MYSQLI_ASSOC);echo " Item name :".$row["item_name"];echo ",";echo " Description : ".$row["description"]; // Free the result setmysqli_free_result($result);mysqli_close($conn);?> Output: table array 12. mysqli_fetch_all(): The MySQLi function fetches all rows and return the result set as an associative array, a numeric array, or both. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); $query = "SELECT item_name from items_info";$result = mysqli_query($conn,$query);$rowcount=mysqli_num_rows($result);// Gets the Associative array$row = mysqli_fetch_all($result,MYSQLI_ASSOC);print_r($row); for($i=0;$i<$rowcount;$i++){ echo "<br> ".$row[$i]['item_name'];}// Free the result setmysqli_free_result($result);mysqli_close($conn);?> Note: The above function is only available with MySQL Native Driver.13. mysqli_free_result(): The above MySQLi function free the memory of the fetched rows of the result set. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "SELECT item_name,description from items_info"; if ($result=mysqli_query($conn,$query)){ while ($row=mysqli_fetch_row($result)) { echo " Item name :".$row[0].","; echo " Description : ".$row[1]; echo nl2br (" \n "); }//end while // Free result set mysqli_free_result($result);}// end ifmysqli_close($conn);?> Output: Item name :box, Description : square shaped box in red colour 14. mysqli_num_rows(): The above MySQLi function is used to return the number of rows of the result set. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); $query = "SELECT item_name,description from items_info";if ($result=mysqli_query($conn,$query)){ //It returns the total number of rows of the result set $rowcount=mysqli_num_rows($result); echo "Total number of rows of the result : ".$rowcount; // Free result set mysqli_free_result($result); }// end ifmysqli_close($conn);?> Output: Total number of rows of the result : 8 15. mysqli_affected_rows(): The above MySQLi function is used to return the total number of affected rows from the previous MySQL SELECT, INSERT, UPDATE, DELETE or REPLACE query. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "SELECT * FROM items_info"; // performs the querymysqli_query($conn,$query);echo "Total affected rows : ".mysqli_affected_rows($conn);mysqli_close($conn);?> Output: Total affected rows : 8 16. mysqli_get_server_info(): The above MySQLi function is used to return the MySQL server version. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);echo "The MySQL server version is : ".mysqli_get_server_info($conn);mysqli_close($conn);?> Output: The MySQL server version is : 5.6.21 17. mysqli_fetch_fields(): The above MySQLi function returns an array of objects which contains the information of columns of the result set. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "SELECT item_name,description FROM items_info"; if ($result=mysqli_query($conn,$query)) { // Get the fields $fields=mysqli_fetch_fields($result); foreach ($fields as $value) { echo "Column name : ".$value->name."<br> "; echo "Table name : ".$value->table."<br> "; echo "Maximum length : ".$value->max_length."<br> "; echo nl2br (" \n "); } // Free result set mysqli_free_result($result);} mysqli_close($conn);?> Output: Column name : item_name Table name : items_info Maximum length : 18 Column name : description Table name : items_info Maximum length : 35 18. mysqli_error(): The MySQLi function returns the error message for the last MySQL function call, if any error exists. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);if (mysqli_connect_errno()) { echo "Connection to MySQL server failed : " . mysqli_connect_error(); } $query = "INSERT INTO items_info (item_name) VALUES ('Jacket')";// Check for error after performing the queryif (!mysqli_query($conn,$query)) { echo("Error occurred : " . mysqli_error($conn)); } ?> 19. mysqli_autocommit(): This above MySQLi function is used in turning ON/OFF auto-committing database changes or operations. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection $conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); mysqli_autocommit($conn,FALSE); // performs the insert querymysqli_query($conn,"INSERT INTO items_info (item_name, description) VALUES ('Clock', 'Wall clock for the living room')");//Commit the query transactionmysqli_commit($conn);echo "Inserted successfully";mysqli_close($conn);?> 20. mysqli_error_list(): The MySQLi function returns list of error messages for the last MySQL function call, if any error exists. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); if (mysqli_connect_errno()) { echo "Connection to MySQL server failed : " . mysqli_connect_error(); }$query = "INSERT INTO items_info (item_name) VALUES ('Jacket')";// Check for error after performing the queryif (!mysqli_query($conn,$query)) { print_r(mysqli_error_list($conn)); } ?> 21. mysqli_begin_transaction(): The MySQLi function starts a transaction following the MySQL commands. It returns TRUE in case of successful execution, otherwise it returns FALSE. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = "INSERT INTO items_info (item_name, description) VALUES ('Bangles', 'Pink bangles')";// performs the insert query mysqli_begin_transaction($conn, MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT); mysqli_query($conn,$query);mysqli_commit($conn);echo "Inserted successfully";mysqli_close($conn);?> 22. mysqli_change_user(): The MySQLi function is used to change the user of given database connection to the new database . php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG";$other_dbname = "OTHER_GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // reset to new databasemysqli_change_user($conn, $dbuser,$dbpass, $other_dbname);if ($result = mysqli_query($conn,"SELECT database()")){ $row = mysqli_fetch_row($result); echo "Default database : ".$row[0];} mysqli_close($conn);?> Output: Default database : OTHER_GFG 23. mysqli_character_set_name(): The MySQLi function is used to return the default character set selected for the database connection . php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$characterset = mysqli_character_set_name($conn);echo "Default character set is: " . $characterset; mysqli_close($conn);?> Output: Default character set is: latin1 24. mysqli_real_escape_string(): The MySQLi function is used to escape special characters in a string for use in MySQL queries. php <?php// Database configuration$host = "localhost";$dbuser = "root";$dbpass = "";$dbname = "GFG"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); $itemname = "matress's";$description = "Belongs to Mumbai's mall"; // escape variables$itemname = mysqli_real_escape_string($conn,$itemname);$description = mysqli_real_escape_string($conn, $description); // performs the insert query$query = "INSERT INTO items_info (item_name, description) VALUES ('$itemname','$description')"; if (!mysqli_query($conn,$query)) { die('Error: ' . mysqli_error($conn));}echo "One record added successfully"; mysqli_close($conn);?> Output: One record added successfully sagar0719kumar saurabh1990aror mysql SQLmysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Convert VARCHAR to INT SQL Query to Delete Duplicate Rows SQL indexes SQL Query to Compare Two Dates
[ { "code": null, "e": 23877, "s": 23849, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24204, "s": 23877, "text": "MySQLi (MySQL Improved) provides procedural and object oriented interface to data and its management. The i extension MySQL functions allows the user to access its database servers. The MySQL improved extension is specially designed to work with MySQL version 4.1.13 and new versions.Advantages of using prepared statements: " }, { "code": null, "e": 25135, "s": 24204, "text": "Prepared statements are highly efficient specially to avoid SQL injection attacks.The prepared statements are used repeatedly. It also reduces parsing time and overheads as the preparation of query is done only once.The database parses, compiles, optimizes the query statement and stores the result.Binding parameters with the query minimizes overall bandwidth as the parameters are sent whenever required, instead of sending the whole query.Binding parameters with placeholders are safer and easier as the proper formatting is automatically done.By sending the placeholder values to MySQL Server, it follows the client-server protocol.It executes a particular query statement multiple times with different set of variables effectively reducing the cost.It also saves on data copying and conversion.Prepared statements are less prone to errors as the statement is parsed at first and then the parsed values are used by the server." }, { "code": null, "e": 25218, "s": 25135, "text": "Prepared statements are highly efficient specially to avoid SQL injection attacks." }, { "code": null, "e": 25353, "s": 25218, "text": "The prepared statements are used repeatedly. It also reduces parsing time and overheads as the preparation of query is done only once." }, { "code": null, "e": 25437, "s": 25353, "text": "The database parses, compiles, optimizes the query statement and stores the result." }, { "code": null, "e": 25581, "s": 25437, "text": "Binding parameters with the query minimizes overall bandwidth as the parameters are sent whenever required, instead of sending the whole query." }, { "code": null, "e": 25687, "s": 25581, "text": "Binding parameters with placeholders are safer and easier as the proper formatting is automatically done." }, { "code": null, "e": 25777, "s": 25687, "text": "By sending the placeholder values to MySQL Server, it follows the client-server protocol." }, { "code": null, "e": 25896, "s": 25777, "text": "It executes a particular query statement multiple times with different set of variables effectively reducing the cost." }, { "code": null, "e": 25942, "s": 25896, "text": "It also saves on data copying and conversion." }, { "code": null, "e": 26074, "s": 25942, "text": "Prepared statements are less prone to errors as the statement is parsed at first and then the parsed values are used by the server." }, { "code": null, "e": 26514, "s": 26074, "text": "We cannot cover everything under this topic, but let us look into some of the important procedural functions of MySQLi .1. mysqli_connect(): As you know, before doing any database related operations, you need to establish a connection to the MySQL database server. If the connection is established successfully, then it returns a database connection resource identifier. If the connection encounters failure, then it just throws an error. " }, { "code": null, "e": 26518, "s": 26514, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connectionmysqli_connect($host, $dbuser, $dbpass, $dbname); // Check connectionif(mysqli_connect_error()){ echo \"Connection establishing failed!\";}else{ echo \"Connection established successfully.\";}?>", "e": 26837, "s": 26518, "text": null }, { "code": null, "e": 26847, "s": 26837, "text": "Output: " }, { "code": null, "e": 26885, "s": 26847, "text": "Connection established successfully. " }, { "code": null, "e": 27182, "s": 26885, "text": "2. mysqli_connect_error(): The MySQLi function throws an error when the connection is not made successfully and the function stores the error in previous call to mysqli_connect(). If no error is encountered , it returns NULL. If any error is encountered , then it returns an error message.Note: " }, { "code": null, "e": 27319, "s": 27182, "text": "To test mysqli_connect_error(), stop the MySQL server in XAMPP control panel and then call the above PHP code having mysqli_connect(). " }, { "code": null, "e": 27457, "s": 27319, "text": "If display_errors are enabled in PHP configuration, you can see an error of mysqli_connect_error() which returns the following message. " }, { "code": null, "e": 27521, "s": 27459, "text": "Connection failed as the target machine actively refused it. " }, { "code": null, "e": 27708, "s": 27521, "text": "Note: In good programming practice , its better NOT to show any error messages. For troubleshooting purpose, use mysqli_connect_error() to log the error as mentioned in the below code . " }, { "code": null, "e": 27712, "s": 27708, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connectionmysqli_connect($host, $dbuser, $dbpass, $dbname); // Check connectionif(mysqli_connect_error()){ echo \"Connection establishing failed!\";}else{ echo \"Connection established successfully.\";}?>", "e": 28031, "s": 27712, "text": null }, { "code": null, "e": 28141, "s": 28031, "text": "3. mysqli_select_db(): This mySQLi function is used to change the default database for making a connection. " }, { "code": null, "e": 28145, "s": 28141, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\";$dbtest = \"GFG_TEST\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); //write some code for database \"GFG\" // Change database to \"GFG_TEST\" mysqli_select_db($conn,$dbtest); // PHP code for database \"GFG_TEST\"... mysqli_close($conn);?>", "e": 28517, "s": 28145, "text": null }, { "code": null, "e": 28785, "s": 28517, "text": "Result: This will change the current database to GFG_TEST4. mysqli_debug(): Every web developer needs to refer to log files to start troubleshooting for improving the application performance. The above mySQLi function is used in the code for all debugging purposes. " }, { "code": null, "e": 28789, "s": 28785, "text": "php" }, { "code": "<?php//create a trace file in the localhostmysqli_debug(\"d:t:o,/temp/client.trace\");?>", "e": 28876, "s": 28789, "text": null }, { "code": null, "e": 29207, "s": 28876, "text": "Note: The user should compile the MySQL client library to make use of the above function to support debugging. This function on success will return TRUE.5. mysqli_close(): This MySQLi function is used to close a previously connected database. This function will return TRUE on successful closing, otherwise it will return FALSE. " }, { "code": null, "e": 29211, "s": 29207, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);//some php codeif(mysqli_close($conn))echo \"Connection closed successfully.\";?>", "e": 29475, "s": 29211, "text": null }, { "code": null, "e": 29485, "s": 29475, "text": "Output: " }, { "code": null, "e": 29518, "s": 29485, "text": "Connection closed successfully. " }, { "code": null, "e": 29707, "s": 29518, "text": "6. mysqli_prepare(): The above MySQLi function is used to prepare a MySQL query for execution. It returns a statement object for further operations and returns FALSE if some error occurs. " }, { "code": null, "e": 29711, "s": 29707, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // prepare the mysql query statement and bind parameters$query = mysqli_prepare(\"INSERT INTO items_info (item_name, description) VALUES (?, ?)\");$query->bind_param(\"ss\", $itemname, $description); // set parameters and execute$itemname = \"Shampoo\";$description = \"Hairfall preventing protein shampoo\"; $query->execute();echo \"New record inserted successfully\";mysqli_close();?>", "e": 30305, "s": 29711, "text": null }, { "code": null, "e": 30315, "s": 30305, "text": "Output: " }, { "code": null, "e": 30349, "s": 30315, "text": "New record inserted successfully " }, { "code": null, "e": 30444, "s": 30349, "text": "7. mysqli_query(): This MySQLi function performs or executes the query on the given database. " }, { "code": null, "e": 30448, "s": 30444, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // performs the insert querymysqli_query($conn,\"INSERT INTO items_info (item_name, description) VALUES ('Nailpolish', 'Colorbar Pink one')\"); echo \"Inserted successfully\";mysqli_close($conn);?>", "e": 30847, "s": 30448, "text": null }, { "code": null, "e": 30857, "s": 30847, "text": "Output: " }, { "code": null, "e": 30880, "s": 30857, "text": "Inserted successfully " }, { "code": null, "e": 31109, "s": 30880, "text": "8. mysqli_rollback(): The mysqli function rollsback the current transaction for the given database connection. Turn OFF the auto-commit, execute the query, then again commit the query and then rollback the current transaction. " }, { "code": null, "e": 31113, "s": 31109, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // Set autocommit to offmysqli_autocommit($conn,FALSE); // performs the insert querymysqli_query($conn,\"INSERT INTO items_info (item_name, description) VALUES ('Shoes', 'Adidas Brand')\"); echo \"Inserted successfully\";// Commit transactionmysqli_commit($conn); // Rollback transactionmysqli_rollback($conn);mysqli_close($conn);?>", "e": 31647, "s": 31113, "text": null }, { "code": null, "e": 31892, "s": 31647, "text": "9. mysqli_fetch_row(): The above MySQLi function is used to fetch one row from the result-set as an enumerated array. Each call to the above function will return the next row from the result set. If no rows are fetched, then it returns FALSE. " }, { "code": null, "e": 31896, "s": 31892, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"SELECT item_name,description from items_info\"; if ($result=mysqli_query($conn,$query)){ // Fetch one and one row while ($row=mysqli_fetch_row($result)) { echo \" Item name :\".$row[0].\" , \"; echo \" Description : \".$row[1]; echo nl2br (\" \\n \"); }//end while // Free result set mysqli_free_result($result);}// end ifmysqli_close($conn);?>", "e": 32457, "s": 31896, "text": null }, { "code": null, "e": 32695, "s": 32457, "text": "Result: It will show all the rows with Item name , Description 10. mysqli_field_count(): The above MySQLi function is used to return the number of columns for the most recent query. It returns total number of columns in the result set. " }, { "code": null, "e": 32699, "s": 32695, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"SELECT * from items_info\";mysqli_query($conn,$query);$total_columns = mysqli_field_count($conn);echo $total_columns;mysqli_close($conn);?>", "e": 33032, "s": 32699, "text": null }, { "code": null, "e": 33042, "s": 33032, "text": "Output: " }, { "code": null, "e": 33045, "s": 33042, "text": "4 " }, { "code": null, "e": 33199, "s": 33045, "text": "11. mysqli_fetch_array(): The above MySQLi function is used to fetch a row as an associative, numeric array or both types of array from the result set. " }, { "code": null, "e": 33203, "s": 33199, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"SELECT item_name,description from items_info\"; $result=mysqli_query($conn,$query);// Gets the Numeric array$row=mysqli_fetch_array($result,MYSQLI_NUM);echo \" Item name :\".$row[0];echo \",\";echo \" Description : \".$row[1];echo nl2br (\" \\n \");// Gets the Associative array$row=mysqli_fetch_array($result,MYSQLI_ASSOC);echo \" Item name :\".$row[\"item_name\"];echo \",\";echo \" Description : \".$row[\"description\"]; // Free the result setmysqli_free_result($result);mysqli_close($conn);?>", "e": 33876, "s": 33203, "text": null }, { "code": null, "e": 33886, "s": 33876, "text": "Output: " }, { "code": null, "e": 33899, "s": 33886, "text": "table array " }, { "code": null, "e": 34039, "s": 33899, "text": "12. mysqli_fetch_all(): The MySQLi function fetches all rows and return the result set as an associative array, a numeric array, or both. " }, { "code": null, "e": 34043, "s": 34039, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); $query = \"SELECT item_name from items_info\";$result = mysqli_query($conn,$query);$rowcount=mysqli_num_rows($result);// Gets the Associative array$row = mysqli_fetch_all($result,MYSQLI_ASSOC);print_r($row); for($i=0;$i<$rowcount;$i++){ echo \"<br> \".$row[$i]['item_name'];}// Free the result setmysqli_free_result($result);mysqli_close($conn);?>", "e": 34575, "s": 34043, "text": null }, { "code": null, "e": 34752, "s": 34575, "text": "Note: The above function is only available with MySQL Native Driver.13. mysqli_free_result(): The above MySQLi function free the memory of the fetched rows of the result set. " }, { "code": null, "e": 34756, "s": 34752, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"SELECT item_name,description from items_info\"; if ($result=mysqli_query($conn,$query)){ while ($row=mysqli_fetch_row($result)) { echo \" Item name :\".$row[0].\",\"; echo \" Description : \".$row[1]; echo nl2br (\" \\n \"); }//end while // Free result set mysqli_free_result($result);}// end ifmysqli_close($conn);?>", "e": 35291, "s": 34756, "text": null }, { "code": null, "e": 35301, "s": 35291, "text": "Output: " }, { "code": null, "e": 35364, "s": 35301, "text": "Item name :box, Description : square shaped box in red colour " }, { "code": null, "e": 35471, "s": 35364, "text": "14. mysqli_num_rows(): The above MySQLi function is used to return the number of rows of the result set. " }, { "code": null, "e": 35475, "s": 35471, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); $query = \"SELECT item_name,description from items_info\";if ($result=mysqli_query($conn,$query)){ //It returns the total number of rows of the result set $rowcount=mysqli_num_rows($result); echo \"Total number of rows of the result : \".$rowcount; // Free result set mysqli_free_result($result); }// end ifmysqli_close($conn);?>", "e": 35998, "s": 35475, "text": null }, { "code": null, "e": 36008, "s": 35998, "text": "Output: " }, { "code": null, "e": 36048, "s": 36008, "text": "Total number of rows of the result : 8 " }, { "code": null, "e": 36229, "s": 36048, "text": "15. mysqli_affected_rows(): The above MySQLi function is used to return the total number of affected rows from the previous MySQL SELECT, INSERT, UPDATE, DELETE or REPLACE query. " }, { "code": null, "e": 36233, "s": 36229, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"SELECT * FROM items_info\"; // performs the querymysqli_query($conn,$query);echo \"Total affected rows : \".mysqli_affected_rows($conn);mysqli_close($conn);?>", "e": 36584, "s": 36233, "text": null }, { "code": null, "e": 36594, "s": 36584, "text": "Output: " }, { "code": null, "e": 36619, "s": 36594, "text": "Total affected rows : 8 " }, { "code": null, "e": 36721, "s": 36619, "text": "16. mysqli_get_server_info(): The above MySQLi function is used to return the MySQL server version. " }, { "code": null, "e": 36725, "s": 36721, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);echo \"The MySQL server version is : \".mysqli_get_server_info($conn);mysqli_close($conn);?>", "e": 37000, "s": 36725, "text": null }, { "code": null, "e": 37010, "s": 37000, "text": "Output: " }, { "code": null, "e": 37048, "s": 37010, "text": "The MySQL server version is : 5.6.21 " }, { "code": null, "e": 37192, "s": 37048, "text": "17. mysqli_fetch_fields(): The above MySQLi function returns an array of objects which contains the information of columns of the result set. " }, { "code": null, "e": 37196, "s": 37192, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"SELECT item_name,description FROM items_info\"; if ($result=mysqli_query($conn,$query)) { // Get the fields $fields=mysqli_fetch_fields($result); foreach ($fields as $value) { echo \"Column name : \".$value->name.\"<br> \"; echo \"Table name : \".$value->table.\"<br> \"; echo \"Maximum length : \".$value->max_length.\"<br> \"; echo nl2br (\" \\n \"); } // Free result set mysqli_free_result($result);} mysqli_close($conn);?>", "e": 37832, "s": 37196, "text": null }, { "code": null, "e": 37842, "s": 37832, "text": "Output: " }, { "code": null, "e": 37982, "s": 37842, "text": "Column name : item_name\nTable name : items_info\nMaximum length : 18\n\nColumn name : description\nTable name : items_info\nMaximum length : 35 " }, { "code": null, "e": 38105, "s": 37982, "text": "18. mysqli_error(): The MySQLi function returns the error message for the last MySQL function call, if any error exists. " }, { "code": null, "e": 38109, "s": 38105, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);if (mysqli_connect_errno()) { echo \"Connection to MySQL server failed : \" . mysqli_connect_error(); } $query = \"INSERT INTO items_info (item_name) VALUES ('Jacket')\";// Check for error after performing the queryif (!mysqli_query($conn,$query)) { echo(\"Error occurred : \" . mysqli_error($conn)); } ?>", "e": 38599, "s": 38109, "text": null }, { "code": null, "e": 38727, "s": 38599, "text": "19. mysqli_autocommit(): This above MySQLi function is used in turning ON/OFF auto-committing database changes or operations. " }, { "code": null, "e": 38731, "s": 38727, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection $conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); mysqli_autocommit($conn,FALSE); // performs the insert querymysqli_query($conn,\"INSERT INTO items_info (item_name, description) VALUES ('Clock', 'Wall clock for the living room')\");//Commit the query transactionmysqli_commit($conn);echo \"Inserted successfully\";mysqli_close($conn);?>", "e": 39221, "s": 38731, "text": null }, { "code": null, "e": 39354, "s": 39221, "text": "20. mysqli_error_list(): The MySQLi function returns list of error messages for the last MySQL function call, if any error exists. " }, { "code": null, "e": 39358, "s": 39354, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); if (mysqli_connect_errno()) { echo \"Connection to MySQL server failed : \" . mysqli_connect_error(); }$query = \"INSERT INTO items_info (item_name) VALUES ('Jacket')\";// Check for error after performing the queryif (!mysqli_query($conn,$query)) { print_r(mysqli_error_list($conn)); } ?>", "e": 39837, "s": 39358, "text": null }, { "code": null, "e": 40019, "s": 39837, "text": "21. mysqli_begin_transaction(): The MySQLi function starts a transaction following the MySQL commands. It returns TRUE in case of successful execution, otherwise it returns FALSE. " }, { "code": null, "e": 40023, "s": 40019, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$query = \"INSERT INTO items_info (item_name, description) VALUES ('Bangles', 'Pink bangles')\";// performs the insert query mysqli_begin_transaction($conn, MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT); mysqli_query($conn,$query);mysqli_commit($conn);echo \"Inserted successfully\";mysqli_close($conn);?>", "e": 40517, "s": 40023, "text": null }, { "code": null, "e": 40643, "s": 40517, "text": "22. mysqli_change_user(): The MySQLi function is used to change the user of given database connection to the new database . " }, { "code": null, "e": 40647, "s": 40643, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\";$other_dbname = \"OTHER_GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); // reset to new databasemysqli_change_user($conn, $dbuser,$dbpass, $other_dbname);if ($result = mysqli_query($conn,\"SELECT database()\")){ $row = mysqli_fetch_row($result); echo \"Default database : \".$row[0];} mysqli_close($conn);?>", "e": 41099, "s": 40647, "text": null }, { "code": null, "e": 41109, "s": 41099, "text": "Output: " }, { "code": null, "e": 41139, "s": 41109, "text": "Default database : OTHER_GFG " }, { "code": null, "e": 41277, "s": 41139, "text": "23. mysqli_character_set_name(): The MySQLi function is used to return the default character set selected for the database connection . " }, { "code": null, "e": 41281, "s": 41277, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);$characterset = mysqli_character_set_name($conn);echo \"Default character set is: \" . $characterset; mysqli_close($conn);?>", "e": 41588, "s": 41281, "text": null }, { "code": null, "e": 41598, "s": 41588, "text": "Output: " }, { "code": null, "e": 41632, "s": 41598, "text": "Default character set is: latin1 " }, { "code": null, "e": 41762, "s": 41632, "text": "24. mysqli_real_escape_string(): The MySQLi function is used to escape special characters in a string for use in MySQL queries. " }, { "code": null, "e": 41766, "s": 41762, "text": "php" }, { "code": "<?php// Database configuration$host = \"localhost\";$dbuser = \"root\";$dbpass = \"\";$dbname = \"GFG\"; // Create database connection$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname); $itemname = \"matress's\";$description = \"Belongs to Mumbai's mall\"; // escape variables$itemname = mysqli_real_escape_string($conn,$itemname);$description = mysqli_real_escape_string($conn, $description); // performs the insert query$query = \"INSERT INTO items_info (item_name, description) VALUES ('$itemname','$description')\"; if (!mysqli_query($conn,$query)) { die('Error: ' . mysqli_error($conn));}echo \"One record added successfully\"; mysqli_close($conn);?>", "e": 42424, "s": 41766, "text": null }, { "code": null, "e": 42434, "s": 42424, "text": "Output: " }, { "code": null, "e": 42465, "s": 42434, "text": "One record added successfully " }, { "code": null, "e": 42482, "s": 42467, "text": "sagar0719kumar" }, { "code": null, "e": 42498, "s": 42482, "text": "saurabh1990aror" }, { "code": null, "e": 42504, "s": 42498, "text": "mysql" }, { "code": null, "e": 42513, "s": 42504, "text": "SQLmysql" }, { "code": null, "e": 42517, "s": 42513, "text": "SQL" }, { "code": null, "e": 42521, "s": 42517, "text": "SQL" }, { "code": null, "e": 42619, "s": 42521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42628, "s": 42619, "text": "Comments" }, { "code": null, "e": 42641, "s": 42628, "text": "Old Comments" }, { "code": null, "e": 42707, "s": 42641, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 42739, "s": 42707, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 42817, "s": 42739, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 42834, "s": 42817, "text": "SQL using Python" }, { "code": null, "e": 42849, "s": 42834, "text": "SQL | Subquery" }, { "code": null, "e": 42915, "s": 42849, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 42951, "s": 42915, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 42986, "s": 42951, "text": "SQL Query to Delete Duplicate Rows" }, { "code": null, "e": 42998, "s": 42986, "text": "SQL indexes" } ]
Add leading Zeros to Python string
We may sometimes need to append zeros as string to various data elements in python. There may the reason for formatting and nice representation or there may be the reason for some calculations where these values will act as input. Below are the methods which we will use for this purpose. Here we take a DataFrame and apply the format function to the column wher we need to append the zeros as strings. The lambda method is used to apply the function repeatedly. Live Demo import pandas as pd string = {'Column' : ['HOPE','FOR','THE','BEST']} dataframe=pd.DataFrame(string) print("given column is ") print(dataframe) dataframe['Column']=dataframe['Column'].apply(lambda i: '{0:0>10}'.format(i)) print("\n leading zeros is") print(dataframe) Running the above code gives us the following result − given column is Column 0 HOPE 1 FOR 2 THE 3 BEST leading zeros is Column 0 000000HOPE 1 0000000FOR 2 0000000THE 3 000000BEST The right justify function helps us in making the given values right justified by using the parameter we supply to the rjust function. In this example, we add three zeros to a value using rjust function. The number of zeros to be added can be made dynamic. Live Demo val = '98.6 is normal body temperature' print("The given string is :\n " + str(val)) #Number of zeros to be added i = 3 result = val.rjust(i + len(val), '0') print("adding leading zeros to the string is :\n" + str(result)) Running the above code gives us the following result − The given string is : 98.6 is normal body temperature adding leading zeros to the string is : 00098.6 is normal body temperature
[ { "code": null, "e": 1351, "s": 1062, "text": "We may sometimes need to append zeros as string to various data elements in python. There may the reason for formatting and nice representation or there may be the reason for some calculations where these values will act as input. Below are the methods which we will use for this purpose." }, { "code": null, "e": 1525, "s": 1351, "text": "Here we take a DataFrame and apply the format function to the column wher we need to append the zeros as strings. The lambda method is used to apply the function repeatedly." }, { "code": null, "e": 1536, "s": 1525, "text": " Live Demo" }, { "code": null, "e": 1804, "s": 1536, "text": "import pandas as pd\nstring = {'Column' : ['HOPE','FOR','THE','BEST']}\ndataframe=pd.DataFrame(string)\nprint(\"given column is \")\nprint(dataframe)\ndataframe['Column']=dataframe['Column'].apply(lambda i: '{0:0>10}'.format(i))\nprint(\"\\n leading zeros is\")\nprint(dataframe)" }, { "code": null, "e": 1859, "s": 1804, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1985, "s": 1859, "text": "given column is\nColumn\n0 HOPE\n1 FOR\n2 THE\n3 BEST\n\nleading zeros is\nColumn\n0 000000HOPE\n1 0000000FOR\n2 0000000THE\n3 000000BEST" }, { "code": null, "e": 2242, "s": 1985, "text": "The right justify function helps us in making the given values right justified by using the parameter we supply to the rjust function. In this example, we add three zeros to a value using rjust function. The number of zeros to be added can be made dynamic." }, { "code": null, "e": 2253, "s": 2242, "text": " Live Demo" }, { "code": null, "e": 2476, "s": 2253, "text": "val = '98.6 is normal body temperature'\nprint(\"The given string is :\\n \" + str(val))\n#Number of zeros to be added\ni = 3\nresult = val.rjust(i + len(val), '0')\nprint(\"adding leading zeros to the string is :\\n\" + str(result))" }, { "code": null, "e": 2531, "s": 2476, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2660, "s": 2531, "text": "The given string is :\n98.6 is normal body temperature\nadding leading zeros to the string is :\n00098.6 is normal body temperature" } ]
SAP UI5 - Quick Guide
SAP provides various tools that the users can use to enhance their user experience to create apps with rich user interfaces for Web business applications. The most common enablement tools include − Theme Designer NWBC and Side Panel FPM Screens SAP UI5 Development Tools Web-based apps that you create using SAP UI5 provides more consistent user experience and can be accessed on devices such as tablets, smartphones, and laptop. Using the NetWeaver gateway with UI5, you can define a clear separation between the user interface and business logic. SAP UI5 provides the following key features − Extensibility concepts at the code and application level. Ability to create complex UI patterns and predefined layouts for typical use cases. Model-View-Controller (MVC) and data binding methods. Keyboard interaction support and accessibility features. SAP UI5 is based on open standards like JavaScript, CSS, and HTML5. Theming support based on CSS. Following are the advantages of using SAP UI in business − It helps in increasing productivity. Increase user adaption. Less manual errors. Reduce the cost of training. High performance of SAP system. Perfectly designed API and can be consumed easily. Following is the list of recent UI5 versions that have been introduced. Each UI5 provides new features and enhancements from the previous versions, platform support, usability enhancements, etc. SAP UI5 1.26 SAP UI5 1.28 SAP UI5 1.30 SAP UI5 1.32 SAP UI5 1.34 SAP UI5 1.36 SAP UI5 1.38 and many more like SAP UI5 1.6 SAP UI5 uses 3-digit version number. For example, SAPUI5 1.36.5. Here, the digit (1) specifies the major version. The second digit (36) specifies the minor version number. The third digit specifies the patch version number (5). In each SAP UI5, the major and minor version as well as the patch version can be used to identify the patches. SAP UI5 and Open UI5, both provide the UI development environment. However, they are different from each other in the following aspects − SAP UI5 is part of SAP product suite and is not a separate license. It is integrated with different SAP products like − SAP NW 7.4 or higher SAP NetWeaver AS 7.3x SAP HANA Cloud and on premise solution Open UI5 is an open source technology for application development and it was released with Apache 2.0. SAP HANA SAP HANA Cloud Platform SAP NetWeaver higher releases Open UI5 was introduced with Apache 2.0 license OpenUI5 is Open Source, and is available on GitHub SAP UI5 supports all the main browsers from Microsoft, Google and Firefox with latest releases. However, features supported varies with the browser version and the vendor. In SAP UI5 architecture, you have three layers − At the top, is the presentation layer, where UI5 components are consumed by devices like mobile, tablets, and laptops. At the top, is the presentation layer, where UI5 components are consumed by devices like mobile, tablets, and laptops. At the middle layer, is the application clients that includes SAP UI5 libraries for theming and control. UI5 control libraries include Sap.viz Sap.ui.commons (Controls like text fields and buttons) Sap.ui.table (Input controls for table) Sap.ui.ux3 Sap.m (Includes input control for mobile devices) At the middle layer, is the application clients that includes SAP UI5 libraries for theming and control. UI5 control libraries include Sap.viz Sap.viz Sap.ui.commons (Controls like text fields and buttons) Sap.ui.commons (Controls like text fields and buttons) Sap.ui.table (Input controls for table) Sap.ui.table (Input controls for table) Sap.ui.ux3 Sap.ui.ux3 Sap.m (Includes input control for mobile devices) Sap.m (Includes input control for mobile devices) At the bottom, is the option server component. This includes SAP NetWeaver Application Server for ABAP/Java, SAP backend, HANA XS engine for development or database. At the bottom, is the option server component. This includes SAP NetWeaver Application Server for ABAP/Java, SAP backend, HANA XS engine for development or database. SAP UI5 has multiple components which are independent and reusable objects in UI5 application. These components can be developed by different people and can be used in different projects. An application can use the components from different locations and hence you can easily get the structure of an application. You can create different types of components under SAP UI5 development. Faceless components are used to get the data from the backend system and they don’t contain a user interface. Example− They are a part of class sap.ui.core.component UI components are used to add rendering functionality and represent a screen area or element on the user interface. Example − UI component can be a button with settings to perform some task. It is a part of class: sap.ui.core.UIComponent Note − sap.ui.core.component is the base class for faceless and UI components. To define the extensibility function, the components can inherit from the base class or from other components in UI development. The module name of a component is known as the package name, and .component where the package name is defined as the name of the parameter passed to the component constructor. SAP UI5 components can also be divided as per the system landscape − Client side component: This includes, Control libraries sap.m, sap.ui.common, etc. Core Javascript Test includes HTML and Javascript Control libraries sap.m, sap.ui.common, etc. Core Javascript Test includes HTML and Javascript Server side component Theming Generator Control and application development tools in Eclipse Resource handler Theming Generator Control and application development tools in Eclipse Resource handler Each component is represented in the form of a folder and contains the name of the components and the resources required to manage the component. Each component should contain the following files − Component.json file that contains metadata for design time and is used only for design time tools. Component.json file that contains metadata for design time and is used only for design time tools. Component.js is used to define properties, events, and components methods that are responsible for runtime metadata. Component.js is used to define properties, events, and components methods that are responsible for runtime metadata. To create a new component, you have to create new folder. Let us name this as button. Next is to create the component.js file Then, you have to extend UI component base class sap.ui.core.UIComponent.extend and enter the name of the component and package path. Later, to define a new component, you have to start with the require statement as follows − // defining a new UI Component jQuery.sap.require("sap.ui.core.UIComponent"); jQuery.sap.require("sap.ui.commons.Button"); jQuery.sap.declare("samples.components.button.Component"); // new Component sap.ui.core.UIComponent.extend("samples.components.button.Component", { metadata : { properties : { text: "string" } } }); samples.components.button.Component.prototype.createContent = function(){ this.oButton = new sap.ui.commons.Button("btn"); return this.oButton; }; /* * Overrides setText method of the component to set this text in the button */ samples.components.button.Component.prototype.setText = function(sText) { this.oButton.setText(sText); this.setProperty("text", sText); return this; }; The next step is to define the component.json in your folder as follows − { "name": "samples.components.button", "version": "0.1.0", "description": "Sample button component", "keywords": [ "button", "example" ], "dependencies": { } } To use a component, you have to wrap the component in a component container. You cannot directly use a UI component in a page using placeAt method. Another way is to pass the component to the componentContainer constructor. It includes adding the component to the container and using placeAt method to place the component on the page. var oComp = sap.ui.getCore().createComponent({ name: "samples.components.shell", id: "Comp1", settings: {appTitle: "Hello John"} }); var oCompCont = new sap.ui.core.ComponentContainer("CompCont1", { component: oComp }); oCompCont.placeAt("target1"); //using placeAt method A component container carries specific settings and also contains the lifecycle methods of a regular control. The following code segment shows how to pass the component to the componentContainer constructor. var oCompCont2 = new sap.ui.core.ComponentContainer("CompCont2", { name: " samples.components.shell", settings: {text: "Hello John 1"} }); oCompCont2.placeAt("target2"); There are various JavaScript and CSS libraries that you can use in combination for the application development. SAPUI5 can use these libraries in combination and they are called SAPUI5 control libraries. Common SAPUI5 control libraries − Sap.ui.commons for control fields, buttons, etc. Sap.m is the most common control library and is used for mobile devices Sap.ui.table includes table control Sap.ui.ux3 Note − SAPUI5 control library sap.m is the most common library and is used for application development. These libraries can be combined with other control libraries. You can use the control library sap.m with other control libraries - sap.ui.unified, sap.viz, sap.ui.table, sap.ui.layout, and sap.suite. You can use the control library sap.m with other control libraries - sap.ui.unified, sap.viz, sap.ui.table, sap.ui.layout, and sap.suite. You can combine control libraries - sap.ui.commons, sap.ui.table, sap.ui.ux3 and sap.ui.suite with each other. You can combine control libraries - sap.ui.commons, sap.ui.table, sap.ui.ux3 and sap.ui.suite with each other. You can also combine control library sap.ui.commons and sap.ui.ux3 with other libraries like sap.ui.core, sap.ui.unified, sap.ui.layout, and sap.ui.table. You can also combine control library sap.ui.commons and sap.ui.ux3 with other libraries like sap.ui.core, sap.ui.unified, sap.ui.layout, and sap.ui.table. You can combine sap.viz with all other libraries. You can combine sap.viz with all other libraries. The following table shows the main SAPUI5 control libraries and their description − SAP UI5 development kit for HTML5 provides you an environment for the development of web-based applications and it provides an application with one consistent user experience. Web apps that you develop with SAP UI5 are responsive across browsers and devices, and they can run on smartphones, tablets, and desktops. The UI controls automatically adapt themselves to the capabilities of each device. You can use SAP UI5 on the following platforms − SAP HANA SAP HANA Cloud Platform SAP NetWeaver for SAP NetWeaver 7.4 or higher User interface add-on for SAP NetWeaver for SAP NetWeaver Application Server 7.3x You can deploy the application on the server that includes storing the libraries and getting data from the database. You can use the NetWeaver Application server or HANA Cloud platform for application deployment, and data can be accessed by a business application using the OData model using Gateway. Take a look at the following illustration. When a user sends a client request from his mobile/laptop, a request is sent to the server to load the application in a browser, and data is accessed via database and the relevant libraries are accessed. To build a UI5 application, you can download the SAP UI5 developer’s tools of Eclipse. Once you download, you can unzip the file and deploy on the web server. For ABAP, you can install a UI Add-On for SAP NetWeaver and this also includes UI5 Theme Designer. To install and update UI5 development toolkit for HTML5, you should meet the following prerequisites − Only relevant when installing the SAP UI5 ABAP Repository Team Provider For Windows OS: SAP GUI for Windows 7.30/7.40 Only relevant when installing the SAP UI5 ABAP Repository Team Provider For Windows OS: DLLs VS2010 for communication with the back-end system is required Note: Install either the x86 or the x64 variant, accordingly to your 32 or 64-Bit Eclipse installation Let us now proceed and discuss how you can install the SAP UI5 Development Kit in your system. Step 1 − To install JDK, go to Oracle.com and search for the required JDK version. Step 2 − Download and run the setup. You will get a message as shown in the following screenshot. Step 3 − To install Eclipse, go to www.Eclipse.org/downloads Step 4 − Extract the file as shown in the following screenshot. Step 5 − To run the installation, go to the extracted folder and run the application file as shown in the following screenshot. Step 6 − To install SAPUI5 tools, go to Eclipse → Help → Install New software. You can install directly using the URL or by entering the path of UI5 demo kit. Step 7 − Next, enter the URL in install dialog https://tools.hana.ondemand.com/mars Step 8 − To see the available features. Press the ENTER key. You can select the features and click on Next. It will display the list of features to be installed → Click Next. Step 9 − Accept the license agreement and click Finish to start the installation. Step 10 − Download UI Development Kit for HTML 5 from the following link − http://scn.sap.com/community/developer-center/front-end and extract the content in the same folder. Step 11 − Start the Eclipse environment. Go to Help → Install New Software. Step 12 − Click Add → Local. Step 13 − Next, navigate to the local update site location and select the tool-update site folder with the folder where you extracted the HTML5 Development toolkit as the update source. Step 14 − Select all plugins and features for installation. Step 15 − Select the dialog to “Contact all update sites” during the installation to find the required software. Step 16 − Click the Finish button to complete the setup. Restart Eclipse. Step 17 − You can verify the installation by creating a new SAPUI5 Application Project via Eclipse menu File → New → Other at the bottom. Select SAP UI5 Application Development folder and expand to create a new project. Step 18 − Enter the project name, select library and you can check the box to create an initial view. Step 19 − Create a view using some sample code in the project. Enter the name of the view and click the Next button. Step 20 − Select the development paradigm and click on Finish. You will see a new SAPUI5 development project in a new window as shown in the following screenshot. Now, to present your application or run it in production, you can deploy your SAPUI5 application on the tomcat server. If you don’t have a tool like MAVEN, in that you can use the export option to export the project manually. Right-click on Project → Export. Step 21 − Enter the destination path where you want to place the war file. Next, copy the war-File to webapps directory of your apache tomcat. You can access your application by going to this path - http://localhost:8080/<your_app>/ Note − In a normal scenario, many SAP projects run in Internet Explorer but for SAPUI5 development it is recommended to use Google Chrome or Firefox with firebug plugin as both systems allow the use of tools and plugins to debug JavaScript, as well as use HTML and CSS. Model-View-Controller (MVC) concept is used in SAP UI5 development to keep the application data separate from the user interactions. This allows you to develop the web applications and make changes to the applications independently. Model-View-Controller plays a different role in UI development − The Model is responsible for managing the application data in the database/backend. The Model is responsible for managing the application data in the database/backend. The View is responsible for defining the user interface to users. When a user sends a requests from his device, the view is responsible for data view as per the request submitted. The View is responsible for defining the user interface to users. When a user sends a requests from his device, the view is responsible for data view as per the request submitted. The Controller is used to control the data and view events as per user interaction by updating the view and model. The Controller is used to control the data and view events as per user interaction by updating the view and model. You can define Model-View-Controller concept in SAPUI5 with the following features − Model acts as a bridge between the view and the application data. Model is used to get the request from the view and respond as per the user’s input. Model doesn’t depend on classes. View is responsible to manage information display to the users. Views are based on Model. Controller is responsible for taking the input given by devices and communicates to model/view and to trigger correct action. Controller is responsible for taking the input given by devices and communicates to model/view and to trigger correct action. Controllers are based on model. Controllers are based on model. SAP UI5 offers Views and Controllers in the form of single files − sap.ui.core.mvc.XMLView sap.ui.core.mvc.JSView sap.ui.core.mvc.Controller sap.ui.core.mvc.JSONView JSON model is a client-side model and is used for small data sets. JSON model supports two-way binding. Data binding concept is mentioned in the latter half of this tutorial. JSON model can be used to bind controls to JavaScript object data. XML model can be used to bind controls to XML data. XML is also a client side model and hence is used only for small data sets. XML model doesn’t provide any mechanism for server-based paging or loading of deltas. XML model also supports two-way data binding. Views are defined using SAP libraries as follows − XML with HTML, mixed, or Standalone: Library- sap.ui.core.mvc.XMLView JavaScript: Library- sap.ui.core.mvc.JSView JSON: Library - sap.ui.core.mvc.JSONView HTML: Library - sap.ui.core.mvc.HTMLView Sap.ui.jsview(“sap.hcm.address”, { getControllerName: function() { return “sap.hcm.address”; }, createContent: function(oController) { var oButton = new sap.ui.commons.Button({ text: “Hello” }); oButton.attachPress(function() { oController.Hello(); }) Return oButton; } }); <template data-controller-name = ”sap.hcm.address’> <h1>title</h1> <div> Embedded html </div> <div class = ”test” data-sap-ui-type = ”sap.ui.commons.Button” Id = ”Button1” data-text = ”Hello” Data-press = ”sayHello”> </div> </template> Similarly, you can create JSON view derived from sap.ui.core.mvc.JsonView. { “type”:”sap.ui.core.mvc.JsonView”, “controllerName”:”sap.hcm.address”, ............................ ........................ ......................... } The following table lists key features associated with MVC concept and comparison of different view types w.r.t the features. SAPUI5 Developer Studio provides tools to ease the UI5 development process. Following are the functions − Wizard for Control development Wizard for Project creation Wizard for View/Controller creation You can download it from SAP Marketplace using the link https://support.sap.com/software.html. Search for UI Add-on 1.0 for NetWeaver. Go to Software downloads and enter your Id and password. Then, go to support packages and patches. Search for sapui5 tools ide plugin 1.00. A trail of SAPUI5 framework is also available under SCN. You can go to this link http://scn.sap.com/community/developer-center/front-end Step 1 − To create a new project in UI5 developer Studio, go to File → New → Project. Step 2 − Enter the name of project, target device, and Create an Initial View. Step 3 − Enter the View name and View type in the next window and click Next. Step 4 − In the last window, you see the project summary. It shows you the project properties. Click the Finish button to create the project. Step 5 − You will be prompted to switch to Java EE perspective. Click Yes and it will open a new UI5 project window with an initial view - JSView. Step 6 − Now to add a Shell to this view, you can use the library sap.ui.ux3.Shell(). Step 7 − As Shell is not part of sap.ui.commons, you need to add sap.ui.ux3 library. You can add additional libraries to data-sap-ui-libs. To run an application, you have two options − Run on server Run on webapp Run on server is recommended as it has a fixed port and it is not like run on webapp with one-time random port. As shown in the following table, you can define various configuration attributes in SAP UI5 − The core functions in SAP UI5 are as follows − Sap.ui.getCore() − This is used to get a core instance. Sap.ui.getCore() − This is used to get a core instance. Sap.ui.getCore().byid(id) − This is used to get an instance of UI5 control created with id. Sap.ui.getCore().byid(id) − This is used to get an instance of UI5 control created with id. Sap.ui.getCore().applyChanges() − This is used to carry out and render the changes for UI5 controls immediately. Sap.ui.getCore().applyChanges() − This is used to carry out and render the changes for UI5 controls immediately. jQuery.sap.domById(id) − This is used to get any HTML element with id. If there is a UI5 control with id, the element returned is top most HTML element of UI5 control. jQuery.sap.domById(id) − This is used to get any HTML element with id. If there is a UI5 control with id, the element returned is top most HTML element of UI5 control. jQuery.sap.byId(id) − This is used to return jQuery object of DOM element with specified Id. jQuery.sap.byId(id) − This is used to return jQuery object of DOM element with specified Id. There are different types of UI controls that you can use while developing UI5 applications. These controls allow you to add a button, table, images, layout, combo box, and various other controls in UI5 application. Common control types include − Simple Controls Complex Controls UX3 Controls Dialogs Layout Var image = new sap.ui.commons.Image(); Image.setSrc(“Image1.gif”); Image.setAlt(“alternat.text”); You can use a combo box to provide predefined entries. Properties − items, selectedKey Var oComboBox2 = new sap.ui.commons.ComboBox (“ComboBox”,{ Items:{path:”/data”, Template:oItemTemplate, filters:[oFilter]}, Change: function(oEvent){ Sap.ui.getCore(). byId(“field”).setValue( oEvent.oSource.getSelectedKey()); } }); Use attachPresss assign event handler for a push action. Var oButton = new sap.ui.commons.Button ({text : “Click”, Press: oController.update }); To autocomplete the entered value. Var uiElement = new sap.ui.commons.AutoComplete({ Tooltip: ”Enter the product”, maxPopupItems: 4 }); For (var i = 0; i<aData.lenght; i++){ uiElement.addItem(new sap.ui.core.ListItem( {text: aData[i].name})); } It is derived from sap.ui.table and each table contains columns. Var oTable = new sap.ui.table.Table({ Columns: [ New sap.ui.table.Column({ Label: new sap.ui.commons.lable({ text: “First Column”}), Template: new sap.ui.commons.TextView({ text: “{Firstcolumn}” }), Width: “120px” }) In SAP UI5, data binding concept is used to update the data automatically by binding the data with the controls that holds the application data. Using data binding, you can bind simple controls like text field, simple button to application data, and data is automatically updated when there is a new value. Using two-way data binding, application data is updated when the value of bound control changes. The value can be changed via different methods, like user input, etc. In SAP UI5, different data models can be used for data binding. These data models support different features − JSON model is used to bind JavaScript objects to controls. This data model is a client-side model and is suggested for small data sets. It doesn’t provide any mechanism for serverside paging or loading. Key features include − JSON model for data binding supports data in JavaScript notation format. It supports two-way data binding. Creating a model instance − Var oModel = new sap.ui.model.json.JSONModel(dataUrlorData); XML model of data binding allows you to bind the controls to XML data. It is used for clientside objects and for small data sets. It doesn’t provide any mechanism for server-side paging or loading. Key features include − XML model of data binding supports XML data. It also supports two-way data binding. Creating a model instance − Var oModel = new sap.ui.model.xml.XMLModel(dataUrlorData); OData model is a server-side model, so entire data is available at the server side. Client side can see only rows and fields and you can’t use sorting and filtering at the client side. There is a need to send this request to the server to complete these tasks. Data binding in OData model is one way but you can enable two-way binding using experimental write support. Key features include − OData model of data binding supports Odata compliant data. This data model allows you to create OData requests and handle responses. It supports experimental two-way binding. Creating a model instance − Var oModel = new sap.ui.model.odata.ODataModel (dataUrl [,useJSON, user, pass]); You can use the setModel method to assign the model to specific controls or core. Sap.ui.getcore().setModel(oModel); To bind a model to view − Var myView = sap.ui.view({type:sap.ui.core.mvc.ViewType.JS, viewname:”view name”}); myView.setModel(oModel); To bind a model to a control − Var oTable = sap.ui.getCore().byId(“table”); oTable.setModel(oModel); You can bind the properties of a control to model properties. You can bind the properties of a model to a control using bindproperty method − oControl.bindProperty(“controlProperty”, “modelProperty”); or by using below methodvar oControl = new sap.ui.commons.TextView({ controlProperty: “{modelProperty}” }); You can use aggregation binding to bind a collection of values like binding multiple rows to a table. To use aggregation, you have to use a control that acts as a template. You can define aggregation binding using bindAgregation method. oComboBox.bindaggregation( “items”, “/modelaggregation”, oItemTemplate); Design Pattern is a new term in SAP UI5 development when we talk about SAP development or SAP Fiori system. SAP is working hard to find new design patterns that support development in SAP system using UI5 SDK. SAP has released different types of design patterns − This is a first step in application binding and is supported by SplitApp control of SAP UI5. This design pattern supports the list of content and allows lead selection and detailed view. This design pattern displays the detail of transaction in the detail section. Example − You are placing an order online and you want to see a confirmation page that displays what you are buying and display the detail of the transaction with detailed view. This design pattern is mostly recommended for displaying charts, pictorial data, and various types of graphs. This design pattern is recommended when you are using a complex application flow and there is a need to make use of all design patterns to build a working application. In SAPUI5 development for larger JavaScript applications, UI5 framework provides built in support for modularization. Modularization concept allows you to split application into smaller parts and they can be combined together at run time. These smaller application parts are called modularization. You can declare your own JavaScript module by calling the query jQuery.sap.declare function and this is used to keep track of the module name and already loaded module. To load a module, you have to use jQuery.sap.require <script> jQuery.sap.require(“sap.ui.commons.MessageBox”); ........................... </script> When a module is required jQuery.sap.require and that module is not loaded, it automatically loads. It calls the declare method so when require is called it knows that the module has been loaded. SAP UI5 supports localization concept based on Java platform. Identifying the Language Code − For the identification of languages, the framework uses a language code of type string. Resource Bundles − A resource bundle file is a Java properties file and contains key/value pairs where the values are language-dependent texts and the keys are language independent and used by the application to identify and access the corresponding values. Resource bundles are a collection of *.properties files. All files are named with the same base name (prefix identifying the resource bundle), an optional suffix that identifies the language contained in each file, and the fixed .properties extension. The language suffixes are formed according to the older JDK locale syntax. By convention, a file without a language suffix should exist and contain the raw untranslated texts in the developer's language. This file is used if no more suitable language can be found. Resource bundle sap.ui.commons.message_bundle contains the following files − sap.ui.commons.message_bundle.properties − This file carries the raw text from the developer and it determines the set of keys. sap.ui.commons.message_bundle.properties − This file carries the raw text from the developer and it determines the set of keys. sap.ui.commons.message_bundle_en.properties − This file carries English text. sap.ui.commons.message_bundle_en.properties − This file carries English text. sap.ui.commons.message_bundle_en_US.properties − This file carries text in American English. sap.ui.commons.message_bundle_en_US.properties − This file carries text in American English. sap.ui.commons.message_bundle_en_UK.properties − This file carries text in British English. sap.ui.commons.message_bundle_en_UK.properties − This file carries text in British English. SAPUI5 provides two options to use localized texts in applications – the jQuery.sap.resources module and data binding. The following code is used to get resource bundle for a given language − jQuery.sap.require(“jquery.sap.resources”); var oBundle = jQuery.sap.resources({url ; sUrl, locale:sLocale}); The following code is used to access the text in resource bundle − Var sText = oBundle.getText(sKey); The following code is used to get URL of a resource − Var sUrl = sap.ui.resource(“sap.ui.table”,”messagebundle.properties”); A Control is used to define the appearance and screen area. It contains properties likewidth and text. These properties are used to modify the appearance or change the data displayed by the control. You can create aggregate controls or associated controls. Associated control of a control is defined as loosely related controls, which are not child controls or a part of the main control. Controls are used to trigger well-defined events. Controls in SAPUI5 can be created directly using a tool or JavaScript file. Controls that are created using the extend() method are also known as Notepad controls. The following code is used to define a Control using the Extend method − Sap.ui.core.control.extend (sname, oDefinition); The parameters that are passed to this control − Name of the control Definition of the control The definition of a control contains information about control API, aggregations, events, etc. and implementation methods. You can also create custom controls. Definition of custom control can contain public and private methods, metadata, and rendering method, etc. metadata:{ properties: {}, events: {}, aggregations: {} }, publicMethod: function() {}, _privateMethod: function() {}, init: function() {} onclick: function(e) {}, renderer: function(rm, oControl) {} Creating a new control inherits from Button − Sap.ui.commons.Button.extend (sname, oDefinition); The metadata in control definition consists of objects for control properties, events, and aggregations. Type: data type of control property String: string for a string property Int or float for number properties Int[] for an integers array String[] for an string array Events are defined by the name event only. You normally pass an empty object to an event. Application use enablePreventDefault flag to interrupt the event. Events: { Logout:{}, Close: { enablePreventDefault : true } } You can extend UI5 applications that are either remote or in Web IDE. To create a new Extension project, you should have an application remotely or on IDE. Step 1 − To create a new Project, go to File → Extension Project. Step 2 − Select the Workspace to select the desired SAP Fiori application that you want to use as your original application. Step 3 − When you select an application, Extension Project Name field is populated with the name of the original application with the suffix extension. You can change this name → Next Step 4 − If necessary, select the Open extension project in extensibility pane checkbox to automatically open the extensibility pane after the project is generated. Step 5 − Click Finish. Similarly, you can also extend applications that reside in SAP HANA Cloud platform. Follow the steps given below. Step 1 − To create a new Project, go to File → Extension Project. Step 2 − Select the start → Remote → SAP HANA Cloud Platform → Select Application from SAP HANA Cloud Platform dialog box. Step 3 − In the next window, you have to enter SAP HANA Cloud Platform account, user name, and password. Step 4 − Select Get Applications and search for the application that you want to extend. Step 5 − Select the desired application → OK. The Extension Project Name field is automatically populated in the wizard. If necessary, you can edit this name. Step 6 − Click Next. Choose Finish to confirm and create your extension project. The UI theme designer is a browser-based tool that allows you to develop your themes by modifying one of the theme templates provided by SAP. Example − You can change the color scheme, or add your company's logo. The tool provides a live preview of the theme while you are designing. Apply your corporate branding and look to applications built with SAP UI technologies. The UI theme designer is a browser-based tool for cross-theming scenarios. Use it to easily build your corporate identity themes by modifying one of the theme templates provided by SAP. For example, you can change the color scheme, or add your company's logo. The tool is targeted at different user groups, including developers, visual designers, and administrators. SAP NetWeaver as ABAP (via UI Add-On 1.0 SP4) SAP NetWeaver Portal (7.30 SP10 and higher version) SAP HANA Cloud (Planned) SAP NetWeaver Portal (7.02 Planned) Browser-based, graphical WYSIWYG editor − Changes the values of theming parameters and immediately sees how it affects the visualization of the selected preview page. Browser-based, graphical WYSIWYG editor − Changes the values of theming parameters and immediately sees how it affects the visualization of the selected preview page. Built-in preview pages − Select built-in preview pages to see what your custom theme will look like when it is applied to an application − Application previews (Example: Purchase Order Approval, SAP Fiori Launchpad) Control previews Built-in preview pages − Select built-in preview pages to see what your custom theme will look like when it is applied to an application − Application previews (Example: Purchase Order Approval, SAP Fiori Launchpad) Application previews (Example: Purchase Order Approval, SAP Fiori Launchpad) Control previews Control previews Different levels of theming − Quick theming (basic cross-technology theme settings) Expert theming (technology-specific theme settings) Manual LESS or CSS editing Different levels of theming − Quick theming (basic cross-technology theme settings) Quick theming (basic cross-technology theme settings) Expert theming (technology-specific theme settings) Expert theming (technology-specific theme settings) Manual LESS or CSS editing Manual LESS or CSS editing Color palette for reuse − Specifies a set of parameters with the main color values defining your corporate branding. Color palette for reuse − Specifies a set of parameters with the main color values defining your corporate branding. Cross-technology theming − Create one consistent theme that applies to various SAP UI clients and technologies − SAPUI5 standard libraries (including SAP Fiori applications and SAP Fiori Launchpad) Unified Rendering technologies (such as Web Dynpro ABAP and Floorplan Manager) SAP NetWeaver Business Client Cross-technology theming − Create one consistent theme that applies to various SAP UI clients and technologies − SAPUI5 standard libraries (including SAP Fiori applications and SAP Fiori Launchpad) SAPUI5 standard libraries (including SAP Fiori applications and SAP Fiori Launchpad) Unified Rendering technologies (such as Web Dynpro ABAP and Floorplan Manager) Unified Rendering technologies (such as Web Dynpro ABAP and Floorplan Manager) SAP NetWeaver Business Client SAP NetWeaver Business Client You can theme applications that do not use the following UI elements: HTMLIsland HTMLContainer Chart FlashIsland SilverlightIsland BusinessGraphics You can only consume themes created with the UI theme designer for Web Dynpro ABAP applications as of SAP NetWeaver 7.0 EHP2 NWBC for Desktop (4.0 or higher): You can theme NWBC shell and overview pages (index page, new tab page, service map). NWBC for HTML (3.6): You can theme the service map. The shell cannot be themed. Step 1 − Login to SAP Fiori Front-End server. You can use T-Code: Theme Designer or use shortcut as shown in the following screenshot and login. Step 2 − Once you login, you will have all the default templates provided by SAP for Theme Designer. Select the default theme and click Open. Step 3 − Enter the Fiori Launchpad link and Name of the application and click Add. Step 4 − From the right side of the screen panel, you can select Color, Font, Image and other properties. You can edit colors as shown in the following screenshots. Step 5 − To save the Theme, you can click the Save icon as shown in the following screenshot. You also have an option for save and build option. Once you click Save and Build, it will start saving and when completed, you will get a confirmation message - Save and Build completed. Step 6 − To get the link of this Custom Theme, use T-code as shown in the following screenshot − Step 7 − Select the Theme that you have created and click the Info tab. Step 8 − Use Ctrl+Y to copy the URL from the screen and make a note of this. These are the default themes that are shipped with UI5 − Blue Crystal Gold Reflection Mobile Visual Identify High Contrast Black There are various chart types in sap.viz.ui5 charting library that can be used to represent the business data. Following are some CVOM chart types- Column, Bubble, Line, Pie, etc. SAP UI5 applications run on different mobile devices like iPad and smartphones. However, for better user experience, you need to control the appearance, touch interactions, and various other UI parameters. UI5 contains a control library sap.m that supports application development for mobile devices and supports all key concepts like data binding, MVC, etc. Platform support for Android, iOS, BlackBerry It contains 40 controls Webkit browsers - Google Chrome UI5 concepts - MVC, localization, modularization, etc. In this chapter, we will learn how to create a project in Web IDE. Let’s go step by step. Step 1 − To start a new project, go to File → New → Project Step 2 − Enter the name of the project. In the next window, select the template. Step 3 − Select template SAPUI5 Mobile Applications → Next Step 4 − The next step is to select the data connection. Select service URL → Select Step 5 − In the next step, you have to perform template customization. Step 6 − On clicking Next, you will see the Finish button. Once you click Finish, you can see a new project created that has default structure of UI application. It contains the view, model, and name of the project. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 2041, "text": "SAP provides various tools that the users can use to enhance their user experience to create apps with rich user interfaces for Web business applications. The most common enablement tools include −" }, { "code": null, "e": 2254, "s": 2239, "text": "Theme Designer" }, { "code": null, "e": 2274, "s": 2254, "text": "NWBC and Side Panel" }, { "code": null, "e": 2286, "s": 2274, "text": "FPM Screens" }, { "code": null, "e": 2312, "s": 2286, "text": "SAP UI5 Development Tools" }, { "code": null, "e": 2590, "s": 2312, "text": "Web-based apps that you create using SAP UI5 provides more consistent user experience and can be accessed on devices such as tablets, smartphones, and laptop. Using the NetWeaver gateway with UI5, you can define a clear separation between the user interface and business logic." }, { "code": null, "e": 2636, "s": 2590, "text": "SAP UI5 provides the following key features −" }, { "code": null, "e": 2694, "s": 2636, "text": "Extensibility concepts at the code and application level." }, { "code": null, "e": 2778, "s": 2694, "text": "Ability to create complex UI patterns and predefined layouts for typical use cases." }, { "code": null, "e": 2832, "s": 2778, "text": "Model-View-Controller (MVC) and data binding methods." }, { "code": null, "e": 2889, "s": 2832, "text": "Keyboard interaction support and accessibility features." }, { "code": null, "e": 2957, "s": 2889, "text": "SAP UI5 is based on open standards like JavaScript, CSS, and HTML5." }, { "code": null, "e": 2987, "s": 2957, "text": "Theming support based on CSS." }, { "code": null, "e": 3046, "s": 2987, "text": "Following are the advantages of using SAP UI in business −" }, { "code": null, "e": 3083, "s": 3046, "text": "It helps in increasing productivity." }, { "code": null, "e": 3107, "s": 3083, "text": "Increase user adaption." }, { "code": null, "e": 3127, "s": 3107, "text": "Less manual errors." }, { "code": null, "e": 3156, "s": 3127, "text": "Reduce the cost of training." }, { "code": null, "e": 3188, "s": 3156, "text": "High performance of SAP system." }, { "code": null, "e": 3239, "s": 3188, "text": "Perfectly designed API and can be consumed easily." }, { "code": null, "e": 3434, "s": 3239, "text": "Following is the list of recent UI5 versions that have been introduced. Each UI5 provides new features and enhancements from the previous versions, platform support, usability enhancements, etc." }, { "code": null, "e": 3447, "s": 3434, "text": "SAP UI5 1.26" }, { "code": null, "e": 3460, "s": 3447, "text": "SAP UI5 1.28" }, { "code": null, "e": 3473, "s": 3460, "text": "SAP UI5 1.30" }, { "code": null, "e": 3486, "s": 3473, "text": "SAP UI5 1.32" }, { "code": null, "e": 3499, "s": 3486, "text": "SAP UI5 1.34" }, { "code": null, "e": 3512, "s": 3499, "text": "SAP UI5 1.36" }, { "code": null, "e": 3556, "s": 3512, "text": "SAP UI5 1.38 and many more like SAP UI5 1.6" }, { "code": null, "e": 3784, "s": 3556, "text": "SAP UI5 uses 3-digit version number. For example, SAPUI5 1.36.5. Here, the digit (1) specifies the major version. The second digit (36) specifies the minor version number. The third digit specifies the patch version number (5)." }, { "code": null, "e": 3895, "s": 3784, "text": "In each SAP UI5, the major and minor version as well as the patch version can be used to identify the patches." }, { "code": null, "e": 4033, "s": 3895, "text": "SAP UI5 and Open UI5, both provide the UI development environment. However, they are different from each other in the following aspects −" }, { "code": null, "e": 4153, "s": 4033, "text": "SAP UI5 is part of SAP product suite and is not a separate license. It is integrated with different SAP products like −" }, { "code": null, "e": 4174, "s": 4153, "text": "SAP NW 7.4 or higher" }, { "code": null, "e": 4196, "s": 4174, "text": "SAP NetWeaver AS 7.3x" }, { "code": null, "e": 4235, "s": 4196, "text": "SAP HANA Cloud and on premise solution" }, { "code": null, "e": 4338, "s": 4235, "text": "Open UI5 is an open source technology for application development and it was released with Apache 2.0." }, { "code": null, "e": 4347, "s": 4338, "text": "SAP HANA" }, { "code": null, "e": 4371, "s": 4347, "text": "SAP HANA Cloud Platform" }, { "code": null, "e": 4401, "s": 4371, "text": "SAP NetWeaver higher releases" }, { "code": null, "e": 4449, "s": 4401, "text": "Open UI5 was introduced with Apache 2.0 license" }, { "code": null, "e": 4500, "s": 4449, "text": "OpenUI5 is Open Source, and is available on GitHub" }, { "code": null, "e": 4672, "s": 4500, "text": "SAP UI5 supports all the main browsers from Microsoft, Google and Firefox with latest releases. However, features supported varies with the browser version and the vendor." }, { "code": null, "e": 4721, "s": 4672, "text": "In SAP UI5 architecture, you have three layers −" }, { "code": null, "e": 4840, "s": 4721, "text": "At the top, is the presentation layer, where UI5 components are consumed by devices like mobile, tablets, and laptops." }, { "code": null, "e": 4959, "s": 4840, "text": "At the top, is the presentation layer, where UI5 components are consumed by devices like mobile, tablets, and laptops." }, { "code": null, "e": 5260, "s": 4959, "text": "At the middle layer, is the application clients that includes SAP UI5 libraries for theming and control. UI5 control libraries include\n\nSap.viz\nSap.ui.commons (Controls like text fields and buttons)\nSap.ui.table (Input controls for table)\nSap.ui.ux3\nSap.m (Includes input control for mobile devices)\n" }, { "code": null, "e": 5395, "s": 5260, "text": "At the middle layer, is the application clients that includes SAP UI5 libraries for theming and control. UI5 control libraries include" }, { "code": null, "e": 5403, "s": 5395, "text": "Sap.viz" }, { "code": null, "e": 5411, "s": 5403, "text": "Sap.viz" }, { "code": null, "e": 5466, "s": 5411, "text": "Sap.ui.commons (Controls like text fields and buttons)" }, { "code": null, "e": 5521, "s": 5466, "text": "Sap.ui.commons (Controls like text fields and buttons)" }, { "code": null, "e": 5561, "s": 5521, "text": "Sap.ui.table (Input controls for table)" }, { "code": null, "e": 5601, "s": 5561, "text": "Sap.ui.table (Input controls for table)" }, { "code": null, "e": 5612, "s": 5601, "text": "Sap.ui.ux3" }, { "code": null, "e": 5623, "s": 5612, "text": "Sap.ui.ux3" }, { "code": null, "e": 5673, "s": 5623, "text": "Sap.m (Includes input control for mobile devices)" }, { "code": null, "e": 5723, "s": 5673, "text": "Sap.m (Includes input control for mobile devices)" }, { "code": null, "e": 5889, "s": 5723, "text": "At the bottom, is the option server component. This includes SAP NetWeaver Application Server for ABAP/Java, SAP backend, HANA XS engine for development or database." }, { "code": null, "e": 6055, "s": 5889, "text": "At the bottom, is the option server component. This includes SAP NetWeaver Application Server for ABAP/Java, SAP backend, HANA XS engine for development or database." }, { "code": null, "e": 6243, "s": 6055, "text": "SAP UI5 has multiple components which are independent and reusable objects in UI5 application. These components can be developed by different people and can be used in different projects." }, { "code": null, "e": 6440, "s": 6243, "text": "An application can use the components from different locations and hence you can easily get the structure of an application. You can create different types of components under SAP UI5 development." }, { "code": null, "e": 6550, "s": 6440, "text": "Faceless components are used to get the data from the backend system and they don’t contain a user interface." }, { "code": null, "e": 6606, "s": 6550, "text": "Example− They are a part of class sap.ui.core.component" }, { "code": null, "e": 6722, "s": 6606, "text": "UI components are used to add rendering functionality and represent a screen area or element on the user interface." }, { "code": null, "e": 6844, "s": 6722, "text": "Example − UI component can be a button with settings to perform some task. It is a part of class: sap.ui.core.UIComponent" }, { "code": null, "e": 7052, "s": 6844, "text": "Note − sap.ui.core.component is the base class for faceless and UI components. To define the extensibility function, the components can inherit from the base class or from other components in UI development." }, { "code": null, "e": 7228, "s": 7052, "text": "The module name of a component is known as the package name, and .component where the package name is defined as the name of the parameter passed to the component constructor." }, { "code": null, "e": 7297, "s": 7228, "text": "SAP UI5 components can also be divided as per the system landscape −" }, { "code": null, "e": 7432, "s": 7297, "text": "Client side component: This includes,\n\nControl libraries sap.m, sap.ui.common, etc.\nCore Javascript\nTest includes HTML and Javascript\n" }, { "code": null, "e": 7477, "s": 7432, "text": "Control libraries sap.m, sap.ui.common, etc." }, { "code": null, "e": 7493, "s": 7477, "text": "Core Javascript" }, { "code": null, "e": 7527, "s": 7493, "text": "Test includes HTML and Javascript" }, { "code": null, "e": 7639, "s": 7527, "text": "Server side component\n\nTheming Generator\nControl and application development tools in Eclipse\nResource handler\n" }, { "code": null, "e": 7657, "s": 7639, "text": "Theming Generator" }, { "code": null, "e": 7710, "s": 7657, "text": "Control and application development tools in Eclipse" }, { "code": null, "e": 7727, "s": 7710, "text": "Resource handler" }, { "code": null, "e": 7873, "s": 7727, "text": "Each component is represented in the form of a folder and contains the name of the components and the resources required to manage the component." }, { "code": null, "e": 7925, "s": 7873, "text": "Each component should contain the following files −" }, { "code": null, "e": 8024, "s": 7925, "text": "Component.json file that contains metadata for design time and is used only for design time tools." }, { "code": null, "e": 8123, "s": 8024, "text": "Component.json file that contains metadata for design time and is used only for design time tools." }, { "code": null, "e": 8240, "s": 8123, "text": "Component.js is used to define properties, events, and components methods that are responsible for runtime metadata." }, { "code": null, "e": 8357, "s": 8240, "text": "Component.js is used to define properties, events, and components methods that are responsible for runtime metadata." }, { "code": null, "e": 8443, "s": 8357, "text": "To create a new component, you have to create new folder. Let us name this as button." }, { "code": null, "e": 8483, "s": 8443, "text": "Next is to create the component.js file" }, { "code": null, "e": 8617, "s": 8483, "text": "Then, you have to extend UI component base class sap.ui.core.UIComponent.extend and enter the name of the component and package path." }, { "code": null, "e": 8709, "s": 8617, "text": "Later, to define a new component, you have to start with the require statement as follows −" }, { "code": null, "e": 9456, "s": 8709, "text": "// defining a new UI Component\njQuery.sap.require(\"sap.ui.core.UIComponent\");\njQuery.sap.require(\"sap.ui.commons.Button\");\njQuery.sap.declare(\"samples.components.button.Component\");\n\n// new Component\nsap.ui.core.UIComponent.extend(\"samples.components.button.Component\", {\n metadata : {\n properties : {\n text: \"string\"\n }\n }\n});\n\nsamples.components.button.Component.prototype.createContent = function(){\n this.oButton = new sap.ui.commons.Button(\"btn\");\n return this.oButton;\n};\n\n/*\n* Overrides setText method of the component to set this text in the button\n*/\nsamples.components.button.Component.prototype.setText = function(sText) {\n this.oButton.setText(sText);\n this.setProperty(\"text\", sText);\n return this;\n};" }, { "code": null, "e": 9530, "s": 9456, "text": "The next step is to define the component.json in your folder as follows −" }, { "code": null, "e": 9723, "s": 9530, "text": "{\n \"name\": \"samples.components.button\",\n \"version\": \"0.1.0\",\n \"description\": \"Sample button component\",\n \"keywords\": [\n \"button\",\n \"example\"\n ],\n \"dependencies\": {\n }\n}" }, { "code": null, "e": 9947, "s": 9723, "text": "To use a component, you have to wrap the component in a component container. You cannot directly use a UI component in a page using placeAt method. Another way is to pass the component to the componentContainer constructor." }, { "code": null, "e": 10058, "s": 9947, "text": "It includes adding the component to the container and using placeAt method to place the component on the page." }, { "code": null, "e": 10345, "s": 10058, "text": "var oComp = sap.ui.getCore().createComponent({\n name: \"samples.components.shell\",\n id: \"Comp1\",\n settings: {appTitle: \"Hello John\"}\n});\n\nvar oCompCont = new sap.ui.core.ComponentContainer(\"CompCont1\", {\n component: oComp\n});\n\noCompCont.placeAt(\"target1\");\n//using placeAt method" }, { "code": null, "e": 10553, "s": 10345, "text": "A component container carries specific settings and also contains the lifecycle methods of a regular control. The following code segment shows how to pass the component to the componentContainer constructor." }, { "code": null, "e": 10730, "s": 10553, "text": "var oCompCont2 = new sap.ui.core.ComponentContainer(\"CompCont2\", {\n name: \" samples.components.shell\",\n settings: {text: \"Hello John 1\"}\n});\noCompCont2.placeAt(\"target2\");\n" }, { "code": null, "e": 10934, "s": 10730, "text": "There are various JavaScript and CSS libraries that you can use in combination for the application development. SAPUI5 can use these libraries in combination and they are called SAPUI5 control libraries." }, { "code": null, "e": 10968, "s": 10934, "text": "Common SAPUI5 control libraries −" }, { "code": null, "e": 11017, "s": 10968, "text": "Sap.ui.commons for control fields, buttons, etc." }, { "code": null, "e": 11089, "s": 11017, "text": "Sap.m is the most common control library and is used for mobile devices" }, { "code": null, "e": 11125, "s": 11089, "text": "Sap.ui.table includes table control" }, { "code": null, "e": 11136, "s": 11125, "text": "Sap.ui.ux3" }, { "code": null, "e": 11302, "s": 11136, "text": "Note − SAPUI5 control library sap.m is the most common library and is used for application development. These libraries can be combined with other control libraries." }, { "code": null, "e": 11440, "s": 11302, "text": "You can use the control library sap.m with other control libraries - sap.ui.unified, sap.viz, sap.ui.table, sap.ui.layout, and sap.suite." }, { "code": null, "e": 11578, "s": 11440, "text": "You can use the control library sap.m with other control libraries - sap.ui.unified, sap.viz, sap.ui.table, sap.ui.layout, and sap.suite." }, { "code": null, "e": 11689, "s": 11578, "text": "You can combine control libraries - sap.ui.commons, sap.ui.table, sap.ui.ux3 and sap.ui.suite with each other." }, { "code": null, "e": 11800, "s": 11689, "text": "You can combine control libraries - sap.ui.commons, sap.ui.table, sap.ui.ux3 and sap.ui.suite with each other." }, { "code": null, "e": 11955, "s": 11800, "text": "You can also combine control library sap.ui.commons and sap.ui.ux3 with other libraries like sap.ui.core, sap.ui.unified, sap.ui.layout, and sap.ui.table." }, { "code": null, "e": 12110, "s": 11955, "text": "You can also combine control library sap.ui.commons and sap.ui.ux3 with other libraries like sap.ui.core, sap.ui.unified, sap.ui.layout, and sap.ui.table." }, { "code": null, "e": 12160, "s": 12110, "text": "You can combine sap.viz with all other libraries." }, { "code": null, "e": 12210, "s": 12160, "text": "You can combine sap.viz with all other libraries." }, { "code": null, "e": 12294, "s": 12210, "text": "The following table shows the main SAPUI5 control libraries and their description −" }, { "code": null, "e": 12609, "s": 12294, "text": "SAP UI5 development kit for HTML5 provides you an environment for the development of web-based applications and it provides an application with one consistent user experience. Web apps that you develop with SAP UI5 are responsive across browsers and devices, and they can run on smartphones, tablets, and desktops." }, { "code": null, "e": 12692, "s": 12609, "text": "The UI controls automatically adapt themselves to the capabilities of each device." }, { "code": null, "e": 12741, "s": 12692, "text": "You can use SAP UI5 on the following platforms −" }, { "code": null, "e": 12750, "s": 12741, "text": "SAP HANA" }, { "code": null, "e": 12774, "s": 12750, "text": "SAP HANA Cloud Platform" }, { "code": null, "e": 12820, "s": 12774, "text": "SAP NetWeaver for SAP NetWeaver 7.4 or higher" }, { "code": null, "e": 12902, "s": 12820, "text": "User interface add-on for SAP NetWeaver for SAP NetWeaver Application Server 7.3x" }, { "code": null, "e": 13246, "s": 12902, "text": "You can deploy the application on the server that includes storing the libraries and getting data from the database. You can use the NetWeaver Application server or HANA Cloud platform for application deployment, and data can be accessed by a business application using the OData model using Gateway. Take a look at the following illustration." }, { "code": null, "e": 13450, "s": 13246, "text": "When a user sends a client request from his mobile/laptop, a request is sent to the server to load the application in a browser, and data is accessed via database and the relevant libraries are accessed." }, { "code": null, "e": 13708, "s": 13450, "text": "To build a UI5 application, you can download the SAP UI5 developer’s tools of Eclipse. Once you download, you can unzip the file and deploy on the web server. For ABAP, you can install a UI Add-On for SAP NetWeaver and this also includes UI5 Theme Designer." }, { "code": null, "e": 13811, "s": 13708, "text": "To install and update UI5 development toolkit for HTML5, you should meet the following prerequisites −" }, { "code": null, "e": 13883, "s": 13811, "text": "Only relevant when installing the SAP UI5 ABAP Repository Team Provider" }, { "code": null, "e": 13929, "s": 13883, "text": "For Windows OS: SAP GUI for Windows 7.30/7.40" }, { "code": null, "e": 14001, "s": 13929, "text": "Only relevant when installing the SAP UI5 ABAP Repository Team Provider" }, { "code": null, "e": 14084, "s": 14001, "text": "For Windows OS: DLLs VS2010 for communication with the back-end system is required" }, { "code": null, "e": 14187, "s": 14084, "text": "Note: Install either the x86 or the x64 variant, accordingly to your 32 or 64-Bit Eclipse installation" }, { "code": null, "e": 14282, "s": 14187, "text": "Let us now proceed and discuss how you can install the SAP UI5 Development Kit in your system." }, { "code": null, "e": 14365, "s": 14282, "text": "Step 1 − To install JDK, go to Oracle.com and search for the required JDK version." }, { "code": null, "e": 14463, "s": 14365, "text": "Step 2 − Download and run the setup. You will get a message as shown in the following screenshot." }, { "code": null, "e": 14524, "s": 14463, "text": "Step 3 − To install Eclipse, go to www.Eclipse.org/downloads" }, { "code": null, "e": 14588, "s": 14524, "text": "Step 4 − Extract the file as shown in the following screenshot." }, { "code": null, "e": 14716, "s": 14588, "text": "Step 5 − To run the installation, go to the extracted folder and run the application file as shown in the following screenshot." }, { "code": null, "e": 14795, "s": 14716, "text": "Step 6 − To install SAPUI5 tools, go to Eclipse → Help → Install New software." }, { "code": null, "e": 14875, "s": 14795, "text": "You can install directly using the URL or by entering the path of UI5 demo kit." }, { "code": null, "e": 14960, "s": 14875, "text": "Step 7 − Next, enter the URL in install dialog https://tools.hana.ondemand.com/mars" }, { "code": null, "e": 15135, "s": 14960, "text": "Step 8 − To see the available features. Press the ENTER key. You can select the features and click on Next. It will display the list of features to be installed → Click Next." }, { "code": null, "e": 15217, "s": 15135, "text": "Step 9 − Accept the license agreement and click Finish to start the installation." }, { "code": null, "e": 15292, "s": 15217, "text": "Step 10 − Download UI Development Kit for HTML 5 from the following link −" }, { "code": null, "e": 15392, "s": 15292, "text": "http://scn.sap.com/community/developer-center/front-end and extract the content in the same folder." }, { "code": null, "e": 15468, "s": 15392, "text": "Step 11 − Start the Eclipse environment. Go to Help → Install New Software." }, { "code": null, "e": 15497, "s": 15468, "text": "Step 12 − Click Add → Local." }, { "code": null, "e": 15683, "s": 15497, "text": "Step 13 − Next, navigate to the local update site location and select the tool-update site folder with the folder where you extracted the HTML5 Development toolkit as the update source." }, { "code": null, "e": 15743, "s": 15683, "text": "Step 14 − Select all plugins and features for installation." }, { "code": null, "e": 15856, "s": 15743, "text": "Step 15 − Select the dialog to “Contact all update sites” during the installation to find the required software." }, { "code": null, "e": 15930, "s": 15856, "text": "Step 16 − Click the Finish button to complete the setup. Restart Eclipse." }, { "code": null, "e": 16150, "s": 15930, "text": "Step 17 − You can verify the installation by creating a new SAPUI5 Application Project via Eclipse menu File → New → Other at the bottom. Select SAP UI5 Application Development folder and expand to create a new project." }, { "code": null, "e": 16252, "s": 16150, "text": "Step 18 − Enter the project name, select library and you can check the box to create an initial view." }, { "code": null, "e": 16369, "s": 16252, "text": "Step 19 − Create a view using some sample code in the project. Enter the name of the view and click the Next button." }, { "code": null, "e": 16532, "s": 16369, "text": "Step 20 − Select the development paradigm and click on Finish. You will see a new SAPUI5 development project in a new window as shown in the following screenshot." }, { "code": null, "e": 16791, "s": 16532, "text": "Now, to present your application or run it in production, you can deploy your SAPUI5 application on the tomcat server. If you don’t have a tool like MAVEN, in that you can use the export option to export the project manually. Right-click on Project → Export." }, { "code": null, "e": 16866, "s": 16791, "text": "Step 21 − Enter the destination path where you want to place the war file." }, { "code": null, "e": 17024, "s": 16866, "text": "Next, copy the war-File to webapps directory of your apache tomcat. You can access your application by going to this path - http://localhost:8080/<your_app>/" }, { "code": null, "e": 17294, "s": 17024, "text": "Note − In a normal scenario, many SAP projects run in Internet Explorer but for SAPUI5 development it is recommended to use Google Chrome or Firefox with firebug plugin as both systems allow the use of tools and plugins to debug JavaScript, as well as use HTML and CSS." }, { "code": null, "e": 17527, "s": 17294, "text": "Model-View-Controller (MVC) concept is used in SAP UI5 development to keep the application data separate from the user interactions. This allows you to develop the web applications and make changes to the applications independently." }, { "code": null, "e": 17592, "s": 17527, "text": "Model-View-Controller plays a different role in UI development −" }, { "code": null, "e": 17676, "s": 17592, "text": "The Model is responsible for managing the application data in the database/backend." }, { "code": null, "e": 17760, "s": 17676, "text": "The Model is responsible for managing the application data in the database/backend." }, { "code": null, "e": 17940, "s": 17760, "text": "The View is responsible for defining the user interface to users. When a user sends a requests from his device, the view is responsible for data view as per the request submitted." }, { "code": null, "e": 18120, "s": 17940, "text": "The View is responsible for defining the user interface to users. When a user sends a requests from his device, the view is responsible for data view as per the request submitted." }, { "code": null, "e": 18235, "s": 18120, "text": "The Controller is used to control the data and view events as per user interaction by updating the view and model." }, { "code": null, "e": 18350, "s": 18235, "text": "The Controller is used to control the data and view events as per user interaction by updating the view and model." }, { "code": null, "e": 18435, "s": 18350, "text": "You can define Model-View-Controller concept in SAPUI5 with the following features −" }, { "code": null, "e": 18501, "s": 18435, "text": "Model acts as a bridge between the view and the application data." }, { "code": null, "e": 18585, "s": 18501, "text": "Model is used to get the request from the view and respond as per the user’s input." }, { "code": null, "e": 18618, "s": 18585, "text": "Model doesn’t depend on classes." }, { "code": null, "e": 18682, "s": 18618, "text": "View is responsible to manage information display to the users." }, { "code": null, "e": 18708, "s": 18682, "text": "Views are based on Model." }, { "code": null, "e": 18834, "s": 18708, "text": "Controller is responsible for taking the input given by devices and communicates to model/view and to trigger correct action." }, { "code": null, "e": 18960, "s": 18834, "text": "Controller is responsible for taking the input given by devices and communicates to model/view and to trigger correct action." }, { "code": null, "e": 18992, "s": 18960, "text": "Controllers are based on model." }, { "code": null, "e": 19024, "s": 18992, "text": "Controllers are based on model." }, { "code": null, "e": 19091, "s": 19024, "text": "SAP UI5 offers Views and Controllers in the form of single files −" }, { "code": null, "e": 19115, "s": 19091, "text": "sap.ui.core.mvc.XMLView" }, { "code": null, "e": 19138, "s": 19115, "text": "sap.ui.core.mvc.JSView" }, { "code": null, "e": 19165, "s": 19138, "text": "sap.ui.core.mvc.Controller" }, { "code": null, "e": 19190, "s": 19165, "text": "sap.ui.core.mvc.JSONView" }, { "code": null, "e": 19257, "s": 19190, "text": "JSON model is a client-side model and is used for small data sets." }, { "code": null, "e": 19365, "s": 19257, "text": "JSON model supports two-way binding. Data binding concept is mentioned in the latter half of this tutorial." }, { "code": null, "e": 19432, "s": 19365, "text": "JSON model can be used to bind controls to JavaScript object data." }, { "code": null, "e": 19484, "s": 19432, "text": "XML model can be used to bind controls to XML data." }, { "code": null, "e": 19560, "s": 19484, "text": "XML is also a client side model and hence is used only for small data sets." }, { "code": null, "e": 19646, "s": 19560, "text": "XML model doesn’t provide any mechanism for server-based paging or loading of deltas." }, { "code": null, "e": 19692, "s": 19646, "text": "XML model also supports two-way data binding." }, { "code": null, "e": 19743, "s": 19692, "text": "Views are defined using SAP libraries as follows −" }, { "code": null, "e": 19813, "s": 19743, "text": "XML with HTML, mixed, or Standalone: Library- sap.ui.core.mvc.XMLView" }, { "code": null, "e": 19857, "s": 19813, "text": "JavaScript: Library- sap.ui.core.mvc.JSView" }, { "code": null, "e": 19898, "s": 19857, "text": "JSON: Library - sap.ui.core.mvc.JSONView" }, { "code": null, "e": 19939, "s": 19898, "text": "HTML: Library - sap.ui.core.mvc.HTMLView" }, { "code": null, "e": 20264, "s": 19939, "text": "Sap.ui.jsview(“sap.hcm.address”, {\n getControllerName: function() {\n return “sap.hcm.address”;\n },\n createContent: function(oController) {\n var oButton = new sap.ui.commons.Button({ text: “Hello” });\n oButton.attachPress(function() {\n oController.Hello();\n })\n Return oButton;\n }\n});" }, { "code": null, "e": 20519, "s": 20264, "text": "<template data-controller-name = ”sap.hcm.address’>\n <h1>title</h1>\n <div> Embedded html </div>\n <div class = ”test” data-sap-ui-type = ”sap.ui.commons.Button”\n Id = ”Button1” data-text = ”Hello” Data-press = ”sayHello”>\n </div>\n</template>" }, { "code": null, "e": 20594, "s": 20519, "text": "Similarly, you can create JSON view derived from sap.ui.core.mvc.JsonView." }, { "code": null, "e": 20765, "s": 20594, "text": "{\n “type”:”sap.ui.core.mvc.JsonView”,\n “controllerName”:”sap.hcm.address”,\n ............................\n ........................\n .........................\n}\n" }, { "code": null, "e": 20891, "s": 20765, "text": "The following table lists key features associated with MVC concept and comparison of different view types w.r.t the features." }, { "code": null, "e": 20997, "s": 20891, "text": "SAPUI5 Developer Studio provides tools to ease the UI5 development process. Following are the functions −" }, { "code": null, "e": 21028, "s": 20997, "text": "Wizard for Control development" }, { "code": null, "e": 21056, "s": 21028, "text": "Wizard for Project creation" }, { "code": null, "e": 21092, "s": 21056, "text": "Wizard for View/Controller creation" }, { "code": null, "e": 21227, "s": 21092, "text": "You can download it from SAP Marketplace using the link https://support.sap.com/software.html. Search for UI Add-on 1.0 for NetWeaver." }, { "code": null, "e": 21367, "s": 21227, "text": "Go to Software downloads and enter your Id and password. Then, go to support packages and patches. Search for sapui5 tools ide plugin 1.00." }, { "code": null, "e": 21504, "s": 21367, "text": "A trail of SAPUI5 framework is also available under SCN. You can go to this link http://scn.sap.com/community/developer-center/front-end" }, { "code": null, "e": 21590, "s": 21504, "text": "Step 1 − To create a new project in UI5 developer Studio, go to File → New → Project." }, { "code": null, "e": 21669, "s": 21590, "text": "Step 2 − Enter the name of project, target device, and Create an Initial View." }, { "code": null, "e": 21747, "s": 21669, "text": "Step 3 − Enter the View name and View type in the next window and click Next." }, { "code": null, "e": 21889, "s": 21747, "text": "Step 4 − In the last window, you see the project summary. It shows you the project properties. Click the Finish button to create the project." }, { "code": null, "e": 22036, "s": 21889, "text": "Step 5 − You will be prompted to switch to Java EE perspective. Click Yes and it will open a new UI5 project window with an initial view - JSView." }, { "code": null, "e": 22122, "s": 22036, "text": "Step 6 − Now to add a Shell to this view, you can use the library sap.ui.ux3.Shell()." }, { "code": null, "e": 22261, "s": 22122, "text": "Step 7 − As Shell is not part of sap.ui.commons, you need to add sap.ui.ux3 library. You can add additional libraries to data-sap-ui-libs." }, { "code": null, "e": 22307, "s": 22261, "text": "To run an application, you have two options −" }, { "code": null, "e": 22321, "s": 22307, "text": "Run on server" }, { "code": null, "e": 22335, "s": 22321, "text": "Run on webapp" }, { "code": null, "e": 22447, "s": 22335, "text": "Run on server is recommended as it has a fixed port and it is not like run on webapp with one-time random port." }, { "code": null, "e": 22541, "s": 22447, "text": "As shown in the following table, you can define various configuration attributes in SAP UI5 −" }, { "code": null, "e": 22588, "s": 22541, "text": "The core functions in SAP UI5 are as follows −" }, { "code": null, "e": 22644, "s": 22588, "text": "Sap.ui.getCore() − This is used to get a core instance." }, { "code": null, "e": 22700, "s": 22644, "text": "Sap.ui.getCore() − This is used to get a core instance." }, { "code": null, "e": 22792, "s": 22700, "text": "Sap.ui.getCore().byid(id) − This is used to get an instance of UI5 control created with id." }, { "code": null, "e": 22884, "s": 22792, "text": "Sap.ui.getCore().byid(id) − This is used to get an instance of UI5 control created with id." }, { "code": null, "e": 22997, "s": 22884, "text": "Sap.ui.getCore().applyChanges() − This is used to carry out and render the changes for UI5 controls immediately." }, { "code": null, "e": 23110, "s": 22997, "text": "Sap.ui.getCore().applyChanges() − This is used to carry out and render the changes for UI5 controls immediately." }, { "code": null, "e": 23278, "s": 23110, "text": "jQuery.sap.domById(id) − This is used to get any HTML element with id. If there is a UI5 control with id, the element returned is top most HTML element of UI5 control." }, { "code": null, "e": 23446, "s": 23278, "text": "jQuery.sap.domById(id) − This is used to get any HTML element with id. If there is a UI5 control with id, the element returned is top most HTML element of UI5 control." }, { "code": null, "e": 23539, "s": 23446, "text": "jQuery.sap.byId(id) − This is used to return jQuery object of DOM element with specified Id." }, { "code": null, "e": 23632, "s": 23539, "text": "jQuery.sap.byId(id) − This is used to return jQuery object of DOM element with specified Id." }, { "code": null, "e": 23848, "s": 23632, "text": "There are different types of UI controls that you can use while developing UI5 applications. These controls allow you to add a button, table, images, layout, combo box, and various other controls in UI5 application." }, { "code": null, "e": 23879, "s": 23848, "text": "Common control types include −" }, { "code": null, "e": 23895, "s": 23879, "text": "Simple Controls" }, { "code": null, "e": 23912, "s": 23895, "text": "Complex Controls" }, { "code": null, "e": 23925, "s": 23912, "text": "UX3 Controls" }, { "code": null, "e": 23933, "s": 23925, "text": "Dialogs" }, { "code": null, "e": 23940, "s": 23933, "text": "Layout" }, { "code": null, "e": 24040, "s": 23940, "text": "Var image = new sap.ui.commons.Image();\nImage.setSrc(“Image1.gif”);\nImage.setAlt(“alternat.text”);\n" }, { "code": null, "e": 24095, "s": 24040, "text": "You can use a combo box to provide predefined entries." }, { "code": null, "e": 24127, "s": 24095, "text": "Properties − items, selectedKey" }, { "code": null, "e": 24389, "s": 24127, "text": "Var oComboBox2 = new sap.ui.commons.ComboBox (“ComboBox”,{\n Items:{path:”/data”,\n Template:oItemTemplate, filters:[oFilter]},\n Change: function(oEvent){\n Sap.ui.getCore(). byId(“field”).setValue(\n oEvent.oSource.getSelectedKey());\n }\n});" }, { "code": null, "e": 24446, "s": 24389, "text": "Use attachPresss assign event handler for a push action." }, { "code": null, "e": 24538, "s": 24446, "text": "Var oButton = new sap.ui.commons.Button ({text : “Click”,\n Press: oController.update\n});\n" }, { "code": null, "e": 24573, "s": 24538, "text": "To autocomplete the entered value." }, { "code": null, "e": 24799, "s": 24573, "text": "Var uiElement = new sap.ui.commons.AutoComplete({\n Tooltip: ”Enter the product”,\n maxPopupItems: 4\n});\nFor (var i = 0; i<aData.lenght; i++){\n uiElement.addItem(new sap.ui.core.ListItem(\n {text: aData[i].name}));\n}\n" }, { "code": null, "e": 24864, "s": 24799, "text": "It is derived from sap.ui.table and each table contains columns." }, { "code": null, "e": 25124, "s": 24864, "text": "Var oTable = new sap.ui.table.Table({\n Columns: [\n New sap.ui.table.Column({\n Label: new sap.ui.commons.lable({ text: “First Column”}),\n Template: new sap.ui.commons.TextView({ text: “{Firstcolumn}” }),\n Width: “120px”\n })\n" }, { "code": null, "e": 25431, "s": 25124, "text": "In SAP UI5, data binding concept is used to update the data automatically by binding the data with the controls that holds the application data. Using data binding, you can bind simple controls like text field, simple button to application data, and data is automatically updated when there is a new value." }, { "code": null, "e": 25598, "s": 25431, "text": "Using two-way data binding, application data is updated when the value of bound control changes. The value can be changed via different methods, like user input, etc." }, { "code": null, "e": 25709, "s": 25598, "text": "In SAP UI5, different data models can be used for data binding. These data models support different features −" }, { "code": null, "e": 25912, "s": 25709, "text": "JSON model is used to bind JavaScript objects to controls. This data model is a client-side model and is suggested for small data sets. It doesn’t provide any mechanism for serverside paging or loading." }, { "code": null, "e": 25935, "s": 25912, "text": "Key features include −" }, { "code": null, "e": 26008, "s": 25935, "text": "JSON model for data binding supports data in JavaScript notation format." }, { "code": null, "e": 26042, "s": 26008, "text": "It supports two-way data binding." }, { "code": null, "e": 26070, "s": 26042, "text": "Creating a model instance −" }, { "code": null, "e": 26132, "s": 26070, "text": "Var oModel = new sap.ui.model.json.JSONModel(dataUrlorData);\n" }, { "code": null, "e": 26330, "s": 26132, "text": "XML model of data binding allows you to bind the controls to XML data. It is used for clientside objects and for small data sets. It doesn’t provide any mechanism for server-side paging or loading." }, { "code": null, "e": 26353, "s": 26330, "text": "Key features include −" }, { "code": null, "e": 26398, "s": 26353, "text": "XML model of data binding supports XML data." }, { "code": null, "e": 26437, "s": 26398, "text": "It also supports two-way data binding." }, { "code": null, "e": 26465, "s": 26437, "text": "Creating a model instance −" }, { "code": null, "e": 26525, "s": 26465, "text": "Var oModel = new sap.ui.model.xml.XMLModel(dataUrlorData);\n" }, { "code": null, "e": 26786, "s": 26525, "text": "OData model is a server-side model, so entire data is available at the server side. Client side can see only rows and fields and you can’t use sorting and filtering at the client side. There is a need to send this request to the server to complete these tasks." }, { "code": null, "e": 26894, "s": 26786, "text": "Data binding in OData model is one way but you can enable two-way binding using experimental write support." }, { "code": null, "e": 26917, "s": 26894, "text": "Key features include −" }, { "code": null, "e": 26976, "s": 26917, "text": "OData model of data binding supports Odata compliant data." }, { "code": null, "e": 27050, "s": 26976, "text": "This data model allows you to create OData requests and handle responses." }, { "code": null, "e": 27092, "s": 27050, "text": "It supports experimental two-way binding." }, { "code": null, "e": 27120, "s": 27092, "text": "Creating a model instance −" }, { "code": null, "e": 27202, "s": 27120, "text": "Var oModel = new sap.ui.model.odata.ODataModel (dataUrl [,useJSON, user, pass]);\n" }, { "code": null, "e": 27284, "s": 27202, "text": "You can use the setModel method to assign the model to specific controls or core." }, { "code": null, "e": 27320, "s": 27284, "text": "Sap.ui.getcore().setModel(oModel);\n" }, { "code": null, "e": 27346, "s": 27320, "text": "To bind a model to view −" }, { "code": null, "e": 27456, "s": 27346, "text": "Var myView = sap.ui.view({type:sap.ui.core.mvc.ViewType.JS, viewname:”view name”});\nmyView.setModel(oModel);\n" }, { "code": null, "e": 27487, "s": 27456, "text": "To bind a model to a control −" }, { "code": null, "e": 27558, "s": 27487, "text": "Var oTable = sap.ui.getCore().byId(“table”);\noTable.setModel(oModel);\n" }, { "code": null, "e": 27700, "s": 27558, "text": "You can bind the properties of a control to model properties. You can bind the properties of a model to a control using bindproperty method −" }, { "code": null, "e": 27871, "s": 27700, "text": "oControl.bindProperty(“controlProperty”, “modelProperty”);\nor by using below methodvar\noControl = new sap.ui.commons.TextView({\n controlProperty: “{modelProperty}”\n});\n" }, { "code": null, "e": 28044, "s": 27871, "text": "You can use aggregation binding to bind a collection of values like binding multiple rows to a table. To use aggregation, you have to use a control that acts as a template." }, { "code": null, "e": 28108, "s": 28044, "text": "You can define aggregation binding using bindAgregation method." }, { "code": null, "e": 28182, "s": 28108, "text": "oComboBox.bindaggregation( “items”, “/modelaggregation”, oItemTemplate);\n" }, { "code": null, "e": 28392, "s": 28182, "text": "Design Pattern is a new term in SAP UI5 development when we talk about SAP development or SAP Fiori system. SAP is working hard to find new design patterns that support development in SAP system using UI5 SDK." }, { "code": null, "e": 28446, "s": 28392, "text": "SAP has released different types of design patterns −" }, { "code": null, "e": 28633, "s": 28446, "text": "This is a first step in application binding and is supported by SplitApp control of SAP UI5. This design pattern supports the list of content and allows lead selection and detailed view." }, { "code": null, "e": 28711, "s": 28633, "text": "This design pattern displays the detail of transaction in the detail section." }, { "code": null, "e": 28889, "s": 28711, "text": "Example − You are placing an order online and you want to see a confirmation page that displays what you are buying and display the detail of the transaction with detailed view." }, { "code": null, "e": 28999, "s": 28889, "text": "This design pattern is mostly recommended for displaying charts, pictorial data, and various types of graphs." }, { "code": null, "e": 29167, "s": 28999, "text": "This design pattern is recommended when you are using a complex application flow and there is a need to make use of all design patterns to build a working application." }, { "code": null, "e": 29465, "s": 29167, "text": "In SAPUI5 development for larger JavaScript applications, UI5 framework provides built in support for modularization. Modularization concept allows you to split application into smaller parts and they can be combined together at run time. These smaller application parts are called modularization." }, { "code": null, "e": 29634, "s": 29465, "text": "You can declare your own JavaScript module by calling the query jQuery.sap.declare function and this is used to keep track of the module name and already loaded module." }, { "code": null, "e": 29687, "s": 29634, "text": "To load a module, you have to use jQuery.sap.require" }, { "code": null, "e": 29789, "s": 29687, "text": "<script>\n jQuery.sap.require(“sap.ui.commons.MessageBox”);\n ...........................\n</script>" }, { "code": null, "e": 29985, "s": 29789, "text": "When a module is required jQuery.sap.require and that module is not loaded, it automatically loads. It calls the declare method so when require is called it knows that the module has been loaded." }, { "code": null, "e": 30047, "s": 29985, "text": "SAP UI5 supports localization concept based on Java platform." }, { "code": null, "e": 30167, "s": 30047, "text": "Identifying the Language Code − For the identification of languages, the framework uses a language code of type string." }, { "code": null, "e": 30425, "s": 30167, "text": "Resource Bundles − A resource bundle file is a Java properties file and contains key/value pairs where the values are language-dependent texts and the keys are language independent and used by the application to identify and access the corresponding values." }, { "code": null, "e": 30677, "s": 30425, "text": "Resource bundles are a collection of *.properties files. All files are named with the same base name (prefix identifying the resource bundle), an optional suffix that identifies the language contained in each file, and the fixed .properties extension." }, { "code": null, "e": 30942, "s": 30677, "text": "The language suffixes are formed according to the older JDK locale syntax. By convention, a file without a language suffix should exist and contain the raw untranslated texts in the developer's language. This file is used if no more suitable language can be found." }, { "code": null, "e": 31019, "s": 30942, "text": "Resource bundle sap.ui.commons.message_bundle contains the following files −" }, { "code": null, "e": 31147, "s": 31019, "text": "sap.ui.commons.message_bundle.properties − This file carries the raw text from the developer and it determines the set of keys." }, { "code": null, "e": 31275, "s": 31147, "text": "sap.ui.commons.message_bundle.properties − This file carries the raw text from the developer and it determines the set of keys." }, { "code": null, "e": 31353, "s": 31275, "text": "sap.ui.commons.message_bundle_en.properties − This file carries English text." }, { "code": null, "e": 31431, "s": 31353, "text": "sap.ui.commons.message_bundle_en.properties − This file carries English text." }, { "code": null, "e": 31524, "s": 31431, "text": "sap.ui.commons.message_bundle_en_US.properties − This file carries text in American English." }, { "code": null, "e": 31617, "s": 31524, "text": "sap.ui.commons.message_bundle_en_US.properties − This file carries text in American English." }, { "code": null, "e": 31709, "s": 31617, "text": "sap.ui.commons.message_bundle_en_UK.properties − This file carries text in British English." }, { "code": null, "e": 31801, "s": 31709, "text": "sap.ui.commons.message_bundle_en_UK.properties − This file carries text in British English." }, { "code": null, "e": 31920, "s": 31801, "text": "SAPUI5 provides two options to use localized texts in applications – the jQuery.sap.resources module and data binding." }, { "code": null, "e": 31993, "s": 31920, "text": "The following code is used to get resource bundle for a given language −" }, { "code": null, "e": 32104, "s": 31993, "text": "jQuery.sap.require(“jquery.sap.resources”);\nvar oBundle = jQuery.sap.resources({url ; sUrl, locale:sLocale});\n" }, { "code": null, "e": 32171, "s": 32104, "text": "The following code is used to access the text in resource bundle −" }, { "code": null, "e": 32207, "s": 32171, "text": "Var sText = oBundle.getText(sKey);\n" }, { "code": null, "e": 32261, "s": 32207, "text": "The following code is used to get URL of a resource −" }, { "code": null, "e": 32333, "s": 32261, "text": "Var sUrl = sap.ui.resource(“sap.ui.table”,”messagebundle.properties”);\n" }, { "code": null, "e": 32590, "s": 32333, "text": "A Control is used to define the appearance and screen area. It contains properties likewidth and text. These properties are used to modify the appearance or change the data displayed by the control. You can create aggregate controls or associated controls." }, { "code": null, "e": 32772, "s": 32590, "text": "Associated control of a control is defined as loosely related controls, which are not child controls or a part of the main control. Controls are used to trigger well-defined events." }, { "code": null, "e": 32936, "s": 32772, "text": "Controls in SAPUI5 can be created directly using a tool or JavaScript file. Controls that are created using the extend() method are also known as Notepad controls." }, { "code": null, "e": 33009, "s": 32936, "text": "The following code is used to define a Control using the Extend method −" }, { "code": null, "e": 33059, "s": 33009, "text": "Sap.ui.core.control.extend (sname, oDefinition);\n" }, { "code": null, "e": 33108, "s": 33059, "text": "The parameters that are passed to this control −" }, { "code": null, "e": 33128, "s": 33108, "text": "Name of the control" }, { "code": null, "e": 33154, "s": 33128, "text": "Definition of the control" }, { "code": null, "e": 33277, "s": 33154, "text": "The definition of a control contains information about control API, aggregations, events, etc. and implementation methods." }, { "code": null, "e": 33420, "s": 33277, "text": "You can also create custom controls. Definition of custom control can contain public and private methods, metadata, and rendering method, etc." }, { "code": null, "e": 33630, "s": 33420, "text": "metadata:{\n properties: {},\n events: {},\n aggregations: {}\n},\n\npublicMethod: function() {},\n_privateMethod: function() {},\ninit: function() {}\nonclick: function(e) {},\nrenderer: function(rm, oControl) {}" }, { "code": null, "e": 33676, "s": 33630, "text": "Creating a new control inherits from Button −" }, { "code": null, "e": 33728, "s": 33676, "text": "Sap.ui.commons.Button.extend (sname, oDefinition);\n" }, { "code": null, "e": 33833, "s": 33728, "text": "The metadata in control definition consists of objects for control properties, events, and aggregations." }, { "code": null, "e": 33869, "s": 33833, "text": "Type: data type of control property" }, { "code": null, "e": 33906, "s": 33869, "text": "String: string for a string property" }, { "code": null, "e": 33941, "s": 33906, "text": "Int or float for number properties" }, { "code": null, "e": 33969, "s": 33941, "text": "Int[] for an integers array" }, { "code": null, "e": 33998, "s": 33969, "text": "String[] for an string array" }, { "code": null, "e": 34154, "s": 33998, "text": "Events are defined by the name event only. You normally pass an empty object to an event. Application use enablePreventDefault flag to interrupt the event." }, { "code": null, "e": 34232, "s": 34154, "text": "Events: {\n Logout:{},\n Close: {\n enablePreventDefault : true\n }\n}\n" }, { "code": null, "e": 34388, "s": 34232, "text": "You can extend UI5 applications that are either remote or in Web IDE. To create a new Extension project, you should have an application remotely or on IDE." }, { "code": null, "e": 34454, "s": 34388, "text": "Step 1 − To create a new Project, go to File → Extension Project." }, { "code": null, "e": 34579, "s": 34454, "text": "Step 2 − Select the Workspace to select the desired SAP Fiori application that you want to use as your original application." }, { "code": null, "e": 34763, "s": 34579, "text": "Step 3 − When you select an application, Extension Project Name field is populated with the name of the original application with the suffix extension. You can change this name → Next" }, { "code": null, "e": 34928, "s": 34763, "text": "Step 4 − If necessary, select the Open extension project in extensibility pane checkbox to automatically open the extensibility pane after the project is generated." }, { "code": null, "e": 34951, "s": 34928, "text": "Step 5 − Click Finish." }, { "code": null, "e": 35065, "s": 34951, "text": "Similarly, you can also extend applications that reside in SAP HANA Cloud platform. Follow the steps given below." }, { "code": null, "e": 35131, "s": 35065, "text": "Step 1 − To create a new Project, go to File → Extension Project." }, { "code": null, "e": 35254, "s": 35131, "text": "Step 2 − Select the start → Remote → SAP HANA Cloud Platform → Select Application from SAP HANA Cloud Platform dialog box." }, { "code": null, "e": 35359, "s": 35254, "text": "Step 3 − In the next window, you have to enter SAP HANA Cloud Platform account, user name, and password." }, { "code": null, "e": 35448, "s": 35359, "text": "Step 4 − Select Get Applications and search for the application that you want to extend." }, { "code": null, "e": 35607, "s": 35448, "text": "Step 5 − Select the desired application → OK. The Extension Project Name field is automatically populated in the wizard. If necessary, you can edit this name." }, { "code": null, "e": 35688, "s": 35607, "text": "Step 6 − Click Next. Choose Finish to confirm and create your extension project." }, { "code": null, "e": 35830, "s": 35688, "text": "The UI theme designer is a browser-based tool that allows you to develop your themes by modifying one of the theme templates provided by SAP." }, { "code": null, "e": 35972, "s": 35830, "text": "Example − You can change the color scheme, or add your company's logo. The tool provides a live preview of the theme while you are designing." }, { "code": null, "e": 36426, "s": 35972, "text": "Apply your corporate branding and look to applications built with SAP UI technologies. The UI theme designer is a browser-based tool for cross-theming scenarios. Use it to easily build your corporate identity themes by modifying one of the theme templates provided by SAP. For example, you can change the color scheme, or add your company's logo. The tool is targeted at different user groups, including developers, visual designers, and administrators." }, { "code": null, "e": 36472, "s": 36426, "text": "SAP NetWeaver as ABAP (via UI Add-On 1.0 SP4)" }, { "code": null, "e": 36524, "s": 36472, "text": "SAP NetWeaver Portal (7.30 SP10 and higher version)" }, { "code": null, "e": 36549, "s": 36524, "text": "SAP HANA Cloud (Planned)" }, { "code": null, "e": 36585, "s": 36549, "text": "SAP NetWeaver Portal (7.02 Planned)" }, { "code": null, "e": 36752, "s": 36585, "text": "Browser-based, graphical WYSIWYG editor − Changes the values of theming parameters and immediately sees how it affects the visualization of the selected preview page." }, { "code": null, "e": 36919, "s": 36752, "text": "Browser-based, graphical WYSIWYG editor − Changes the values of theming parameters and immediately sees how it affects the visualization of the selected preview page." }, { "code": null, "e": 37155, "s": 36919, "text": "Built-in preview pages − Select built-in preview pages to see what your custom theme will look like when it is applied to an application − \n\nApplication previews (Example: Purchase Order Approval, SAP Fiori Launchpad)\nControl previews\n" }, { "code": null, "e": 37295, "s": 37155, "text": "Built-in preview pages − Select built-in preview pages to see what your custom theme will look like when it is applied to an application − " }, { "code": null, "e": 37372, "s": 37295, "text": "Application previews (Example: Purchase Order Approval, SAP Fiori Launchpad)" }, { "code": null, "e": 37449, "s": 37372, "text": "Application previews (Example: Purchase Order Approval, SAP Fiori Launchpad)" }, { "code": null, "e": 37466, "s": 37449, "text": "Control previews" }, { "code": null, "e": 37483, "s": 37466, "text": "Control previews" }, { "code": null, "e": 37650, "s": 37483, "text": "Different levels of theming − \n\nQuick theming (basic cross-technology theme settings)\nExpert theming (technology-specific theme settings)\nManual LESS or CSS editing\n\n" }, { "code": null, "e": 37681, "s": 37650, "text": "Different levels of theming − " }, { "code": null, "e": 37735, "s": 37681, "text": "Quick theming (basic cross-technology theme settings)" }, { "code": null, "e": 37789, "s": 37735, "text": "Quick theming (basic cross-technology theme settings)" }, { "code": null, "e": 37841, "s": 37789, "text": "Expert theming (technology-specific theme settings)" }, { "code": null, "e": 37893, "s": 37841, "text": "Expert theming (technology-specific theme settings)" }, { "code": null, "e": 37920, "s": 37893, "text": "Manual LESS or CSS editing" }, { "code": null, "e": 37947, "s": 37920, "text": "Manual LESS or CSS editing" }, { "code": null, "e": 38064, "s": 37947, "text": "Color palette for reuse − Specifies a set of parameters with the main color values defining your corporate branding." }, { "code": null, "e": 38181, "s": 38064, "text": "Color palette for reuse − Specifies a set of parameters with the main color values defining your corporate branding." }, { "code": null, "e": 38490, "s": 38181, "text": "Cross-technology theming − Create one consistent theme that applies to various SAP UI clients and technologies −\n\nSAPUI5 standard libraries (including SAP Fiori applications and SAP Fiori Launchpad)\nUnified Rendering technologies (such as Web Dynpro ABAP and Floorplan Manager)\nSAP NetWeaver Business Client\n" }, { "code": null, "e": 38603, "s": 38490, "text": "Cross-technology theming − Create one consistent theme that applies to various SAP UI clients and technologies −" }, { "code": null, "e": 38688, "s": 38603, "text": "SAPUI5 standard libraries (including SAP Fiori applications and SAP Fiori Launchpad)" }, { "code": null, "e": 38773, "s": 38688, "text": "SAPUI5 standard libraries (including SAP Fiori applications and SAP Fiori Launchpad)" }, { "code": null, "e": 38852, "s": 38773, "text": "Unified Rendering technologies (such as Web Dynpro ABAP and Floorplan Manager)" }, { "code": null, "e": 38931, "s": 38852, "text": "Unified Rendering technologies (such as Web Dynpro ABAP and Floorplan Manager)" }, { "code": null, "e": 38961, "s": 38931, "text": "SAP NetWeaver Business Client" }, { "code": null, "e": 38991, "s": 38961, "text": "SAP NetWeaver Business Client" }, { "code": null, "e": 39061, "s": 38991, "text": "You can theme applications that do not use the following UI elements:" }, { "code": null, "e": 39072, "s": 39061, "text": "HTMLIsland" }, { "code": null, "e": 39086, "s": 39072, "text": "HTMLContainer" }, { "code": null, "e": 39092, "s": 39086, "text": "Chart" }, { "code": null, "e": 39104, "s": 39092, "text": "FlashIsland" }, { "code": null, "e": 39122, "s": 39104, "text": "SilverlightIsland" }, { "code": null, "e": 39139, "s": 39122, "text": "BusinessGraphics" }, { "code": null, "e": 39264, "s": 39139, "text": "You can only consume themes created with the UI theme designer for Web Dynpro ABAP applications as of SAP NetWeaver 7.0 EHP2" }, { "code": null, "e": 39383, "s": 39264, "text": "NWBC for Desktop (4.0 or higher): You can theme NWBC shell and overview pages (index page, new tab page, service map)." }, { "code": null, "e": 39463, "s": 39383, "text": "NWBC for HTML (3.6): You can theme the service map. The shell cannot be themed." }, { "code": null, "e": 39608, "s": 39463, "text": "Step 1 − Login to SAP Fiori Front-End server. You can use T-Code: Theme Designer or use shortcut as shown in the following screenshot and login." }, { "code": null, "e": 39750, "s": 39608, "text": "Step 2 − Once you login, you will have all the default templates provided by SAP for Theme Designer. Select the default theme and click Open." }, { "code": null, "e": 39833, "s": 39750, "text": "Step 3 − Enter the Fiori Launchpad link and Name of the application and click Add." }, { "code": null, "e": 39998, "s": 39833, "text": "Step 4 − From the right side of the screen panel, you can select Color, Font, Image and other properties. You can edit colors as shown in the following screenshots." }, { "code": null, "e": 40143, "s": 39998, "text": "Step 5 − To save the Theme, you can click the Save icon as shown in the following screenshot. You also have an option for save and build option." }, { "code": null, "e": 40279, "s": 40143, "text": "Once you click Save and Build, it will start saving and when completed, you will get a confirmation message - Save and Build completed." }, { "code": null, "e": 40376, "s": 40279, "text": "Step 6 − To get the link of this Custom Theme, use T-code as shown in the following screenshot −" }, { "code": null, "e": 40448, "s": 40376, "text": "Step 7 − Select the Theme that you have created and click the Info tab." }, { "code": null, "e": 40525, "s": 40448, "text": "Step 8 − Use Ctrl+Y to copy the URL from the screen and make a note of this." }, { "code": null, "e": 40582, "s": 40525, "text": "These are the default themes that are shipped with UI5 −" }, { "code": null, "e": 40595, "s": 40582, "text": "Blue Crystal" }, { "code": null, "e": 40611, "s": 40595, "text": "Gold Reflection" }, { "code": null, "e": 40634, "s": 40611, "text": "Mobile Visual Identify" }, { "code": null, "e": 40654, "s": 40634, "text": "High Contrast Black" }, { "code": null, "e": 40834, "s": 40654, "text": "There are various chart types in sap.viz.ui5 charting library that can be used to represent the business data. Following are some CVOM chart types- Column, Bubble, Line, Pie, etc." }, { "code": null, "e": 41040, "s": 40834, "text": "SAP UI5 applications run on different mobile devices like iPad and smartphones. However, for better user experience, you need to control the appearance, touch interactions, and various other UI parameters." }, { "code": null, "e": 41193, "s": 41040, "text": "UI5 contains a control library sap.m that supports application development for mobile devices and supports all key concepts like data binding, MVC, etc." }, { "code": null, "e": 41239, "s": 41193, "text": "Platform support for Android, iOS, BlackBerry" }, { "code": null, "e": 41263, "s": 41239, "text": "It contains 40 controls" }, { "code": null, "e": 41295, "s": 41263, "text": "Webkit browsers - Google Chrome" }, { "code": null, "e": 41350, "s": 41295, "text": "UI5 concepts - MVC, localization, modularization, etc." }, { "code": null, "e": 41440, "s": 41350, "text": "In this chapter, we will learn how to create a project in Web IDE. Let’s go step by step." }, { "code": null, "e": 41500, "s": 41440, "text": "Step 1 − To start a new project, go to File → New → Project" }, { "code": null, "e": 41581, "s": 41500, "text": "Step 2 − Enter the name of the project. In the next window, select the template." }, { "code": null, "e": 41640, "s": 41581, "text": "Step 3 − Select template SAPUI5 Mobile Applications → Next" }, { "code": null, "e": 41725, "s": 41640, "text": "Step 4 − The next step is to select the data connection. Select service URL → Select" }, { "code": null, "e": 41796, "s": 41725, "text": "Step 5 − In the next step, you have to perform template customization." }, { "code": null, "e": 41855, "s": 41796, "text": "Step 6 − On clicking Next, you will see the Finish button." }, { "code": null, "e": 42012, "s": 41855, "text": "Once you click Finish, you can see a new project created that has default structure of UI application. It contains the view, model, and name of the project." }, { "code": null, "e": 42045, "s": 42012, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 42059, "s": 42045, "text": " Sanjo Thomas" }, { "code": null, "e": 42092, "s": 42059, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 42104, "s": 42092, "text": " Neha Gupta" }, { "code": null, "e": 42139, "s": 42104, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 42154, "s": 42139, "text": " Sumit Agarwal" }, { "code": null, "e": 42187, "s": 42154, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 42202, "s": 42187, "text": " Sumit Agarwal" }, { "code": null, "e": 42237, "s": 42202, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 42249, "s": 42237, "text": " Neha Malik" }, { "code": null, "e": 42284, "s": 42249, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 42296, "s": 42284, "text": " Neha Malik" }, { "code": null, "e": 42303, "s": 42296, "text": " Print" }, { "code": null, "e": 42314, "s": 42303, "text": " Add Notes" } ]
Using Association Rules for HR Analysis | by Eduardo Furtado | Towards Data Science
Association Rules algorithms such as Apriori are a great way to find what items regularly occur together in your dataset and see their relationship. It is an unsupervised machine learning model commonly used to find relationships in transactions, eg. clients purchases. An item is considered frequent if its occurrences is greater than the threshold we set. If you have 100 lines of data and set a threshold of 0.1, everything that happens more than 10 times will show in our result. In this example, we’ll use Apriori for a different type of problem. We are going to use an HR dataset that contains ages, gender, level of education, etc and we will try to find the frequent characteristics that happen when the employees do not have Attrition. Firstly a quick recap of the main Apriori components: Support is how much an item appearsfreq(A, B)/Total Confidence is the probability of B happening given that A happenedfreq(A, B)/freq(A) Lift is similar to the confidence but it also accounts for how popular B isfreq(A, B)/support(A)*Support(B) In this example, we’ll use the IBM HR Analytics Employee Attrition & Performance from Kaggle which you can download from the link below: www.kaggle.com This code will be written in Python using the MLxtend library (http://rasbt.github.io/mlxtend/) Firstly, we import our libraries. For this project, only Pandas and MLxtend are needed. import pandas as pdfrom mlxtend.frequent_patterns import apriorifrom mlxtend.frequent_patterns import association_rules After reading the data, we can see that there are 35 columns to work with but we will only use a few that look more interesting to us. There are a couple of columns that would be nice to use but they are not categorical, so what we can do is create bins for them. Pandas qcut function can divide the Age, DistanceFromHome and HourlyRate columns into bins of 4 for us. pd.qcut(df['Age'], q=4) This piece of code shows us that the Age column could be divided in these 4 categories: Categories (4, interval[float64]): [(17.999, 30.0] < (30.0, 36.0] < (36.0, 43.0] < (43.0, 60.0]] So we can create an Age_Range column like so: df['Age_Range'] = pd.qcut(df['Age'], q=4, labels=['<=30', '>30 <=36', '>36 <=43', '>43']) After doing the same for DistanceFromHome and HourlyRate now we have to prepare our data for the algorithm. Apriori only accepts boolean values, so instead of sending the MaritalStatus column with ‘Single’, ‘Married’ and ‘Divorced’ values we will convert this into 3 different columns called ‘MaritalStatus_Single’, ‘MaritalStatus_Married’ and ‘MaritalStatus_Divorced’ with 0 or 1 values in them. For this, the Pandas get_dummies function can be used for each column that needs to be converted. First we’ll create a list with all the columns that are going to used, and also a second list with the remaining columns. After using get_dummies, the original columns will be removed and only the boolean columns will be there, however, the unused columns are still there too, so we drop them. columns = ['Attrition', 'Age_Range', 'BusinessTravel', 'Department', 'DistanceFromHome_Range', 'Education', 'EducationField', 'EnvironmentSatisfaction', 'Gender', 'HourlyRate_Range', 'JobInvolvement', 'JobLevel', 'JobRole', 'JobSatisfaction', 'MaritalStatus']not_used_columns = list(set(df.columns.to_list()) - set(columns))df = pd.get_dummies(df, columns=columns)df.drop(labels=not_used_columns, axis=1, inplace=True) Now we have a dataframe ready to use and generate the frequent items. Our dataset has a total of 1470 lines so let’s start choosing a minimum support of 0.05. This means that only results that occurred more than 73 times in our data will be considered. And max_len is the amount of columns combinations generated in the antecedents column. #Apriori min supportmin_support = 0.05#Max lenght of apriori n-gramsmax_len = 3frequent_items = apriori(df, use_colnames=True, min_support=min_support, max_len=max_len + 1)rules = association_rules(frequent_items, metric='lift', min_threshold=1)rules.head(10).sort_values(by='confidence', ascending=False) That’s it! Now you can see the frequent relationships in the dataset. But what if we want to know only what gives us ‘Attrition_Yes’ or ‘Attrition_No’ in the consequents column? First of all, let’s see how many occurrences of each there is in our dataframe. df['Attrition_No'].value_counts()#1 1233#0 237#Name: Attrition_No, dtype: int64 There are way more cases of No than Yes so we’ll also need to take that in consideration choosing our threshold since one is more common than the other. For No, let’s increase the threshold to 0.1 and filter the consequents column for Attrition_No: #Apriori min supportmin_support = 0.1#Max lenght of apriori n-gramsmax_len = 3frequent_items = apriori(df, use_colnames=True, min_support=min_support, max_len=max_len + 1)rules = association_rules(frequent_items, metric='lift', min_threshold=1)target = '{\'Attrition_No\'}'results_attrition_no = rules[rules['consequents'].astype(str).str.contains(target, na=False)].sort_values(by='confidence', ascending=False)results_attrition_no.head(10) Now we can see that a person that is from the Research & Development Department and Job Level 2 happens 11% of the time in our dataset, however almost 95% of those do not have Attrition. Sidenote: the antecedents and consequents columns are frozensets which look like this: array([frozenset({‘JobSatisfaction_4’, ‘JobLevel_2’}), frozenset({‘Department_Research_&_Development’, ‘JobLevel_2’}), frozenset({‘Department_Research_&_Development’, ‘JobInvolvement_3’, ‘JobLevel_2’})... If you want to beautify it and export this result you can use this piece of code: df['antecedents'] = df['antecedents'].apply(lambda x: ','.join(list(x))).astype('unicode')df['antecedents'] = df['antecedents'].str.title().str.replace('_', ' ') Now let’s change our threshold to 0.02 and see what we have for Attrition_Yes: The biggest confidence is for people younger than 30 years old, single and Job Level 1. But differently from the previous case, only 45% of those cases have Attrition. And that’s the very basic of using Apriori with HR data! Hope you try it in your next project and find new relationships in your dataset that can give you more insights to your problem. You can download all the notebook used to create this post here: https://gist.github.com/eduardoftdo/e3d2b7ca4a06d8d86b144482d0aed5a1 If you have any questions and would like to contact me, feel free to send a message at https://www.linkedin.com/in/eduardo-furtado/
[ { "code": null, "e": 442, "s": 172, "text": "Association Rules algorithms such as Apriori are a great way to find what items regularly occur together in your dataset and see their relationship. It is an unsupervised machine learning model commonly used to find relationships in transactions, eg. clients purchases." }, { "code": null, "e": 656, "s": 442, "text": "An item is considered frequent if its occurrences is greater than the threshold we set. If you have 100 lines of data and set a threshold of 0.1, everything that happens more than 10 times will show in our result." }, { "code": null, "e": 917, "s": 656, "text": "In this example, we’ll use Apriori for a different type of problem. We are going to use an HR dataset that contains ages, gender, level of education, etc and we will try to find the frequent characteristics that happen when the employees do not have Attrition." }, { "code": null, "e": 971, "s": 917, "text": "Firstly a quick recap of the main Apriori components:" }, { "code": null, "e": 1023, "s": 971, "text": "Support is how much an item appearsfreq(A, B)/Total" }, { "code": null, "e": 1108, "s": 1023, "text": "Confidence is the probability of B happening given that A happenedfreq(A, B)/freq(A)" }, { "code": null, "e": 1216, "s": 1108, "text": "Lift is similar to the confidence but it also accounts for how popular B isfreq(A, B)/support(A)*Support(B)" }, { "code": null, "e": 1353, "s": 1216, "text": "In this example, we’ll use the IBM HR Analytics Employee Attrition & Performance from Kaggle which you can download from the link below:" }, { "code": null, "e": 1368, "s": 1353, "text": "www.kaggle.com" }, { "code": null, "e": 1464, "s": 1368, "text": "This code will be written in Python using the MLxtend library (http://rasbt.github.io/mlxtend/)" }, { "code": null, "e": 1552, "s": 1464, "text": "Firstly, we import our libraries. For this project, only Pandas and MLxtend are needed." }, { "code": null, "e": 1672, "s": 1552, "text": "import pandas as pdfrom mlxtend.frequent_patterns import apriorifrom mlxtend.frequent_patterns import association_rules" }, { "code": null, "e": 1807, "s": 1672, "text": "After reading the data, we can see that there are 35 columns to work with but we will only use a few that look more interesting to us." }, { "code": null, "e": 2040, "s": 1807, "text": "There are a couple of columns that would be nice to use but they are not categorical, so what we can do is create bins for them. Pandas qcut function can divide the Age, DistanceFromHome and HourlyRate columns into bins of 4 for us." }, { "code": null, "e": 2064, "s": 2040, "text": "pd.qcut(df['Age'], q=4)" }, { "code": null, "e": 2152, "s": 2064, "text": "This piece of code shows us that the Age column could be divided in these 4 categories:" }, { "code": null, "e": 2249, "s": 2152, "text": "Categories (4, interval[float64]): [(17.999, 30.0] < (30.0, 36.0] < (36.0, 43.0] < (43.0, 60.0]]" }, { "code": null, "e": 2295, "s": 2249, "text": "So we can create an Age_Range column like so:" }, { "code": null, "e": 2385, "s": 2295, "text": "df['Age_Range'] = pd.qcut(df['Age'], q=4, labels=['<=30', '>30 <=36', '>36 <=43', '>43'])" }, { "code": null, "e": 2782, "s": 2385, "text": "After doing the same for DistanceFromHome and HourlyRate now we have to prepare our data for the algorithm. Apriori only accepts boolean values, so instead of sending the MaritalStatus column with ‘Single’, ‘Married’ and ‘Divorced’ values we will convert this into 3 different columns called ‘MaritalStatus_Single’, ‘MaritalStatus_Married’ and ‘MaritalStatus_Divorced’ with 0 or 1 values in them." }, { "code": null, "e": 3174, "s": 2782, "text": "For this, the Pandas get_dummies function can be used for each column that needs to be converted. First we’ll create a list with all the columns that are going to used, and also a second list with the remaining columns. After using get_dummies, the original columns will be removed and only the boolean columns will be there, however, the unused columns are still there too, so we drop them." }, { "code": null, "e": 3719, "s": 3174, "text": "columns = ['Attrition', 'Age_Range', 'BusinessTravel', 'Department', 'DistanceFromHome_Range', 'Education', 'EducationField', 'EnvironmentSatisfaction', 'Gender', 'HourlyRate_Range', 'JobInvolvement', 'JobLevel', 'JobRole', 'JobSatisfaction', 'MaritalStatus']not_used_columns = list(set(df.columns.to_list()) - set(columns))df = pd.get_dummies(df, columns=columns)df.drop(labels=not_used_columns, axis=1, inplace=True)" }, { "code": null, "e": 3789, "s": 3719, "text": "Now we have a dataframe ready to use and generate the frequent items." }, { "code": null, "e": 4059, "s": 3789, "text": "Our dataset has a total of 1470 lines so let’s start choosing a minimum support of 0.05. This means that only results that occurred more than 73 times in our data will be considered. And max_len is the amount of columns combinations generated in the antecedents column." }, { "code": null, "e": 4365, "s": 4059, "text": "#Apriori min supportmin_support = 0.05#Max lenght of apriori n-gramsmax_len = 3frequent_items = apriori(df, use_colnames=True, min_support=min_support, max_len=max_len + 1)rules = association_rules(frequent_items, metric='lift', min_threshold=1)rules.head(10).sort_values(by='confidence', ascending=False)" }, { "code": null, "e": 4435, "s": 4365, "text": "That’s it! Now you can see the frequent relationships in the dataset." }, { "code": null, "e": 4543, "s": 4435, "text": "But what if we want to know only what gives us ‘Attrition_Yes’ or ‘Attrition_No’ in the consequents column?" }, { "code": null, "e": 4623, "s": 4543, "text": "First of all, let’s see how many occurrences of each there is in our dataframe." }, { "code": null, "e": 4711, "s": 4623, "text": "df['Attrition_No'].value_counts()#1 1233#0 237#Name: Attrition_No, dtype: int64" }, { "code": null, "e": 4864, "s": 4711, "text": "There are way more cases of No than Yes so we’ll also need to take that in consideration choosing our threshold since one is more common than the other." }, { "code": null, "e": 4960, "s": 4864, "text": "For No, let’s increase the threshold to 0.1 and filter the consequents column for Attrition_No:" }, { "code": null, "e": 5402, "s": 4960, "text": "#Apriori min supportmin_support = 0.1#Max lenght of apriori n-gramsmax_len = 3frequent_items = apriori(df, use_colnames=True, min_support=min_support, max_len=max_len + 1)rules = association_rules(frequent_items, metric='lift', min_threshold=1)target = '{\\'Attrition_No\\'}'results_attrition_no = rules[rules['consequents'].astype(str).str.contains(target, na=False)].sort_values(by='confidence', ascending=False)results_attrition_no.head(10)" }, { "code": null, "e": 5589, "s": 5402, "text": "Now we can see that a person that is from the Research & Development Department and Job Level 2 happens 11% of the time in our dataset, however almost 95% of those do not have Attrition." }, { "code": null, "e": 5676, "s": 5589, "text": "Sidenote: the antecedents and consequents columns are frozensets which look like this:" }, { "code": null, "e": 5881, "s": 5676, "text": "array([frozenset({‘JobSatisfaction_4’, ‘JobLevel_2’}), frozenset({‘Department_Research_&_Development’, ‘JobLevel_2’}), frozenset({‘Department_Research_&_Development’, ‘JobInvolvement_3’, ‘JobLevel_2’})..." }, { "code": null, "e": 5963, "s": 5881, "text": "If you want to beautify it and export this result you can use this piece of code:" }, { "code": null, "e": 6125, "s": 5963, "text": "df['antecedents'] = df['antecedents'].apply(lambda x: ','.join(list(x))).astype('unicode')df['antecedents'] = df['antecedents'].str.title().str.replace('_', ' ')" }, { "code": null, "e": 6204, "s": 6125, "text": "Now let’s change our threshold to 0.02 and see what we have for Attrition_Yes:" }, { "code": null, "e": 6372, "s": 6204, "text": "The biggest confidence is for people younger than 30 years old, single and Job Level 1. But differently from the previous case, only 45% of those cases have Attrition." }, { "code": null, "e": 6558, "s": 6372, "text": "And that’s the very basic of using Apriori with HR data! Hope you try it in your next project and find new relationships in your dataset that can give you more insights to your problem." }, { "code": null, "e": 6692, "s": 6558, "text": "You can download all the notebook used to create this post here: https://gist.github.com/eduardoftdo/e3d2b7ca4a06d8d86b144482d0aed5a1" } ]
MATLAB - Determinant of a Matrix
Determinant of a matrix is calculated using the det function of MATLAB. Determinant of a matrix A is given by det(A). Create a script file with the following code − a = [ 1 2 3; 2 3 4; 1 2 5] det(a) When you run the file, it displays the following result − a = 1 2 3 2 3 4 1 2 5 ans = -2 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2259, "s": 2141, "text": "Determinant of a matrix is calculated using the det function of MATLAB. Determinant of a matrix A is given by det(A)." }, { "code": null, "e": 2306, "s": 2259, "text": "Create a script file with the following code −" }, { "code": null, "e": 2340, "s": 2306, "text": "a = [ 1 2 3; 2 3 4; 1 2 5]\ndet(a)" }, { "code": null, "e": 2398, "s": 2340, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2472, "s": 2398, "text": "a =\n 1 2 3\n 2 3 4\n 1 2 5\nans = -2\n" }, { "code": null, "e": 2505, "s": 2472, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2518, "s": 2505, "text": " Nouman Azam" }, { "code": null, "e": 2553, "s": 2518, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 2566, "s": 2553, "text": " Nouman Azam" }, { "code": null, "e": 2599, "s": 2566, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 2608, "s": 2599, "text": " Sanjeev" }, { "code": null, "e": 2641, "s": 2608, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 2657, "s": 2641, "text": " TELCOMA Global" }, { "code": null, "e": 2690, "s": 2657, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 2706, "s": 2690, "text": " TELCOMA Global" }, { "code": null, "e": 2739, "s": 2706, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 2756, "s": 2739, "text": " Phinite Academy" }, { "code": null, "e": 2763, "s": 2756, "text": " Print" }, { "code": null, "e": 2774, "s": 2763, "text": " Add Notes" } ]
Marketing Mix Modeling with Facebook’s Robyn | Towards Data Science
This article provides you a first overview of Facebook Experimental’s Robyn. Since the Facebook Marketing Science team has already created a great quick start guide and very detailed pages, I try to keep the article short and on point. For detailed explanations, you can find more information here. Facebook Experimental’s Robyn is an automated Marketing Mix Modeling (MMM) code which is currently in beta version. It offers two adstock (geometric and weibull) and an s-curve transformation (diminishing returns) techniques for feature transformation. To take time series features into account Robyn makes use of Facebook Prophet. It generates a set of Pareto optimal model solutions by making use of Facebook’s Nevergrad gradient-free optimization platform. To increase the model’s accuracy it allows you to include results from randomized controlled-experiments. Two big questions every marketeer has are What’s the impact of my current marketing channels? and How should I allocate my budget strategically to get the optimal marketing mix? These questions are not new. John Wanamaker (1838–1922), considered by some to be a pioneer in marketing had the same questions and is known for his famous and often cited quote: Half my advertising spend is wasted; the trouble is, I don’t know which half. To address these challenges econometricians developed multivariate regression techniques known as Marketing Mix Modeling (MMM). A very new tool in this area and currently in its beta version is Facebook’s Robyn. The Facebook Experimental team describes Robyn as [...] an automated Marketing Mix Modeling (MMM) code. It aims to reduce human bias by means of ridge regression and evolutionary algorithms, enables actionable decision making providing a budget allocator and diminishing returns curves and allows ground-truth calibration to account for causation. In the following, I’ll give you a quick overview of Robyn’s features and main ideas. Since it is still in beta version, the code and concepts used might change. You can find its latest version here. It was quite tricky to find a suitable open data set for this article so I used Google’s Agreggate Marketing System Simulator (AMSS) to generate a simple data set for this purpose. If you are interested in more details about AMSS you can find their paper here and if you’d like to use the same data set I used you can find it here. You will find in the following a description table and plots of the marketing data to get more familiar with the data set. The used data set is based on weekly data and contains 208 entries. All values are in EUR (€) and no NA values exist. Our target variable is revenue while the other columns are features that can be used to explain it. Columns ending with a _S are our marketing budget expenses by channel (TV, radio, paid search). Our competitor sales are given by the self explaining column competitor_sales. A column that is not shown in the description table is the DATE column, representing the corresponding week in the format YYYY-MM-DD. Figure 1 shows the revenue, its components, competitor sales and marketing expenses over time. We can clearly see a seasonality (A1) in the revenue as well as a bit of a trend (A2). It can be also seen that the competitor sales follow a very similar pattern like our revenue, that we have gaps in the spring months in radio expenses and a seasonality as well as a trend in Paid Search expenses. Figure 2 shows the correlation plot of our data set to get a first idea of the relationships between the variables. We can see a high correlation between competitor sales and our revenue followed by a lower correlation of 0.4 between our expenses in Paid search and our revenue as well as competitor sales. Now that you are a bit more familiar with the data set, let us now use Robyn. To get the latest version of Robyn we clone it’s repository to our machine: git clone https://github.com/facebookexperimental/Robyn After we cloned the repository, we create a new folder called plots to store the visualizations of the later outcomes. Your folder structure should now look like this: Robyn/├── CHANGELOG.md├── CODE_OF_CONDUCT.md├── CONTRIBUTING.md├── LICENSE.md├── README.md├── Robyn.Rproj├── plots├── source│ ├── de_simulated_data.csv│ ├── fb_robyn.exec.R│ ├── fb_robyn.func.R│ ├── fb_robyn.optm.R│ └── holidays.csv├── website The main file we are interested in lies in the source folder and is called fb_robyn.exec.R. This is the file where we have to set our configuration and run the wrangling, modeling, optimization and if needed budget allocation process. But before we go there, let us have a short look what (modeling) techniques Robyn uses. The following points describe what is under Robyn’s hood on a high level. For more detailed information and explanation see their docs. The developer’s motivation to use a regularization method was to address multicollinearity among many regressors and prevent the model from overfitting. The model’s equation with the main components of the function is shown in figure 3. Where yt is our dependent variable revenue at time t. The independent variables are defined by the intercept, followed by the ad-stock and s-curve transformed component for each media j. Holiday, seasonality and trend effects are represented by hol, sea and trend. Additional independent variables are defined by ETC followed by the error term ε. Very common transformation techniques in MMM are ad-stock and s-curve (diminishing returns) transformations. Ad-stock transformationThe idea behind the ad-stock transformation is that advertising effects usually do not immediately take effect. They have a half-life. Customers (usually) do not run instantly to the stores and buy your product after they saw your commercial. Your ads take some time to wear in. Robyn offers here two methods, the classical geometric one, and the more flexible weibull survival function. For a deeper explanation, please see the docs. S-curve (diminishing returns) transformationThe basic idea behind this transformation is that an advertisement loses its effectiveness over time, even if more money is allocated to it. In order to include time-series features or components like trend, seasonality, or holidays in the model, Robyn makes use of Facebooks Prophet. Robyn uses the Facebook’s Nevergrad gradient-free optimization platform to perform a multi-objective optimization that balances out the relationship between spend share and channels coefficient decomposition share by providing a set of Pareto optimal model solutions. These Pareto optimal model solutions are the result of running an evolutionary algorithm (natural selection) over several iterations (i.e., with 20,000 iterations and possible model solutions) Robyn allows us to apply results from randomized controlled experiments to increase the model’s accuracy, where these results are used as a prior to shrink the coefficients of media variables. This part is not covered in this article. If you are interested in more details, you can find their documentation here. Now that we a basic overview of Robyn’s techniques let’s continue with our use case. You will find at the end of this article the complete code. We run the Robyn.Rproj with R-Studio and open the fb_robyn.exec.R located in the source folder. The first thing you should do if your OS is not English to uncomment line 13: Otherwise you will get errors in the data wrangling process (line 166). Make sure to install all the used libraries, create a conda environment called r-reticulate, install nevergrad and use the created conda env. Now it is time to load our csv file. The dev team already provides a file called de_simulated_data.csv. Since I am using my own simulated file I change the line. The dev team also provides a holiday file which includes public holidays from several countries (i.e. US, UK, IN, DE). In this part, we link the configuration in the code to the columns in our data set. This part is very crucial since typos will lead to errors during the automated data wrangling process. Robyn allows us to either use the geometric or weibull adstock technique. In this article, we stay with the geometric one, but it is definitely worth trying out the weibull technique. Since Robyn uses Nevergrad, we have to select an algorithm as well as the number of trials. Here we also stick to the default ones. According to our defined variables and used ad-stock method, we have to set their hyperparameter bounds. Now that we have all parameters set, we can run our model by using the following code. Robyn is now running and will automatically generate plots in our specified plots folder. After the modeling process is done, you should find several files in your plots folder. These plots (with the model id as their name) represent the optimal model solutions based on the Pareto optimal process (pareto_front.png) and provide us additional information about hyperparameter selection (hypersampling.png). Figure 4. shows the model one-pager for one of these models (3_30_1). Response decomposition waterfall by predictorShows the percentage of each of the features effect on the response variable (revenue). In this example 34.08% of the revenue can be attributed to seasonality and 11.62% to TV commercials and so on. Share of spend vs. share of effectThis plot describes the share of spend and the share of effect by channel. In addition to that, it also shows the return on investment (ROI) of each channel. For our example, we can see that the channel radio has the highest ROI followed by TV and Paid search. It also shows that the average expenses on TV are a bit larger than their average effect share. This likely means that they are hitting some diminishing returns. Average ad-stock decay rateShows each channel’s percentage decay rate. The higher the decay rate, the longer the decay effect lasts. For this example, the channel TV has the highest average decay rate. Actual vs. predicted responseThis plot compares the actuals with our prediction. Our aim is that our model can explain most of the variance in the data. Therefore we are looking for a high R-squared (rsq) and a low NRMSE. Response curves and mean spend by channelIndicates the saturation of each channel and may suggest potential budget reallocation strategies. Looking at the curves, the faster they reach to an inflection point and to a flat slope, the quicker they will saturate with each additional € spent. For our example, the curves for radio and paid search do not show any flat slope and may require further investigations. Fitted vs. residual The classic chart to check if there are any problems with our regression model. Once we decided on a reasonable(!!) model, we can run budget optimization simulations to calculate the optimal media spend allocation. We have two types of simulation scenarios: max_historical_response max_response_expected_spend The first one will use the historical data and spend that contributed to the model to calculate how the most optimized media plan would be. The second one calculates the optimal media plan given a certain budget and a number of days. All the models are stored in the model_output_collect$allSolutions variable. Assuming we want to go with the model above (3_30_1) we just use the following code: Besides the model id and scenario type we also have to set lower and upper bounds for our used channels. If the lower bound of our channel is 0.7 and the upper bound is 1.2 then our spend change will be constrained by 0.7 times the average time period spend and 1.2 times the average time period spend. After we run that code Robyn outputs a new one-pager (figure 5). The two left charts show how the budget allocation and mean response would change if we would follow the budget optimization. The chart on the right shows the response curves for each channel with the initial vs. recommended average spend level. The idea of this article was to provide you a first overview of Facebook Experimental’s Robyn and how to use it by using a simplified data set. For deeper explanations, the use of experimental results, and more details, I highly suggest you to check out Robyn’s documentation. Unlike in this short introduction, it is also important to really focus and invest time on the model selection part. Only with a reasonable model, it makes sense to discuss the results with the business and to use the budget optimization step. Even if the project is still in beta, the motivation and ideas behind it and its features are very clever and quite impressive! If I could make three wishes, I would love to have an option to use panel regression for cross-sectional data. Second, it would be also great to find a way to decrease the computational time. Third, similar to the first wish, using categorical variables not only as baseline variables would be nice. ...and if I could make a fourth one... a port to Python would be great ;) The code for the complete file:
[ { "code": null, "e": 471, "s": 172, "text": "This article provides you a first overview of Facebook Experimental’s Robyn. Since the Facebook Marketing Science team has already created a great quick start guide and very detailed pages, I try to keep the article short and on point. For detailed explanations, you can find more information here." }, { "code": null, "e": 587, "s": 471, "text": "Facebook Experimental’s Robyn is an automated Marketing Mix Modeling (MMM) code which is currently in beta version." }, { "code": null, "e": 724, "s": 587, "text": "It offers two adstock (geometric and weibull) and an s-curve transformation (diminishing returns) techniques for feature transformation." }, { "code": null, "e": 803, "s": 724, "text": "To take time series features into account Robyn makes use of Facebook Prophet." }, { "code": null, "e": 931, "s": 803, "text": "It generates a set of Pareto optimal model solutions by making use of Facebook’s Nevergrad gradient-free optimization platform." }, { "code": null, "e": 1037, "s": 931, "text": "To increase the model’s accuracy it allows you to include results from randomized controlled-experiments." }, { "code": null, "e": 1215, "s": 1037, "text": "Two big questions every marketeer has are What’s the impact of my current marketing channels? and How should I allocate my budget strategically to get the optimal marketing mix?" }, { "code": null, "e": 1394, "s": 1215, "text": "These questions are not new. John Wanamaker (1838–1922), considered by some to be a pioneer in marketing had the same questions and is known for his famous and often cited quote:" }, { "code": null, "e": 1472, "s": 1394, "text": "Half my advertising spend is wasted; the trouble is, I don’t know which half." }, { "code": null, "e": 1734, "s": 1472, "text": "To address these challenges econometricians developed multivariate regression techniques known as Marketing Mix Modeling (MMM). A very new tool in this area and currently in its beta version is Facebook’s Robyn. The Facebook Experimental team describes Robyn as" }, { "code": null, "e": 2032, "s": 1734, "text": "[...] an automated Marketing Mix Modeling (MMM) code. It aims to reduce human bias by means of ridge regression and evolutionary algorithms, enables actionable decision making providing a budget allocator and diminishing returns curves and allows ground-truth calibration to account for causation." }, { "code": null, "e": 2231, "s": 2032, "text": "In the following, I’ll give you a quick overview of Robyn’s features and main ideas. Since it is still in beta version, the code and concepts used might change. You can find its latest version here." }, { "code": null, "e": 2563, "s": 2231, "text": "It was quite tricky to find a suitable open data set for this article so I used Google’s Agreggate Marketing System Simulator (AMSS) to generate a simple data set for this purpose. If you are interested in more details about AMSS you can find their paper here and if you’d like to use the same data set I used you can find it here." }, { "code": null, "e": 2686, "s": 2563, "text": "You will find in the following a description table and plots of the marketing data to get more familiar with the data set." }, { "code": null, "e": 2904, "s": 2686, "text": "The used data set is based on weekly data and contains 208 entries. All values are in EUR (€) and no NA values exist. Our target variable is revenue while the other columns are features that can be used to explain it." }, { "code": null, "e": 3079, "s": 2904, "text": "Columns ending with a _S are our marketing budget expenses by channel (TV, radio, paid search). Our competitor sales are given by the self explaining column competitor_sales." }, { "code": null, "e": 3213, "s": 3079, "text": "A column that is not shown in the description table is the DATE column, representing the corresponding week in the format YYYY-MM-DD." }, { "code": null, "e": 3308, "s": 3213, "text": "Figure 1 shows the revenue, its components, competitor sales and marketing expenses over time." }, { "code": null, "e": 3608, "s": 3308, "text": "We can clearly see a seasonality (A1) in the revenue as well as a bit of a trend (A2). It can be also seen that the competitor sales follow a very similar pattern like our revenue, that we have gaps in the spring months in radio expenses and a seasonality as well as a trend in Paid Search expenses." }, { "code": null, "e": 3724, "s": 3608, "text": "Figure 2 shows the correlation plot of our data set to get a first idea of the relationships between the variables." }, { "code": null, "e": 3915, "s": 3724, "text": "We can see a high correlation between competitor sales and our revenue followed by a lower correlation of 0.4 between our expenses in Paid search and our revenue as well as competitor sales." }, { "code": null, "e": 3993, "s": 3915, "text": "Now that you are a bit more familiar with the data set, let us now use Robyn." }, { "code": null, "e": 4069, "s": 3993, "text": "To get the latest version of Robyn we clone it’s repository to our machine:" }, { "code": null, "e": 4125, "s": 4069, "text": "git clone https://github.com/facebookexperimental/Robyn" }, { "code": null, "e": 4244, "s": 4125, "text": "After we cloned the repository, we create a new folder called plots to store the visualizations of the later outcomes." }, { "code": null, "e": 4293, "s": 4244, "text": "Your folder structure should now look like this:" }, { "code": null, "e": 4547, "s": 4293, "text": "Robyn/├── CHANGELOG.md├── CODE_OF_CONDUCT.md├── CONTRIBUTING.md├── LICENSE.md├── README.md├── Robyn.Rproj├── plots├── source│ ├── de_simulated_data.csv│ ├── fb_robyn.exec.R│ ├── fb_robyn.func.R│ ├── fb_robyn.optm.R│ └── holidays.csv├── website" }, { "code": null, "e": 4782, "s": 4547, "text": "The main file we are interested in lies in the source folder and is called fb_robyn.exec.R. This is the file where we have to set our configuration and run the wrangling, modeling, optimization and if needed budget allocation process." }, { "code": null, "e": 4870, "s": 4782, "text": "But before we go there, let us have a short look what (modeling) techniques Robyn uses." }, { "code": null, "e": 5006, "s": 4870, "text": "The following points describe what is under Robyn’s hood on a high level. For more detailed information and explanation see their docs." }, { "code": null, "e": 5243, "s": 5006, "text": "The developer’s motivation to use a regularization method was to address multicollinearity among many regressors and prevent the model from overfitting. The model’s equation with the main components of the function is shown in figure 3." }, { "code": null, "e": 5590, "s": 5243, "text": "Where yt is our dependent variable revenue at time t. The independent variables are defined by the intercept, followed by the ad-stock and s-curve transformed component for each media j. Holiday, seasonality and trend effects are represented by hol, sea and trend. Additional independent variables are defined by ETC followed by the error term ε." }, { "code": null, "e": 5699, "s": 5590, "text": "Very common transformation techniques in MMM are ad-stock and s-curve (diminishing returns) transformations." }, { "code": null, "e": 6001, "s": 5699, "text": "Ad-stock transformationThe idea behind the ad-stock transformation is that advertising effects usually do not immediately take effect. They have a half-life. Customers (usually) do not run instantly to the stores and buy your product after they saw your commercial. Your ads take some time to wear in." }, { "code": null, "e": 6157, "s": 6001, "text": "Robyn offers here two methods, the classical geometric one, and the more flexible weibull survival function. For a deeper explanation, please see the docs." }, { "code": null, "e": 6342, "s": 6157, "text": "S-curve (diminishing returns) transformationThe basic idea behind this transformation is that an advertisement loses its effectiveness over time, even if more money is allocated to it." }, { "code": null, "e": 6486, "s": 6342, "text": "In order to include time-series features or components like trend, seasonality, or holidays in the model, Robyn makes use of Facebooks Prophet." }, { "code": null, "e": 6754, "s": 6486, "text": "Robyn uses the Facebook’s Nevergrad gradient-free optimization platform to perform a multi-objective optimization that balances out the relationship between spend share and channels coefficient decomposition share by providing a set of Pareto optimal model solutions." }, { "code": null, "e": 6947, "s": 6754, "text": "These Pareto optimal model solutions are the result of running an evolutionary algorithm (natural selection) over several iterations (i.e., with 20,000 iterations and possible model solutions)" }, { "code": null, "e": 7140, "s": 6947, "text": "Robyn allows us to apply results from randomized controlled experiments to increase the model’s accuracy, where these results are used as a prior to shrink the coefficients of media variables." }, { "code": null, "e": 7260, "s": 7140, "text": "This part is not covered in this article. If you are interested in more details, you can find their documentation here." }, { "code": null, "e": 7405, "s": 7260, "text": "Now that we a basic overview of Robyn’s techniques let’s continue with our use case. You will find at the end of this article the complete code." }, { "code": null, "e": 7501, "s": 7405, "text": "We run the Robyn.Rproj with R-Studio and open the fb_robyn.exec.R located in the source folder." }, { "code": null, "e": 7579, "s": 7501, "text": "The first thing you should do if your OS is not English to uncomment line 13:" }, { "code": null, "e": 7651, "s": 7579, "text": "Otherwise you will get errors in the data wrangling process (line 166)." }, { "code": null, "e": 7793, "s": 7651, "text": "Make sure to install all the used libraries, create a conda environment called r-reticulate, install nevergrad and use the created conda env." }, { "code": null, "e": 7955, "s": 7793, "text": "Now it is time to load our csv file. The dev team already provides a file called de_simulated_data.csv. Since I am using my own simulated file I change the line." }, { "code": null, "e": 8074, "s": 7955, "text": "The dev team also provides a holiday file which includes public holidays from several countries (i.e. US, UK, IN, DE)." }, { "code": null, "e": 8261, "s": 8074, "text": "In this part, we link the configuration in the code to the columns in our data set. This part is very crucial since typos will lead to errors during the automated data wrangling process." }, { "code": null, "e": 8445, "s": 8261, "text": "Robyn allows us to either use the geometric or weibull adstock technique. In this article, we stay with the geometric one, but it is definitely worth trying out the weibull technique." }, { "code": null, "e": 8577, "s": 8445, "text": "Since Robyn uses Nevergrad, we have to select an algorithm as well as the number of trials. Here we also stick to the default ones." }, { "code": null, "e": 8682, "s": 8577, "text": "According to our defined variables and used ad-stock method, we have to set their hyperparameter bounds." }, { "code": null, "e": 8769, "s": 8682, "text": "Now that we have all parameters set, we can run our model by using the following code." }, { "code": null, "e": 8859, "s": 8769, "text": "Robyn is now running and will automatically generate plots in our specified plots folder." }, { "code": null, "e": 8947, "s": 8859, "text": "After the modeling process is done, you should find several files in your plots folder." }, { "code": null, "e": 9176, "s": 8947, "text": "These plots (with the model id as their name) represent the optimal model solutions based on the Pareto optimal process (pareto_front.png) and provide us additional information about hyperparameter selection (hypersampling.png)." }, { "code": null, "e": 9246, "s": 9176, "text": "Figure 4. shows the model one-pager for one of these models (3_30_1)." }, { "code": null, "e": 9490, "s": 9246, "text": "Response decomposition waterfall by predictorShows the percentage of each of the features effect on the response variable (revenue). In this example 34.08% of the revenue can be attributed to seasonality and 11.62% to TV commercials and so on." }, { "code": null, "e": 9947, "s": 9490, "text": "Share of spend vs. share of effectThis plot describes the share of spend and the share of effect by channel. In addition to that, it also shows the return on investment (ROI) of each channel. For our example, we can see that the channel radio has the highest ROI followed by TV and Paid search. It also shows that the average expenses on TV are a bit larger than their average effect share. This likely means that they are hitting some diminishing returns." }, { "code": null, "e": 10149, "s": 9947, "text": "Average ad-stock decay rateShows each channel’s percentage decay rate. The higher the decay rate, the longer the decay effect lasts. For this example, the channel TV has the highest average decay rate." }, { "code": null, "e": 10371, "s": 10149, "text": "Actual vs. predicted responseThis plot compares the actuals with our prediction. Our aim is that our model can explain most of the variance in the data. Therefore we are looking for a high R-squared (rsq) and a low NRMSE." }, { "code": null, "e": 10782, "s": 10371, "text": "Response curves and mean spend by channelIndicates the saturation of each channel and may suggest potential budget reallocation strategies. Looking at the curves, the faster they reach to an inflection point and to a flat slope, the quicker they will saturate with each additional € spent. For our example, the curves for radio and paid search do not show any flat slope and may require further investigations." }, { "code": null, "e": 10882, "s": 10782, "text": "Fitted vs. residual The classic chart to check if there are any problems with our regression model." }, { "code": null, "e": 11060, "s": 10882, "text": "Once we decided on a reasonable(!!) model, we can run budget optimization simulations to calculate the optimal media spend allocation. We have two types of simulation scenarios:" }, { "code": null, "e": 11084, "s": 11060, "text": "max_historical_response" }, { "code": null, "e": 11112, "s": 11084, "text": "max_response_expected_spend" }, { "code": null, "e": 11252, "s": 11112, "text": "The first one will use the historical data and spend that contributed to the model to calculate how the most optimized media plan would be." }, { "code": null, "e": 11346, "s": 11252, "text": "The second one calculates the optimal media plan given a certain budget and a number of days." }, { "code": null, "e": 11508, "s": 11346, "text": "All the models are stored in the model_output_collect$allSolutions variable. Assuming we want to go with the model above (3_30_1) we just use the following code:" }, { "code": null, "e": 11811, "s": 11508, "text": "Besides the model id and scenario type we also have to set lower and upper bounds for our used channels. If the lower bound of our channel is 0.7 and the upper bound is 1.2 then our spend change will be constrained by 0.7 times the average time period spend and 1.2 times the average time period spend." }, { "code": null, "e": 11876, "s": 11811, "text": "After we run that code Robyn outputs a new one-pager (figure 5)." }, { "code": null, "e": 12122, "s": 11876, "text": "The two left charts show how the budget allocation and mean response would change if we would follow the budget optimization. The chart on the right shows the response curves for each channel with the initial vs. recommended average spend level." }, { "code": null, "e": 12399, "s": 12122, "text": "The idea of this article was to provide you a first overview of Facebook Experimental’s Robyn and how to use it by using a simplified data set. For deeper explanations, the use of experimental results, and more details, I highly suggest you to check out Robyn’s documentation." }, { "code": null, "e": 12643, "s": 12399, "text": "Unlike in this short introduction, it is also important to really focus and invest time on the model selection part. Only with a reasonable model, it makes sense to discuss the results with the business and to use the budget optimization step." }, { "code": null, "e": 12771, "s": 12643, "text": "Even if the project is still in beta, the motivation and ideas behind it and its features are very clever and quite impressive!" }, { "code": null, "e": 13145, "s": 12771, "text": "If I could make three wishes, I would love to have an option to use panel regression for cross-sectional data. Second, it would be also great to find a way to decrease the computational time. Third, similar to the first wish, using categorical variables not only as baseline variables would be nice. ...and if I could make a fourth one... a port to Python would be great ;)" } ]
How to perform drag and drop operation in Selenium with python?
We can perform drag and drop actions in Selenium with the help of Action Chains class. These classes are generally used for automating interactions like context menu click, mouse button actions, key press and mouse movements. These types of actions are mainly common in complex scenarios like drag and drop and hovering over an element on the page. The methods of the Action Chains class are utilized by advanced scripts. We can manipulate DOM with the help of Action Chains in Selenium. The action chain object implements the ActionChains in the form of a queue and then executes the perform() method. On calling the method perform(), all the actions on action chains will be performed. The method of creating an Action Chain object is listed below − First we need to import the Action Chain class and then the driver will be passed as an argument to it. First we need to import the Action Chain class and then the driver will be passed as an argument to it. Now all the operations of action chains can be done with the help of this object. Now all the operations of action chains can be done with the help of this object. Syntax for creating an object of Action Chains − from selenium import webdriver # import Action chains from selenium.webdriver import ActionChains # create webdriver object driver = webdriver.Firefox() # create action chain object action = ActionChains(driver) After creating an object of Action Chains, we can perform numerous operations one by one like a chain which is queued. drag_and_drop() - This method performs the action of holding the left mouse button on the source element. Then moves to the target element and finally releases the mouse button. drag_and_drop(args1, args2) Where, args1 is the element on which mouse down operation is done. And args2 is the element on which mouse up operation is done. #source source = driver.find_element_by_link_text("Tutorialspoint") #target target = driver.find_element_by_link_text("Selenium") #action chain object action = ActionChains(driver) # drag and drop operation action.drag_and_drop(source, target) Code Implementation for drag and drop operation. from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://jqueryui.com/droppable/") #to refresh the browser driver.refresh() # identifying the source and target elements source= driver.find_element_by_id("draggable"); target= driver.find_element_by_id("droppable"); # action chain object creation action = ActionChains(driver) # drag and drop operation and the perform action.drag_and_drop(source, target).perform() driver.close()
[ { "code": null, "e": 1288, "s": 1062, "text": "We can perform drag and drop actions in Selenium with the help of Action\nChains class. These classes are generally used for automating interactions like\ncontext menu click, mouse button actions, key press and mouse movements." }, { "code": null, "e": 1550, "s": 1288, "text": "These types of actions are mainly common in complex scenarios like drag and drop\nand hovering over an element on the page. The methods of the Action Chains class\nare utilized by advanced scripts. We can manipulate DOM with the help of Action\nChains in Selenium." }, { "code": null, "e": 1750, "s": 1550, "text": "The action chain object implements the ActionChains in the form of a queue and\nthen executes the perform() method. On calling the method perform(), all the\nactions on action chains will be performed." }, { "code": null, "e": 1814, "s": 1750, "text": "The method of creating an Action Chain object is listed below −" }, { "code": null, "e": 1918, "s": 1814, "text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it." }, { "code": null, "e": 2022, "s": 1918, "text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it." }, { "code": null, "e": 2104, "s": 2022, "text": "Now all the operations of action chains can be done with the help of this\nobject." }, { "code": null, "e": 2186, "s": 2104, "text": "Now all the operations of action chains can be done with the help of this\nobject." }, { "code": null, "e": 2235, "s": 2186, "text": "Syntax for creating an object of Action Chains −" }, { "code": null, "e": 2266, "s": 2235, "text": "from selenium import webdriver" }, { "code": null, "e": 2447, "s": 2266, "text": "# import Action chains\nfrom selenium.webdriver import ActionChains\n# create webdriver object\ndriver = webdriver.Firefox()\n# create action chain object\naction = ActionChains(driver)" }, { "code": null, "e": 2566, "s": 2447, "text": "After creating an object of Action Chains, we can perform numerous operations\none by one like a chain which is queued." }, { "code": null, "e": 2744, "s": 2566, "text": "drag_and_drop() - This method performs the action of holding the left mouse\nbutton on the source element. Then moves to the target element and finally\nreleases the mouse button." }, { "code": null, "e": 2772, "s": 2744, "text": "drag_and_drop(args1, args2)" }, { "code": null, "e": 2839, "s": 2772, "text": "Where, args1 is the element on which mouse down operation is done." }, { "code": null, "e": 2901, "s": 2839, "text": "And args2 is the element on which mouse up operation is done." }, { "code": null, "e": 3145, "s": 2901, "text": "#source\nsource = driver.find_element_by_link_text(\"Tutorialspoint\")\n#target\ntarget = driver.find_element_by_link_text(\"Selenium\")\n#action chain object\naction = ActionChains(driver)\n# drag and drop operation\naction.drag_and_drop(source, target)" }, { "code": null, "e": 3194, "s": 3145, "text": "Code Implementation for drag and drop operation." }, { "code": null, "e": 3997, "s": 3194, "text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://jqueryui.com/droppable/\")\n#to refresh the browser\ndriver.refresh()\n# identifying the source and target elements\nsource= driver.find_element_by_id(\"draggable\");\ntarget= driver.find_element_by_id(\"droppable\");\n# action chain object creation\naction = ActionChains(driver)\n# drag and drop operation and the perform\naction.drag_and_drop(source, target).perform()\ndriver.close()" } ]
Concatenate a string given number of times in C++ programming
A program to concatenate a string a given number of times will run the string concatenate method n number of times based on the value of n. The result would be string repeated a number of times. given string: “ I love Tutorials point” n = 5 I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point I love Tutorials point After seeing the output, it is clear that what the function will do. #include <iostream> #include <string> using namespace std; string repeat(string s, int n) { string s1 = s; for (int i=1; i<n;i++) s += s1; // Concatinating strings return s; } // Driver code int main() { string s = "I love tutorials point"; int n = 4; string s1 = s; for (int i=1; i<n;i++) s += s1; cout << s << endl;; return 0; } I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point
[ { "code": null, "e": 1202, "s": 1062, "text": "A program to concatenate a string a given number of times will run the string concatenate method n number of times based on the value of n." }, { "code": null, "e": 1257, "s": 1202, "text": "The result would be string repeated a number of times." }, { "code": null, "e": 1303, "s": 1257, "text": "given string: “ I love Tutorials point”\nn = 5" }, { "code": null, "e": 1415, "s": 1303, "text": "I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point\nI love Tutorials point" }, { "code": null, "e": 1484, "s": 1415, "text": "After seeing the output, it is clear that what the function will do." }, { "code": null, "e": 1851, "s": 1484, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nstring repeat(string s, int n) {\n string s1 = s;\n for (int i=1; i<n;i++)\n s += s1; // Concatinating strings\n return s;\n}\n// Driver code\nint main() {\n string s = \"I love tutorials point\";\n int n = 4;\n string s1 = s;\n for (int i=1; i<n;i++)\n s += s1;\n cout << s << endl;;\n return 0;\n}" }, { "code": null, "e": 1940, "s": 1851, "text": "I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point" } ]
Java Program to create a TreeSet with custom Comparator
To create a TreeSet with custom comparator, let us first create a an Integer array and set it to TreeSet Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder()); Above, we have used the Comparator with reverseOrder(), which returns a comparator that imposes the reverse of the natural ordering. import java.util.Collections; import java.util.Set; import java.util.TreeSet; public class Demo { public static void main(String args[]) throws Exception { Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder()); for (int i = 0, n = arr.length; i < n; i++) { set.add(arr[i]); } System.out.println("TreeSet = "+set); System.out.println(((TreeSet<Integer>) set).comparator()); } } TreeSet = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] java.util.Collections$ReverseComparator@6276ae34
[ { "code": null, "e": 1167, "s": 1062, "text": "To create a TreeSet with custom comparator, let us first create a an Integer array and set it to TreeSet" }, { "code": null, "e": 1297, "s": 1167, "text": "Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };\nSet<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());" }, { "code": null, "e": 1430, "s": 1297, "text": "Above, we have used the Comparator with reverseOrder(), which returns a comparator that imposes the\nreverse of the natural ordering." }, { "code": null, "e": 1933, "s": 1430, "text": "import java.util.Collections;\nimport java.util.Set;\nimport java.util.TreeSet;\npublic class Demo {\n public static void main(String args[]) throws Exception {\n Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };\n Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());\n for (int i = 0, n = arr.length; i < n; i++) {\n set.add(arr[i]);\n }\n System.out.println(\"TreeSet = \"+set);\n System.out.println(((TreeSet<Integer>) set).comparator());\n }\n}" }, { "code": null, "e": 2034, "s": 1933, "text": "TreeSet = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]\njava.util.Collections$ReverseComparator@6276ae34" } ]
Convert list of tuples into list in Python
We may come across a lists whose elements are tuples. But for further data processing we may need to convert the tuples to the normal elements of a list. In this article we will see the approaches to achieve this. In this approach we design nested for loops to iterate through each tuple and produce the final list of elements. Live Demo listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] # Given list print("Given list : \n", listA) res = [item for t in listA for item in t] # Result print("Final list: \n",res) Running the above code gives us the following result − Given list : [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] Final list: ['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm'] We can also use the itertools.chain method along with * operator which will fetch each element in the list of tuples and then combine them as a series of elements for the list. Live Demo import itertools listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] # Given list print("Given list : \n", listA) res = list(itertools.chain(*listA)) # Result print("Final list: \n",res) Running the above code gives us the following result − Given list : [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] Final list: ['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm'] The reduce function in used to apply the concat function to each of the list elements which finally produces a list of all elements from the original list. Live Demo import operator from functools import reduce listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] # Given list print("Given list : \n", listA) res = (list(reduce(operator.concat, listA))) # Result print("Final list: \n",res) Running the above code gives us the following result − Given list : [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] Final list: ['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']
[ { "code": null, "e": 1276, "s": 1062, "text": "We may come across a lists whose elements are tuples. But for further data processing we may need to convert the tuples to the normal elements of a list. In this article we will see the approaches to achieve this." }, { "code": null, "e": 1390, "s": 1276, "text": "In this approach we design nested for loops to iterate through each tuple and produce the final list of elements." }, { "code": null, "e": 1401, "s": 1390, "text": " Live Demo" }, { "code": null, "e": 1576, "s": 1401, "text": "listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]\n# Given list\nprint(\"Given list : \\n\", listA)\nres = [item for t in listA for item in t]\n# Result\nprint(\"Final list: \\n\",res)" }, { "code": null, "e": 1631, "s": 1576, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1736, "s": 1631, "text": "Given list :\n[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]\nFinal list:\n['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']" }, { "code": null, "e": 1913, "s": 1736, "text": "We can also use the itertools.chain method along with * operator which will fetch each element in the list of tuples and then combine them as a series of elements for the list." }, { "code": null, "e": 1924, "s": 1913, "text": " Live Demo" }, { "code": null, "e": 2110, "s": 1924, "text": "import itertools\nlistA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]\n# Given list\nprint(\"Given list : \\n\", listA)\nres = list(itertools.chain(*listA))\n# Result\nprint(\"Final list: \\n\",res)" }, { "code": null, "e": 2165, "s": 2110, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2270, "s": 2165, "text": "Given list :\n[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]\nFinal list:\n['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']" }, { "code": null, "e": 2426, "s": 2270, "text": "The reduce function in used to apply the concat function to each of the list elements which finally produces a list of all elements from the original list." }, { "code": null, "e": 2437, "s": 2426, "text": " Live Demo" }, { "code": null, "e": 2660, "s": 2437, "text": "import operator\nfrom functools import reduce\nlistA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]\n# Given list\nprint(\"Given list : \\n\", listA)\nres = (list(reduce(operator.concat, listA)))\n# Result\nprint(\"Final list: \\n\",res)" }, { "code": null, "e": 2715, "s": 2660, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2820, "s": 2715, "text": "Given list :\n[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]\nFinal list:\n['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']" } ]
How to add Icon to JButton in Java?
To add icon to a button, use the Icon class, which will allow you to add an image to the button. We are creating a button wherein we are adding an icon with Icon class − Icon icon = new ImageIcon("E:\\editicon.PNG"); JButton button7 = new JButton(icon); Above, we have set icon for button 7. The following is an example to add icon to JButton− package my; import javax.swing.Box; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; public class SwingDemo { public static void main(String[] args) { JButton button1 = new JButton("One"); JButton button2 = new JButton("Two"); JButton button3 = new JButton("Three"); JButton button4 = new JButton("Four"); JButton button5 = new JButton("Five"); JButton button6 = new JButton("Six"); Icon icon = new ImageIcon("E:\\editicon.PNG"); JButton button7 = new JButton(icon); Box box = Box.createVerticalBox(); box.add(button1); box.add(button2); box.add(button3); box.add(button4); box.add(button5); box.add(button6); box.add(button7); JFrame frame = new JFrame(); frame.add(box); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationByPlatform(true); frame.setSize(500, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1159, "s": 1062, "text": "To add icon to a button, use the Icon class, which will allow you to add an image to the button." }, { "code": null, "e": 1232, "s": 1159, "text": "We are creating a button wherein we are adding an icon with Icon class −" }, { "code": null, "e": 1316, "s": 1232, "text": "Icon icon = new ImageIcon(\"E:\\\\editicon.PNG\");\nJButton button7 = new JButton(icon);" }, { "code": null, "e": 1354, "s": 1316, "text": "Above, we have set icon for button 7." }, { "code": null, "e": 1406, "s": 1354, "text": "The following is an example to add icon to JButton−" }, { "code": null, "e": 2420, "s": 1406, "text": "package my;\nimport javax.swing.Box;\nimport javax.swing.Icon;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] args) {\n JButton button1 = new JButton(\"One\");\n JButton button2 = new JButton(\"Two\");\n JButton button3 = new JButton(\"Three\");\n JButton button4 = new JButton(\"Four\");\n JButton button5 = new JButton(\"Five\");\n JButton button6 = new JButton(\"Six\");\n Icon icon = new ImageIcon(\"E:\\\\editicon.PNG\");\n JButton button7 = new JButton(icon);\n Box box = Box.createVerticalBox();\n box.add(button1);\n box.add(button2);\n box.add(button3);\n box.add(button4);\n box.add(button5);\n box.add(button6);\n box.add(button7);\n JFrame frame = new JFrame();\n frame.add(box);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationByPlatform(true);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}" } ]
HTML - <title> Tag
The HTML <title> tag is used for indicating the title of the HTML document. The body title is placed between the <head> and the </head> tags. HTML document title is visible via browser’s title bar. <!DOCTYPE html> <html> <head> <title>Title comes here</title> </head> <body> <p>title tag is used for indicating the title of the HTML document. HTML document title is visible via browser’s title bar.</p> </body> </html> This will produce the following result − title tag is used for indicating the title of the HTML document. HTML document title is visible via browser’s title bar. This tag supports all the global attributes described in − HTML Attribute Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2374, "text": "The HTML <title> tag is used for indicating the title of the HTML document. The body title is placed between the <head> and the </head> tags." }, { "code": null, "e": 2572, "s": 2516, "text": "HTML document title is visible via browser’s title bar." }, { "code": null, "e": 2829, "s": 2572, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Title comes here</title>\n </head>\n\n <body>\n <p>title tag is used for indicating the title of the HTML document. HTML document\n title is visible via browser’s title bar.</p>\n </body>\n\n</html>" }, { "code": null, "e": 2870, "s": 2829, "text": "This will produce the following result −" }, { "code": null, "e": 2991, "s": 2870, "text": "title tag is used for indicating the title of the HTML document. HTML document title is visible via browser’s title bar." }, { "code": null, "e": 3075, "s": 2991, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 3108, "s": 3075, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3122, "s": 3108, "text": " Anadi Sharma" }, { "code": null, "e": 3157, "s": 3122, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3171, "s": 3157, "text": " Anadi Sharma" }, { "code": null, "e": 3206, "s": 3171, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3223, "s": 3206, "text": " Frahaan Hussain" }, { "code": null, "e": 3258, "s": 3223, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3289, "s": 3258, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3322, "s": 3289, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3353, "s": 3322, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3388, "s": 3353, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3419, "s": 3388, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3426, "s": 3419, "text": " Print" }, { "code": null, "e": 3437, "s": 3426, "text": " Add Notes" } ]
Pairs of Amicable Numbers - GeeksforGeeks
25 Feb, 2022 Given an array of integers, print the number of pairs in the array that form an amicable pair. Two numbers are amicable if the first is equal to the sum of divisors of the second, and if the second number is equal to the sum of divisors of the first.Examples : Input : arr[] = {220, 284, 1184, 1210, 2, 5} Output : 2 Explanation : (220, 284) and (1184, 1210) form amicable pair Input : arr[] = {2620, 2924, 5020, 5564, 6232, 6368} Output : 3 Explanation : (2620, 2924), (5020, 5564) and (6232, 6368) forms amicable pair A simple solution is to traverse each pair and check if they form an amicable pair, if they do we increment the count. C++ Java Python3 C# PHP Javascript // A simple C++ program to count// amicable pairs in an array.#include <bits/stdc++.h>using namespace std; // Calculate the sum// of proper divisorsint sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablebool isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints pair// of amicable pairs present// in the input arrayint countPairs(int arr[], int n){ int count = 0; // Iterate through each // pair, and find if it // an amicable pair for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count;} // Driver codeint main(){ int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); cout << countPairs(arr1, n1) << endl; int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); cout << countPairs(arr2, n2); return 0;} // A simple Java program to count// amicable pairs in an array.import java.io.*; class GFG{ // Calculate the sum // of proper divisors static int sumOfDiv(int x) { // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum; } // Check if pair is amicable static boolean isAmicable(int a, int b) { return (sumOfDiv(a) == b && sumOfDiv(b) == a); } // This function prints pair // of amicable pairs present // in the input array static int countPairs(int arr[], int n) { int count = 0; // Iterate through each pair, // and find if it an amicable pair for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count; } // Driver code public static void main(String args[]) { int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = arr1.length; System.out.println(countPairs(arr1, n1)); int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = arr2.length; System.out.println(countPairs(arr2, n2)); }} // This code is contributed by Anshika Goyal. # Python3 program to count# amicable pairs in an array # Calculate the sum# of proper divisorsdef sumOfDiv(x): sum = 1 for i in range(2, x): if x % i == 0: sum += i return sum # Check if pair is amicabledef isAmicable(a, b): if sumOfDiv(a) == b and sumOfDiv(b) == a: return True else: return False # This function prints pair# of amicable pairs present# in the input arraydef countPairs(arr, n): count = 0 for i in range(0, n): for j in range(i + 1, n): if isAmicable(arr[i], arr[j]): count = count + 1 return count # Driver Codearr1 = [220, 284, 1184, 1210, 2, 5]n1 = len(arr1)print(countPairs(arr1, n1)) arr2 = [2620, 2924, 5020, 5564, 6232, 6368]n2 = len(arr2)print(countPairs(arr2, n2)) # This code is contributed# by Smitha Dinesh Semwal // A simple C# program to count// amicable pairs in an array.using System; class GFG{ // Calculate the sum // of proper divisors static int sumOfDiv(int x) { // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.Sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum; } // Check if pair is amicable static bool isAmicable(int a, int b) { return (sumOfDiv(a) == b && sumOfDiv(b) == a); } // This function prints pair // of amicable pairs present // in the input array static int countPairs(int []arr, int n) { int count = 0; // Iterate through each pair, // and find if it an amicable pair for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count; } // Driver code public static void Main() { int []arr1 = {220, 284, 1184, 1210, 2, 5}; int n1 = arr1.Length; Console.WriteLine(countPairs(arr1, n1)); int []arr2 = {2620, 2924, 5020, 5564, 6232, 6368}; int n2 = arr2.Length; Console.WriteLine(countPairs(arr2, n2)); }} // This code is contributed by vt_m. <?php// A simple PHP program to count// amicable pairs in an array. // Calculate the sum// of proper divisorsfunction sumOfDiv( $x){ // 1 is a proper divisor $sum = 1; for ( $i = 2; $i <= sqrt($x); $i++) { if ($x % $i == 0) { $sum += $i; // To handle perfect squares if ($x / $i != $i) $sum += $x / $i; } } return $sum;} // Check if pair is amicablefunction isAmicable( $a, $b){ return (sumOfDiv($a) == $b and sumOfDiv($b) == $a);} // This function prints pair// of amicable pairs present// in the input arrayfunction countPairs( $arr, $n){ $count = 0; // Iterate through each pair, // and find if it an amicable pair for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) if (isAmicable($arr[$i], $arr[$j])) $count++; return $count;} // Driver code$arr1 = array( 220, 284, 1184, 1210, 2, 5 );$n1 = count($arr1);echo countPairs($arr1, $n1),"\n"; $arr2 = array( 2620, 2924, 5020, 5564, 6232, 6368 );$n2 = count($arr2);echo countPairs($arr2, $n2); // This code is contributed by anuj_67.?> <script> // A simple Javascript program to count // amicable pairs in an array. // Calculate the sum // of proper divisors function sumOfDiv(x) { // 1 is a proper divisor let sum = 1; for (let i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (parseInt(x / i, 10) != i) sum += parseInt(x / i, 10); } } return sum; } // Check if pair is amicable function isAmicable(a, b) { return (sumOfDiv(a) == b && sumOfDiv(b) == a); } // This function prints pair // of amicable pairs present // in the input array function countPairs(arr, n) { let count = 0; // Iterate through each pair, // and find if it an amicable pair for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count; } let arr1 = [220, 284, 1184, 1210, 2, 5]; let n1 = arr1.length; document.write(countPairs(arr1, n1) + "</br>"); let arr2 = [2620, 2924, 5020, 5564, 6232, 6368]; let n2 = arr2.length; document.write(countPairs(arr2, n2)); </script> Output: 2 3 An efficient solution is to keep the numbers stored in a map and for every number, we find the sum of its proper divisor and check if that’s also present in the array. If it is present, we can check if they form an amicable pair or not.Thus, the complexity would be considerably reduced. Below is the C++ program for the same. C++ Java Python3 C# Javascript // Efficient C++ program to count// Amicable pairs in an array.#include <bits/stdc++.h>using namespace std; // Calculate the sum// of proper divisorsint sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablebool isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arrayint countPairs(int arr[], int n){ // Map to store the numbers unordered_set<int> s; int count = 0; for (int i = 0; i < n; i++) s.insert(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (int i = 0; i < n; i++) { if (s.find(sumOfDiv(arr[i])) != s.end()) { // It's sum of proper divisors int sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return count / 2;} // Driver codeint main(){ int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); cout << countPairs(arr1, n1) << endl; int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); cout << countPairs(arr2, n2) << endl; return 0;} // Efficient Java program to count// Amicable pairs in an array.import java.util.*; class GFG{ // Calculate the sum// of proper divisorsstatic int sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablestatic boolean isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arraystatic int countPairs(int arr[], int n){ // Map to store the numbers HashSet<Integer> s = new HashSet<Integer>(); int count = 0; for (int i = 0; i < n; i++) s.add(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (int i = 0; i < n; i++) { if (s.contains(sumOfDiv(arr[i]))) { // It's sum of proper divisors int sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return count / 2;} // Driver codepublic static void main(String[] args){ int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = arr1.length; System.out.println(countPairs(arr1, n1)); int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = arr2.length; System.out.println(countPairs(arr2, n2));}} // This code is contributed by PrinciRaj1992 # Efficient Python3 program to count# Amicable pairs in an array.import math # Calculating the sum# of proper divisorsdef sumOfDiv(x): # 1 is a proper divisor sum = 1; for i in range(2,int(math.sqrt(x))): if x % i==0: sum += i # To handle perfect squares if i != x/i: sum += x/i return int(sum); # check if pair is amicabledef isAmicable(a, b): return (sumOfDiv(a) == b and sumOfDiv(b) == a) # This function prints count# of amicable pairs present# in the input arraydef countPairs(arr,n): # Map to store the numbers s = set() count = 0 for i in range(n): s.add(arr[i]) # Iterate through each number, # and find the sum of proper # divisors and check if it's # also present in the array for i in range(n): if sumOfDiv(arr[i]) in s: # It's sum of proper divisors sum = sumOfDiv(arr[i]) if isAmicable(arr[i], sum): count += 1 # As the pairs are counted # twice, thus divide by 2 return int(count/2); # Driver Codearr1 = [220, 284, 1184, 1210, 2, 5]n1 = len(arr1)print(countPairs(arr1, n1)) arr2 = [2620, 2924, 5020, 5564, 6232, 6368]n2 = len(arr2)print(countPairs(arr2, n2)) # This code is contributed# by Naveen Babbar // Efficient C# program to count// Amicable pairs in an array.using System;using System.Collections.Generic; class GFG{ // Calculate the sum// of proper divisorsstatic int sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.Sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablestatic Boolean isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arraystatic int countPairs(int []arr, int n){ // Map to store the numbers HashSet<int> s = new HashSet<int>(); int count = 0; for (int i = 0; i < n; i++) s.Add(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (int i = 0; i < n; i++) { if (s.Contains(sumOfDiv(arr[i]))) { // It's sum of proper divisors int sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return count / 2;} // Driver codepublic static void Main(String[] args){ int []arr1 = { 220, 284, 1184, 1210, 2, 5 }; int n1 = arr1.Length; Console.WriteLine(countPairs(arr1, n1)); int []arr2 = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = arr2.Length; Console.WriteLine(countPairs(arr2, n2));}} // This code is contributed by Princi Singh <script> // JavaScript program to count// Amicable pairs in an array. // Calculate the sum// of proper divisorsfunction sumOfDiv(x){ // 1 is a proper divisor let sum = 1; for (let i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablefunction isAmicable(a, b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arrayfunction countPairs(arr, n){ // Map to store the numbers let s = new Set(); let count = 0; for (let i = 0; i < n; i++) s.add(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (let i = 0; i < n; i++) { if (s.has(sumOfDiv(arr[i]))) { // It's sum of proper divisors let sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return Math.floor(count / 2);} // Driver code let arr1 = [ 220, 284, 1184, 1210, 2, 5 ]; let n1 = arr1.length; document.write(countPairs(arr1, n1) + "<br/>"); let arr2 = [ 2620, 2924, 5020, 5564, 6232, 6368 ]; let n2 = arr2.length; document.write(countPairs(arr2, n2) + "<br/>"); </script> Output: 2 3 This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m princiraj1992 princi singh nbabbar17 mukesh07 avijitmondal1998 simranarora5sos arorakashish0911 Arrays Hash Arrays Hash 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 Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 24431, "s": 24403, "text": "\n25 Feb, 2022" }, { "code": null, "e": 24694, "s": 24431, "text": "Given an array of integers, print the number of pairs in the array that form an amicable pair. Two numbers are amicable if the first is equal to the sum of divisors of the second, and if the second number is equal to the sum of divisors of the first.Examples : " }, { "code": null, "e": 24985, "s": 24694, "text": "Input : arr[] = {220, 284, 1184, 1210, 2, 5}\nOutput : 2\nExplanation : (220, 284) and (1184, 1210) \n form amicable pair\n\nInput : arr[] = {2620, 2924, 5020, 5564, 6232, 6368}\nOutput : 3\nExplanation : (2620, 2924), (5020, 5564) and (6232, 6368)\n forms amicable pair" }, { "code": null, "e": 25108, "s": 24987, "text": "A simple solution is to traverse each pair and check if they form an amicable pair, if they do we increment the count. " }, { "code": null, "e": 25112, "s": 25108, "text": "C++" }, { "code": null, "e": 25117, "s": 25112, "text": "Java" }, { "code": null, "e": 25125, "s": 25117, "text": "Python3" }, { "code": null, "e": 25128, "s": 25125, "text": "C#" }, { "code": null, "e": 25132, "s": 25128, "text": "PHP" }, { "code": null, "e": 25143, "s": 25132, "text": "Javascript" }, { "code": "// A simple C++ program to count// amicable pairs in an array.#include <bits/stdc++.h>using namespace std; // Calculate the sum// of proper divisorsint sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablebool isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints pair// of amicable pairs present// in the input arrayint countPairs(int arr[], int n){ int count = 0; // Iterate through each // pair, and find if it // an amicable pair for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count;} // Driver codeint main(){ int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); cout << countPairs(arr1, n1) << endl; int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); cout << countPairs(arr2, n2); return 0;}", "e": 26414, "s": 25143, "text": null }, { "code": "// A simple Java program to count// amicable pairs in an array.import java.io.*; class GFG{ // Calculate the sum // of proper divisors static int sumOfDiv(int x) { // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum; } // Check if pair is amicable static boolean isAmicable(int a, int b) { return (sumOfDiv(a) == b && sumOfDiv(b) == a); } // This function prints pair // of amicable pairs present // in the input array static int countPairs(int arr[], int n) { int count = 0; // Iterate through each pair, // and find if it an amicable pair for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count; } // Driver code public static void main(String args[]) { int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = arr1.length; System.out.println(countPairs(arr1, n1)); int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = arr2.length; System.out.println(countPairs(arr2, n2)); }} // This code is contributed by Anshika Goyal.", "e": 27931, "s": 26414, "text": null }, { "code": "# Python3 program to count# amicable pairs in an array # Calculate the sum# of proper divisorsdef sumOfDiv(x): sum = 1 for i in range(2, x): if x % i == 0: sum += i return sum # Check if pair is amicabledef isAmicable(a, b): if sumOfDiv(a) == b and sumOfDiv(b) == a: return True else: return False # This function prints pair# of amicable pairs present# in the input arraydef countPairs(arr, n): count = 0 for i in range(0, n): for j in range(i + 1, n): if isAmicable(arr[i], arr[j]): count = count + 1 return count # Driver Codearr1 = [220, 284, 1184, 1210, 2, 5]n1 = len(arr1)print(countPairs(arr1, n1)) arr2 = [2620, 2924, 5020, 5564, 6232, 6368]n2 = len(arr2)print(countPairs(arr2, n2)) # This code is contributed# by Smitha Dinesh Semwal", "e": 28777, "s": 27931, "text": null }, { "code": "// A simple C# program to count// amicable pairs in an array.using System; class GFG{ // Calculate the sum // of proper divisors static int sumOfDiv(int x) { // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.Sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum; } // Check if pair is amicable static bool isAmicable(int a, int b) { return (sumOfDiv(a) == b && sumOfDiv(b) == a); } // This function prints pair // of amicable pairs present // in the input array static int countPairs(int []arr, int n) { int count = 0; // Iterate through each pair, // and find if it an amicable pair for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count; } // Driver code public static void Main() { int []arr1 = {220, 284, 1184, 1210, 2, 5}; int n1 = arr1.Length; Console.WriteLine(countPairs(arr1, n1)); int []arr2 = {2620, 2924, 5020, 5564, 6232, 6368}; int n2 = arr2.Length; Console.WriteLine(countPairs(arr2, n2)); }} // This code is contributed by vt_m.", "e": 30291, "s": 28777, "text": null }, { "code": "<?php// A simple PHP program to count// amicable pairs in an array. // Calculate the sum// of proper divisorsfunction sumOfDiv( $x){ // 1 is a proper divisor $sum = 1; for ( $i = 2; $i <= sqrt($x); $i++) { if ($x % $i == 0) { $sum += $i; // To handle perfect squares if ($x / $i != $i) $sum += $x / $i; } } return $sum;} // Check if pair is amicablefunction isAmicable( $a, $b){ return (sumOfDiv($a) == $b and sumOfDiv($b) == $a);} // This function prints pair// of amicable pairs present// in the input arrayfunction countPairs( $arr, $n){ $count = 0; // Iterate through each pair, // and find if it an amicable pair for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) if (isAmicable($arr[$i], $arr[$j])) $count++; return $count;} // Driver code$arr1 = array( 220, 284, 1184, 1210, 2, 5 );$n1 = count($arr1);echo countPairs($arr1, $n1),\"\\n\"; $arr2 = array( 2620, 2924, 5020, 5564, 6232, 6368 );$n2 = count($arr2);echo countPairs($arr2, $n2); // This code is contributed by anuj_67.?>", "e": 31467, "s": 30291, "text": null }, { "code": "<script> // A simple Javascript program to count // amicable pairs in an array. // Calculate the sum // of proper divisors function sumOfDiv(x) { // 1 is a proper divisor let sum = 1; for (let i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (parseInt(x / i, 10) != i) sum += parseInt(x / i, 10); } } return sum; } // Check if pair is amicable function isAmicable(a, b) { return (sumOfDiv(a) == b && sumOfDiv(b) == a); } // This function prints pair // of amicable pairs present // in the input array function countPairs(arr, n) { let count = 0; // Iterate through each pair, // and find if it an amicable pair for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (isAmicable(arr[i], arr[j])) count++; return count; } let arr1 = [220, 284, 1184, 1210, 2, 5]; let n1 = arr1.length; document.write(countPairs(arr1, n1) + \"</br>\"); let arr2 = [2620, 2924, 5020, 5564, 6232, 6368]; let n2 = arr2.length; document.write(countPairs(arr2, n2)); </script>", "e": 32844, "s": 31467, "text": null }, { "code": null, "e": 32854, "s": 32844, "text": "Output: " }, { "code": null, "e": 32858, "s": 32854, "text": "2\n3" }, { "code": null, "e": 33187, "s": 32858, "text": "An efficient solution is to keep the numbers stored in a map and for every number, we find the sum of its proper divisor and check if that’s also present in the array. If it is present, we can check if they form an amicable pair or not.Thus, the complexity would be considerably reduced. Below is the C++ program for the same. " }, { "code": null, "e": 33191, "s": 33187, "text": "C++" }, { "code": null, "e": 33196, "s": 33191, "text": "Java" }, { "code": null, "e": 33204, "s": 33196, "text": "Python3" }, { "code": null, "e": 33207, "s": 33204, "text": "C#" }, { "code": null, "e": 33218, "s": 33207, "text": "Javascript" }, { "code": "// Efficient C++ program to count// Amicable pairs in an array.#include <bits/stdc++.h>using namespace std; // Calculate the sum// of proper divisorsint sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablebool isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arrayint countPairs(int arr[], int n){ // Map to store the numbers unordered_set<int> s; int count = 0; for (int i = 0; i < n; i++) s.insert(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (int i = 0; i < n; i++) { if (s.find(sumOfDiv(arr[i])) != s.end()) { // It's sum of proper divisors int sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return count / 2;} // Driver codeint main(){ int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); cout << countPairs(arr1, n1) << endl; int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); cout << countPairs(arr2, n2) << endl; return 0;}", "e": 34852, "s": 33218, "text": null }, { "code": "// Efficient Java program to count// Amicable pairs in an array.import java.util.*; class GFG{ // Calculate the sum// of proper divisorsstatic int sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablestatic boolean isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arraystatic int countPairs(int arr[], int n){ // Map to store the numbers HashSet<Integer> s = new HashSet<Integer>(); int count = 0; for (int i = 0; i < n; i++) s.add(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (int i = 0; i < n; i++) { if (s.contains(sumOfDiv(arr[i]))) { // It's sum of proper divisors int sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return count / 2;} // Driver codepublic static void main(String[] args){ int arr1[] = { 220, 284, 1184, 1210, 2, 5 }; int n1 = arr1.length; System.out.println(countPairs(arr1, n1)); int arr2[] = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = arr2.length; System.out.println(countPairs(arr2, n2));}} // This code is contributed by PrinciRaj1992", "e": 36537, "s": 34852, "text": null }, { "code": "# Efficient Python3 program to count# Amicable pairs in an array.import math # Calculating the sum# of proper divisorsdef sumOfDiv(x): # 1 is a proper divisor sum = 1; for i in range(2,int(math.sqrt(x))): if x % i==0: sum += i # To handle perfect squares if i != x/i: sum += x/i return int(sum); # check if pair is amicabledef isAmicable(a, b): return (sumOfDiv(a) == b and sumOfDiv(b) == a) # This function prints count# of amicable pairs present# in the input arraydef countPairs(arr,n): # Map to store the numbers s = set() count = 0 for i in range(n): s.add(arr[i]) # Iterate through each number, # and find the sum of proper # divisors and check if it's # also present in the array for i in range(n): if sumOfDiv(arr[i]) in s: # It's sum of proper divisors sum = sumOfDiv(arr[i]) if isAmicable(arr[i], sum): count += 1 # As the pairs are counted # twice, thus divide by 2 return int(count/2); # Driver Codearr1 = [220, 284, 1184, 1210, 2, 5]n1 = len(arr1)print(countPairs(arr1, n1)) arr2 = [2620, 2924, 5020, 5564, 6232, 6368]n2 = len(arr2)print(countPairs(arr2, n2)) # This code is contributed# by Naveen Babbar", "e": 37909, "s": 36537, "text": null }, { "code": "// Efficient C# program to count// Amicable pairs in an array.using System;using System.Collections.Generic; class GFG{ // Calculate the sum// of proper divisorsstatic int sumOfDiv(int x){ // 1 is a proper divisor int sum = 1; for (int i = 2; i <= Math.Sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablestatic Boolean isAmicable(int a, int b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arraystatic int countPairs(int []arr, int n){ // Map to store the numbers HashSet<int> s = new HashSet<int>(); int count = 0; for (int i = 0; i < n; i++) s.Add(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (int i = 0; i < n; i++) { if (s.Contains(sumOfDiv(arr[i]))) { // It's sum of proper divisors int sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return count / 2;} // Driver codepublic static void Main(String[] args){ int []arr1 = { 220, 284, 1184, 1210, 2, 5 }; int n1 = arr1.Length; Console.WriteLine(countPairs(arr1, n1)); int []arr2 = { 2620, 2924, 5020, 5564, 6232, 6368 }; int n2 = arr2.Length; Console.WriteLine(countPairs(arr2, n2));}} // This code is contributed by Princi Singh", "e": 39612, "s": 37909, "text": null }, { "code": "<script> // JavaScript program to count// Amicable pairs in an array. // Calculate the sum// of proper divisorsfunction sumOfDiv(x){ // 1 is a proper divisor let sum = 1; for (let i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) { sum += i; // To handle perfect squares if (x / i != i) sum += x / i; } } return sum;} // Check if pair is amicablefunction isAmicable(a, b){ return (sumOfDiv(a) == b && sumOfDiv(b) == a);} // This function prints count// of amicable pairs present// in the input arrayfunction countPairs(arr, n){ // Map to store the numbers let s = new Set(); let count = 0; for (let i = 0; i < n; i++) s.add(arr[i]); // Iterate through each number, // and find the sum of proper // divisors and check if it's // also present in the array for (let i = 0; i < n; i++) { if (s.has(sumOfDiv(arr[i]))) { // It's sum of proper divisors let sum = sumOfDiv(arr[i]); if (isAmicable(arr[i], sum)) count++; } } // As the pairs are counted // twice, thus divide by 2 return Math.floor(count / 2);} // Driver code let arr1 = [ 220, 284, 1184, 1210, 2, 5 ]; let n1 = arr1.length; document.write(countPairs(arr1, n1) + \"<br/>\"); let arr2 = [ 2620, 2924, 5020, 5564, 6232, 6368 ]; let n2 = arr2.length; document.write(countPairs(arr2, n2) + \"<br/>\"); </script>", "e": 41183, "s": 39612, "text": null }, { "code": null, "e": 41193, "s": 41183, "text": "Output: " }, { "code": null, "e": 41197, "s": 41193, "text": "2\n3" }, { "code": null, "e": 41619, "s": 41197, "text": "This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41624, "s": 41619, "text": "vt_m" }, { "code": null, "e": 41638, "s": 41624, "text": "princiraj1992" }, { "code": null, "e": 41651, "s": 41638, "text": "princi singh" }, { "code": null, "e": 41661, "s": 41651, "text": "nbabbar17" }, { "code": null, "e": 41670, "s": 41661, "text": "mukesh07" }, { "code": null, "e": 41687, "s": 41670, "text": "avijitmondal1998" }, { "code": null, "e": 41703, "s": 41687, "text": "simranarora5sos" }, { "code": null, "e": 41720, "s": 41703, "text": "arorakashish0911" }, { "code": null, "e": 41727, "s": 41720, "text": "Arrays" }, { "code": null, "e": 41732, "s": 41727, "text": "Hash" }, { "code": null, "e": 41739, "s": 41732, "text": "Arrays" }, { "code": null, "e": 41744, "s": 41739, "text": "Hash" }, { "code": null, "e": 41842, "s": 41744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41851, "s": 41842, "text": "Comments" }, { "code": null, "e": 41864, "s": 41851, "text": "Old Comments" }, { "code": null, "e": 41885, "s": 41864, "text": "Next Greater Element" }, { "code": null, "e": 41910, "s": 41885, "text": "Window Sliding Technique" }, { "code": null, "e": 41937, "s": 41910, "text": "Count pairs with given sum" }, { "code": null, "e": 41986, "s": 41937, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 42024, "s": 41986, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 42060, "s": 42024, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 42091, "s": 42060, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 42118, "s": 42091, "text": "Count pairs with given sum" }, { "code": null, "e": 42152, "s": 42118, "text": "Hashing | Set 3 (Open Addressing)" } ]
Central binomial coefficient - GeeksforGeeks
28 Jun, 2021 Given an integer N, the task is to find the Central binomial coefficient. The first few Central binomial coefficients for N = 0, 1, 2, 3... are 1, 2, 6, 20, 70, 252, 924, 3432..... Examples: Input: N = 3 Output: 20 Explanation: Central Binomial Coefficient = = = = 20Input: N = 2 Output: 6 Approach: The central binomial coefficient is a binomial coefficient of the form . The Binomial Coefficient can be computed using this approach for a given value N using Dynamic Programming.For Example: Central binomial coefficient of N = 3 is given by: = = = 20 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// Nth Central Binomial Coefficient #include<bits/stdc++.h>using namespace std; // Function to find the value of// Nth Central Binomial Coefficientint binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codeint main(){ int n = 3; int k = n; n = 2*n; cout << binomialCoeff(n, k);} // Java implementation to find the// Nth Central Binomial Coefficientclass GFG{ // Function to find the value of// Nth Central Binomial Coefficientstatic int binomialCoeff(int n, int k){ int[][] C = new int[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for(i = 0; i <= n; i++) { for(j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codepublic static void main(String[] args){ int n = 3; int k = n; n = 2 * n; System.out.println(binomialCoeff(n, k));}} // This code is contributed by Ritik Bansal # C# implementation to find the# Nth Central Binomial Coefficient # Function to find the value of# Nth Central Binomial Coefficientdef binomialCoeff(n, k): C = [[0 for j in range(k + 1)] for i in range(n + 1)] i = 0 j = 0 # Calculate value of Binomial # Coefficient in bottom up manner for i in range(n + 1): for j in range(min(i, k) + 1): # Base Cases if j == 0 or j == i: C[i][j] = 1 # Calculate value # using previously # stored values else: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) return C[n][k] # Driver codeif __name__=='__main__': n = 3 k = n n = 2 * n print(binomialCoeff(n, k)) # This code is contributed by rutvik_56 // C# implementation to find the// Nth Central Binomial Coefficientusing System;class GFG{ // Function to find the value of// Nth Central Binomial Coefficientstatic int binomialCoeff(int n, int k){ int [,]C = new int[n + 1, k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for(i = 0; i <= n; i++) { for(j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value // using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k];} // Driver Codepublic static void Main(){ int n = 3; int k = n; n = 2 * n; Console.Write(binomialCoeff(n, k));}} // This code is contributed by Code_Mech <script> // Javascript implementation to find the// Nth Central Binomial Coefficient // Function to find the value of// Nth Central Binomial Coefficientfunction binomialCoeff(n, k){ var C = Array.from(Array(n+1),()=> Array(k+1)); var i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codevar n = 3;var k = n;n = 2*n;document.write( binomialCoeff(n, k)); </script> 20 Time Complexity: O(N * K)Auxiliary Space: O(N * K) bansal_rtk_ Code_Mech nidhi_biet rutvik_56 itsok subhammahato348 binomial coefficient series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) Generate all permutation of a set in Python How to check if a given point lies inside or outside a polygon? Merge two sorted arrays with O(1) extra space Singular Value Decomposition (SVD) Program to multiply two matrices
[ { "code": null, "e": 26047, "s": 26019, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26193, "s": 26047, "text": "Given an integer N, the task is to find the Central binomial coefficient. The first few Central binomial coefficients for N = 0, 1, 2, 3... are " }, { "code": null, "e": 26230, "s": 26193, "text": "1, 2, 6, 20, 70, 252, 924, 3432....." }, { "code": null, "e": 26242, "s": 26230, "text": "Examples: " }, { "code": null, "e": 26343, "s": 26242, "text": "Input: N = 3 Output: 20 Explanation: Central Binomial Coefficient = = = = 20Input: N = 2 Output: 6 " }, { "code": null, "e": 26550, "s": 26345, "text": "Approach: The central binomial coefficient is a binomial coefficient of the form . The Binomial Coefficient can be computed using this approach for a given value N using Dynamic Programming.For Example: " }, { "code": null, "e": 26612, "s": 26550, "text": "Central binomial coefficient of N = 3 is given by: = = = 20 " }, { "code": null, "e": 26664, "s": 26612, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26668, "s": 26664, "text": "C++" }, { "code": null, "e": 26673, "s": 26668, "text": "Java" }, { "code": null, "e": 26681, "s": 26673, "text": "Python3" }, { "code": null, "e": 26684, "s": 26681, "text": "C#" }, { "code": null, "e": 26695, "s": 26684, "text": "Javascript" }, { "code": "// C++ implementation to find the// Nth Central Binomial Coefficient #include<bits/stdc++.h>using namespace std; // Function to find the value of// Nth Central Binomial Coefficientint binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codeint main(){ int n = 3; int k = n; n = 2*n; cout << binomialCoeff(n, k);}", "e": 27505, "s": 26695, "text": null }, { "code": "// Java implementation to find the// Nth Central Binomial Coefficientclass GFG{ // Function to find the value of// Nth Central Binomial Coefficientstatic int binomialCoeff(int n, int k){ int[][] C = new int[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for(i = 0; i <= n; i++) { for(j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codepublic static void main(String[] args){ int n = 3; int k = n; n = 2 * n; System.out.println(binomialCoeff(n, k));}} // This code is contributed by Ritik Bansal", "e": 28404, "s": 27505, "text": null }, { "code": "# C# implementation to find the# Nth Central Binomial Coefficient # Function to find the value of# Nth Central Binomial Coefficientdef binomialCoeff(n, k): C = [[0 for j in range(k + 1)] for i in range(n + 1)] i = 0 j = 0 # Calculate value of Binomial # Coefficient in bottom up manner for i in range(n + 1): for j in range(min(i, k) + 1): # Base Cases if j == 0 or j == i: C[i][j] = 1 # Calculate value # using previously # stored values else: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) return C[n][k] # Driver codeif __name__=='__main__': n = 3 k = n n = 2 * n print(binomialCoeff(n, k)) # This code is contributed by rutvik_56", "e": 29278, "s": 28404, "text": null }, { "code": "// C# implementation to find the// Nth Central Binomial Coefficientusing System;class GFG{ // Function to find the value of// Nth Central Binomial Coefficientstatic int binomialCoeff(int n, int k){ int [,]C = new int[n + 1, k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for(i = 0; i <= n; i++) { for(j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value // using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k];} // Driver Codepublic static void Main(){ int n = 3; int k = n; n = 2 * n; Console.Write(binomialCoeff(n, k));}} // This code is contributed by Code_Mech", "e": 30170, "s": 29278, "text": null }, { "code": "<script> // Javascript implementation to find the// Nth Central Binomial Coefficient // Function to find the value of// Nth Central Binomial Coefficientfunction binomialCoeff(n, k){ var C = Array.from(Array(n+1),()=> Array(k+1)); var i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codevar n = 3;var k = n;n = 2*n;document.write( binomialCoeff(n, k)); </script>", "e": 30973, "s": 30170, "text": null }, { "code": null, "e": 30976, "s": 30973, "text": "20" }, { "code": null, "e": 31029, "s": 30978, "text": "Time Complexity: O(N * K)Auxiliary Space: O(N * K)" }, { "code": null, "e": 31041, "s": 31029, "text": "bansal_rtk_" }, { "code": null, "e": 31051, "s": 31041, "text": "Code_Mech" }, { "code": null, "e": 31062, "s": 31051, "text": "nidhi_biet" }, { "code": null, "e": 31072, "s": 31062, "text": "rutvik_56" }, { "code": null, "e": 31078, "s": 31072, "text": "itsok" }, { "code": null, "e": 31094, "s": 31078, "text": "subhammahato348" }, { "code": null, "e": 31115, "s": 31094, "text": "binomial coefficient" }, { "code": null, "e": 31122, "s": 31115, "text": "series" }, { "code": null, "e": 31135, "s": 31122, "text": "Mathematical" }, { "code": null, "e": 31148, "s": 31135, "text": "Mathematical" }, { "code": null, "e": 31155, "s": 31148, "text": "series" }, { "code": null, "e": 31253, "s": 31155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31297, "s": 31253, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31328, "s": 31297, "text": "Modular multiplicative inverse" }, { "code": null, "e": 31353, "s": 31328, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 31385, "s": 31353, "text": "Check if a number is Palindrome" }, { "code": null, "e": 31427, "s": 31385, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 31471, "s": 31427, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 31535, "s": 31471, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 31581, "s": 31535, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 31616, "s": 31581, "text": "Singular Value Decomposition (SVD)" } ]
How to sort an Array in C# | Array.Sort() Method Set - 1 - GeeksforGeeks
10 May, 2019 Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows: Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) MethodSort(Array, Int32, Int32, IComparer) MethodSort(Array, Array, Int32, Int32, IComparer) MethodSort(Array, Int32, Int32) MethodSort(Array, Array, Int32, Int32) MethodSort(Array, IComparer) MethodSort(Array, Array, IComparer) MethodSort(Array, Array) MethodSort(Array) MethodSort<T>(T[], Int32, Int32, IComparer<T>) MethodSort<TKey,TValue>(TKey[], TValue[]) MethodSort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) MethodSort<TKey,TValue>(TKey[], TValue[], Int32, Int32) MethodSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method Sort<T>(T[]) Method Sort<T>(T[], IComparer<T>) Method Sort<T>(T[], Int32, Int32) Method Sort<T>(T[], Comparison<T>) Method Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method Sort(Array, Array, Int32, Int32) Method Sort(Array, IComparer) Method Sort(Array, Array, IComparer) Method Sort(Array, Array) Method Sort(Array) Method Sort<T>(T[], Int32, Int32, IComparer<T>) Method Sort<TKey,TValue>(TKey[], TValue[]) Method Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Method Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Method Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method Here we will discuss the first 4 methods. This method sorts the elements in an Array using the IComparable<T> generic interface implementation of each element of the Array. Syntax: public static void Sort<T> (T[] array); Parameter:array: It is the one dimensional, zero-based Array which is to be sorted. Exceptions: ArgumentNullException: If the array is null. InvalidOperationException: If one or more elements in the array do not implement the IComparable<T> generic interface. Example: // C# Program to illustrate the use // of the Array.Sort<T>(T[]) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // array elements string[] arr = new string[5] { "A", "D", "X", "G", "M" }; foreach(string g in arr) { Console.WriteLine(g); // display original array } Console.WriteLine("\nAfter Sort:"); Array.Sort(arr); foreach(string g in arr) { Console.WriteLine(g); // display sorted array } Console.WriteLine("\nB sorts between :"); // binary Search for "B" int index = Array.BinarySearch(arr, "B"); // call "sortT" function // which is the Sort<T>(T[]) function sortT(arr, index); Console.WriteLine("\nF sorts between :"); index = Array.BinarySearch(arr, "F"); sortT(arr, index); } public static void sortT<T>(T[] arr, int index) { // If the index is negative, // it represents the bitwise // complement of the next larger // element in the array. if (index < 0) { index = ~index; if (index == 0) Console.Write("beginning of array"); else Console.Write("{0} and ", arr[index - 1]); if (index == arr.Length) Console.WriteLine("end of array."); else Console.WriteLine("{0}", arr[index]); } }} A D X G M After Sort: A D G M X B sorts between : A and D F sorts between : D and G This method Sorts the elements in an Array using the specified IComparer<T> generic interface. Syntax: public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T> comparer); Parameters: T : It is the type of the elements of the array. array : It is the one-dimensional Array which is to be sorted. comparer : It is the IComparer<T> generic interface implementation to use when comparing elements or null to use the IComparable<T> generic interface implementation of each element. Exceptions: ArgumentNullException: If the array is null. InvalidOperationException: If the comparer is null and there is no implementation of the IComparable<T> generic interface. ArgumentException:If the implementation of comparer caused an error during the sort. If the implementation of comparer caused an error during the sort. Example: // C# program to demonstrate the use of the // Array.Sort<T>(T[], IComparer<T>) methodusing System;using System.Collections.Generic; public class GeeK : IComparer<string> { public int Compare(string x, string y) { // Compare x and y in reverse order. return x.CompareTo(y); }} class GFG { // Main Method public static void Main() { // array elements string[] arr = new string[5] {"A", "D", "X", "G", "M" }; foreach(string g in arr) { // display original array Console.WriteLine(g); } Console.WriteLine("\nAfter Sort: "); GeeK gg = new GeeK(); // Sort<T>(T[], IComparer<T>) method Array.Sort(arr, gg); foreach(string g in arr) { // display sorted array Console.WriteLine(g); } Console.WriteLine("\nD Sorts between :"); // binary Search for "D" int index = Array.BinarySearch(arr, "D"); // call "sortT" function sortT(arr, index); Console.WriteLine("\nF Sorts between :"); index = Array.BinarySearch(arr, "F"); sortT(arr, index); } public static void sortT<T>(T[]arr, int index) { if (index < 0) { // If the index is negative, // it represents the bitwise // complement of the next // larger element in the array. index = ~index; Console.Write("Not found. Sorts between: "); if (index == 0) Console.Write("Beginning of array and "); else Console.Write("{0} and ", arr[index-1]); if (index == arr.Length) Console.WriteLine("end of array."); else Console.WriteLine("{0}.", arr[index]); } else { Console.WriteLine("Found at index {0}.", index); } }} A D X G M After Sort: A D G M X D Sorts between : Found at index 1. F Sorts between : Not found. Sorts between: D and G. This method sorts the elements in a range of in an Array using the IComparable<T> generic interface implementation of each element of the Array. Syntax: public static void Sort<T> (T[] array, int index, int length); Parameters: array: It is the one-dimensional, zero-based Array to sort. index: It is the starting index of the range to sort. length: It is the number of elements in the range to sort. Exceptions: ArgumentNullException: If the array is null. ArgumentOutOfRangeException: If the index is less than the lower bound of array or length is less than zero. ArgumentException: If the index and length do not specify a valid range in the array. InvalidOperationException: If one or more elements in the array do not implement the IComparable<T> generic interface. Example: // C# program to demonstrate the use of// Array.Sort<T>(T[], Int32, Int32) methodusing System;using System.Collections.Generic; public class Geek : IComparer<string> { public int Compare(string x, string y) { // Compare y and x in reverse order. return y.CompareTo(x); }} public class Example { // Main Method public static void Main() { // Array elements string[] arr = {"AB", "CD", "GH", "EF", "MN", "IJ"}; Console.WriteLine("Original Array :"); Display(arr); Console.WriteLine("\nSort the array between "+ "index 1 to 4"); // Array.Sort(T[], Int32, Int32) method // sort will happen in between // index 1 to 4 Array.Sort(arr, 1, 4); Display(arr); Console.WriteLine("\nSort the array reversely"+ " in between index 1 to 4"); // sort will happen in between // index 1 to 4 reversely Array.Sort(arr, 1, 4, new Geek()); Display(arr); } public static void Display(string[] arr) { foreach(string g in arr) { Console.WriteLine(g); } }} Original Array : AB CD GH EF MN IJ Sort the array between index 1 to 4 AB CD EF GH MN IJ Sort the array reversely in between index 1 to 4 AB MN GH EF CD IJ This method sorts the elements in an Array using the specified Comparison<T>. Syntax: public static void Sort<T> (T[] array, Comparison<T> comparison); Parameters: array: It is the one-dimensional zero-based Array which is to be sorted. comparison: It is the comparison<T> to used when comparing elements. Exceptions: ArgumentNullException: If the array is null or comparison is null. ArgumentException: If the implementation of comparison caused an error during the sort. Example: // C# program to demonstrate the use of the // Array.Sort<T>(T[ ], Comparison<T>) Methodusing System;using System.Collections.Generic; class GFG { private static int CompareComp(string x, string y) { if (y == null && x == null) { // If x and y is null // then x and y are same return 0; } else { // If x is null but y is not // null then y is greater. return -1; } } // Main method public static void Main() { string[] arr = {"Java", "C++", "Scala", "C", "Ruby", "Python"}; Console.WriteLine("Original Array: "); // display original array Display(arr); Console.WriteLine("\nSort with Comparison: "); // Array.Sort<T>(T[], Comparison<T>) // Method Array.Sort(arr, CompareComp); // display sorted array Display(arr); } // Display function public static void Display(string[] arr) { foreach(string g in arr) { Console.WriteLine(g); } }} Original Array: Java C++ Scala C Ruby Python Sort with Comparison: Python Ruby C Scala C++ Java Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=netframework-4.7.2 shubham_singh CSharp-Arrays CSharp-method C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# | Arrays of Strings C# | Delegates C# | Abstract Classes C# | Replace() Method Extension Method in C# C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 25378, "s": 25350, "text": "\n10 May, 2019" }, { "code": null, "e": 25518, "s": 25378, "text": "Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:" }, { "code": null, "e": 26187, "s": 25518, "text": "Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) MethodSort(Array, Int32, Int32, IComparer) MethodSort(Array, Array, Int32, Int32, IComparer) MethodSort(Array, Int32, Int32) MethodSort(Array, Array, Int32, Int32) MethodSort(Array, IComparer) MethodSort(Array, Array, IComparer) MethodSort(Array, Array) MethodSort(Array) MethodSort<T>(T[], Int32, Int32, IComparer<T>) MethodSort<TKey,TValue>(TKey[], TValue[]) MethodSort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) MethodSort<TKey,TValue>(TKey[], TValue[], Int32, Int32) MethodSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method" }, { "code": null, "e": 26207, "s": 26187, "text": "Sort<T>(T[]) Method" }, { "code": null, "e": 26241, "s": 26207, "text": "Sort<T>(T[], IComparer<T>) Method" }, { "code": null, "e": 26275, "s": 26241, "text": "Sort<T>(T[], Int32, Int32) Method" }, { "code": null, "e": 26310, "s": 26275, "text": "Sort<T>(T[], Comparison<T>) Method" }, { "code": null, "e": 26354, "s": 26310, "text": "Sort(Array, Int32, Int32, IComparer) Method" }, { "code": null, "e": 26405, "s": 26354, "text": "Sort(Array, Array, Int32, Int32, IComparer) Method" }, { "code": null, "e": 26438, "s": 26405, "text": "Sort(Array, Int32, Int32) Method" }, { "code": null, "e": 26478, "s": 26438, "text": "Sort(Array, Array, Int32, Int32) Method" }, { "code": null, "e": 26508, "s": 26478, "text": "Sort(Array, IComparer) Method" }, { "code": null, "e": 26545, "s": 26508, "text": "Sort(Array, Array, IComparer) Method" }, { "code": null, "e": 26571, "s": 26545, "text": "Sort(Array, Array) Method" }, { "code": null, "e": 26590, "s": 26571, "text": "Sort(Array) Method" }, { "code": null, "e": 26638, "s": 26590, "text": "Sort<T>(T[], Int32, Int32, IComparer<T>) Method" }, { "code": null, "e": 26681, "s": 26638, "text": "Sort<TKey,TValue>(TKey[], TValue[]) Method" }, { "code": null, "e": 26741, "s": 26681, "text": "Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Method" }, { "code": null, "e": 26798, "s": 26741, "text": "Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Method" }, { "code": null, "e": 26872, "s": 26798, "text": "Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method" }, { "code": null, "e": 26914, "s": 26872, "text": "Here we will discuss the first 4 methods." }, { "code": null, "e": 27045, "s": 26914, "text": "This method sorts the elements in an Array using the IComparable<T> generic interface implementation of each element of the Array." }, { "code": null, "e": 27093, "s": 27045, "text": "Syntax: public static void Sort<T> (T[] array);" }, { "code": null, "e": 27177, "s": 27093, "text": "Parameter:array: It is the one dimensional, zero-based Array which is to be sorted." }, { "code": null, "e": 27189, "s": 27177, "text": "Exceptions:" }, { "code": null, "e": 27234, "s": 27189, "text": "ArgumentNullException: If the array is null." }, { "code": null, "e": 27353, "s": 27234, "text": "InvalidOperationException: If one or more elements in the array do not implement the IComparable<T> generic interface." }, { "code": null, "e": 27362, "s": 27353, "text": "Example:" }, { "code": "// C# Program to illustrate the use // of the Array.Sort<T>(T[]) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // array elements string[] arr = new string[5] { \"A\", \"D\", \"X\", \"G\", \"M\" }; foreach(string g in arr) { Console.WriteLine(g); // display original array } Console.WriteLine(\"\\nAfter Sort:\"); Array.Sort(arr); foreach(string g in arr) { Console.WriteLine(g); // display sorted array } Console.WriteLine(\"\\nB sorts between :\"); // binary Search for \"B\" int index = Array.BinarySearch(arr, \"B\"); // call \"sortT\" function // which is the Sort<T>(T[]) function sortT(arr, index); Console.WriteLine(\"\\nF sorts between :\"); index = Array.BinarySearch(arr, \"F\"); sortT(arr, index); } public static void sortT<T>(T[] arr, int index) { // If the index is negative, // it represents the bitwise // complement of the next larger // element in the array. if (index < 0) { index = ~index; if (index == 0) Console.Write(\"beginning of array\"); else Console.Write(\"{0} and \", arr[index - 1]); if (index == arr.Length) Console.WriteLine(\"end of array.\"); else Console.WriteLine(\"{0}\", arr[index]); } }}", "e": 28943, "s": 27362, "text": null }, { "code": null, "e": 29031, "s": 28943, "text": "A\nD\nX\nG\nM\n\nAfter Sort:\nA\nD\nG\nM\nX\n\nB sorts between :\nA and D\n\nF sorts between :\nD and G\n" }, { "code": null, "e": 29126, "s": 29031, "text": "This method Sorts the elements in an Array using the specified IComparer<T> generic interface." }, { "code": null, "e": 29224, "s": 29126, "text": "Syntax: public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T> comparer);" }, { "code": null, "e": 29236, "s": 29224, "text": "Parameters:" }, { "code": null, "e": 29285, "s": 29236, "text": "T : It is the type of the elements of the array." }, { "code": null, "e": 29348, "s": 29285, "text": "array : It is the one-dimensional Array which is to be sorted." }, { "code": null, "e": 29530, "s": 29348, "text": "comparer : It is the IComparer<T> generic interface implementation to use when comparing elements or null to use the IComparable<T> generic interface implementation of each element." }, { "code": null, "e": 29542, "s": 29530, "text": "Exceptions:" }, { "code": null, "e": 29587, "s": 29542, "text": "ArgumentNullException: If the array is null." }, { "code": null, "e": 29710, "s": 29587, "text": "InvalidOperationException: If the comparer is null and there is no implementation of the IComparable<T> generic interface." }, { "code": null, "e": 29795, "s": 29710, "text": "ArgumentException:If the implementation of comparer caused an error during the sort." }, { "code": null, "e": 29862, "s": 29795, "text": "If the implementation of comparer caused an error during the sort." }, { "code": null, "e": 29871, "s": 29862, "text": "Example:" }, { "code": "// C# program to demonstrate the use of the // Array.Sort<T>(T[], IComparer<T>) methodusing System;using System.Collections.Generic; public class GeeK : IComparer<string> { public int Compare(string x, string y) { // Compare x and y in reverse order. return x.CompareTo(y); }} class GFG { // Main Method public static void Main() { // array elements string[] arr = new string[5] {\"A\", \"D\", \"X\", \"G\", \"M\" }; foreach(string g in arr) { // display original array Console.WriteLine(g); } Console.WriteLine(\"\\nAfter Sort: \"); GeeK gg = new GeeK(); // Sort<T>(T[], IComparer<T>) method Array.Sort(arr, gg); foreach(string g in arr) { // display sorted array Console.WriteLine(g); } Console.WriteLine(\"\\nD Sorts between :\"); // binary Search for \"D\" int index = Array.BinarySearch(arr, \"D\"); // call \"sortT\" function sortT(arr, index); Console.WriteLine(\"\\nF Sorts between :\"); index = Array.BinarySearch(arr, \"F\"); sortT(arr, index); } public static void sortT<T>(T[]arr, int index) { if (index < 0) { // If the index is negative, // it represents the bitwise // complement of the next // larger element in the array. index = ~index; Console.Write(\"Not found. Sorts between: \"); if (index == 0) Console.Write(\"Beginning of array and \"); else Console.Write(\"{0} and \", arr[index-1]); if (index == arr.Length) Console.WriteLine(\"end of array.\"); else Console.WriteLine(\"{0}.\", arr[index]); } else { Console.WriteLine(\"Found at index {0}.\", index); } }}", "e": 31860, "s": 29871, "text": null }, { "code": null, "e": 31986, "s": 31860, "text": "A\nD\nX\nG\nM\n\nAfter Sort: \nA\nD\nG\nM\nX\n\nD Sorts between :\nFound at index 1.\n\nF Sorts between :\nNot found. Sorts between: D and G.\n" }, { "code": null, "e": 32131, "s": 31986, "text": "This method sorts the elements in a range of in an Array using the IComparable<T> generic interface implementation of each element of the Array." }, { "code": null, "e": 32202, "s": 32131, "text": "Syntax: public static void Sort<T> (T[] array, int index, int length);" }, { "code": null, "e": 32214, "s": 32202, "text": "Parameters:" }, { "code": null, "e": 32274, "s": 32214, "text": "array: It is the one-dimensional, zero-based Array to sort." }, { "code": null, "e": 32328, "s": 32274, "text": "index: It is the starting index of the range to sort." }, { "code": null, "e": 32387, "s": 32328, "text": "length: It is the number of elements in the range to sort." }, { "code": null, "e": 32399, "s": 32387, "text": "Exceptions:" }, { "code": null, "e": 32444, "s": 32399, "text": "ArgumentNullException: If the array is null." }, { "code": null, "e": 32553, "s": 32444, "text": "ArgumentOutOfRangeException: If the index is less than the lower bound of array or length is less than zero." }, { "code": null, "e": 32639, "s": 32553, "text": "ArgumentException: If the index and length do not specify a valid range in the array." }, { "code": null, "e": 32758, "s": 32639, "text": "InvalidOperationException: If one or more elements in the array do not implement the IComparable<T> generic interface." }, { "code": null, "e": 32767, "s": 32758, "text": "Example:" }, { "code": "// C# program to demonstrate the use of// Array.Sort<T>(T[], Int32, Int32) methodusing System;using System.Collections.Generic; public class Geek : IComparer<string> { public int Compare(string x, string y) { // Compare y and x in reverse order. return y.CompareTo(x); }} public class Example { // Main Method public static void Main() { // Array elements string[] arr = {\"AB\", \"CD\", \"GH\", \"EF\", \"MN\", \"IJ\"}; Console.WriteLine(\"Original Array :\"); Display(arr); Console.WriteLine(\"\\nSort the array between \"+ \"index 1 to 4\"); // Array.Sort(T[], Int32, Int32) method // sort will happen in between // index 1 to 4 Array.Sort(arr, 1, 4); Display(arr); Console.WriteLine(\"\\nSort the array reversely\"+ \" in between index 1 to 4\"); // sort will happen in between // index 1 to 4 reversely Array.Sort(arr, 1, 4, new Geek()); Display(arr); } public static void Display(string[] arr) { foreach(string g in arr) { Console.WriteLine(g); } }}", "e": 34025, "s": 32767, "text": null }, { "code": null, "e": 34184, "s": 34025, "text": "Original Array :\nAB\nCD\nGH\nEF\nMN\nIJ\n\nSort the array between index 1 to 4\nAB\nCD\nEF\nGH\nMN\nIJ\n\nSort the array reversely in between index 1 to 4\nAB\nMN\nGH\nEF\nCD\nIJ\n" }, { "code": null, "e": 34262, "s": 34184, "text": "This method sorts the elements in an Array using the specified Comparison<T>." }, { "code": null, "e": 34336, "s": 34262, "text": "Syntax: public static void Sort<T> (T[] array, Comparison<T> comparison);" }, { "code": null, "e": 34348, "s": 34336, "text": "Parameters:" }, { "code": null, "e": 34421, "s": 34348, "text": "array: It is the one-dimensional zero-based Array which is to be sorted." }, { "code": null, "e": 34490, "s": 34421, "text": "comparison: It is the comparison<T> to used when comparing elements." }, { "code": null, "e": 34502, "s": 34490, "text": "Exceptions:" }, { "code": null, "e": 34569, "s": 34502, "text": "ArgumentNullException: If the array is null or comparison is null." }, { "code": null, "e": 34657, "s": 34569, "text": "ArgumentException: If the implementation of comparison caused an error during the sort." }, { "code": null, "e": 34666, "s": 34657, "text": "Example:" }, { "code": "// C# program to demonstrate the use of the // Array.Sort<T>(T[ ], Comparison<T>) Methodusing System;using System.Collections.Generic; class GFG { private static int CompareComp(string x, string y) { if (y == null && x == null) { // If x and y is null // then x and y are same return 0; } else { // If x is null but y is not // null then y is greater. return -1; } } // Main method public static void Main() { string[] arr = {\"Java\", \"C++\", \"Scala\", \"C\", \"Ruby\", \"Python\"}; Console.WriteLine(\"Original Array: \"); // display original array Display(arr); Console.WriteLine(\"\\nSort with Comparison: \"); // Array.Sort<T>(T[], Comparison<T>) // Method Array.Sort(arr, CompareComp); // display sorted array Display(arr); } // Display function public static void Display(string[] arr) { foreach(string g in arr) { Console.WriteLine(g); } }}", "e": 35842, "s": 34666, "text": null }, { "code": null, "e": 35942, "s": 35842, "text": "Original Array: \nJava\nC++\nScala\nC\nRuby\nPython\n\nSort with Comparison: \nPython\nRuby\nC\nScala\nC++\nJava\n" }, { "code": null, "e": 35953, "s": 35942, "text": "Reference:" }, { "code": null, "e": 36039, "s": 35953, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=netframework-4.7.2" }, { "code": null, "e": 36053, "s": 36039, "text": "shubham_singh" }, { "code": null, "e": 36067, "s": 36053, "text": "CSharp-Arrays" }, { "code": null, "e": 36081, "s": 36067, "text": "CSharp-method" }, { "code": null, "e": 36084, "s": 36081, "text": "C#" }, { "code": null, "e": 36103, "s": 36084, "text": "Technical Scripter" }, { "code": null, "e": 36201, "s": 36103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36255, "s": 36201, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 36297, "s": 36255, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 36359, "s": 36297, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 36387, "s": 36359, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 36410, "s": 36387, "text": "C# | Arrays of Strings" }, { "code": null, "e": 36425, "s": 36410, "text": "C# | Delegates" }, { "code": null, "e": 36447, "s": 36425, "text": "C# | Abstract Classes" }, { "code": null, "e": 36469, "s": 36447, "text": "C# | Replace() Method" }, { "code": null, "e": 36492, "s": 36469, "text": "Extension Method in C#" } ]
Field getAnnotation() method in Java With Examples - GeeksforGeeks
17 Sep, 2019 The getAnnotation() method of java.lang.reflect.Field is used to return returns Field objects’s for the specified type if such an annotation is present, else null.This is important method to get annotation for Field object. Syntax: public <T extends Annotation> T getAnnotation(Class<T> annotationClass) Parameters: This method annotationClass which is the Class object corresponding to the annotation type. Return: This method returns this element’s annotation for the specified annotation type if present on this element, else null. Exception: This method throws NullPointerException if the given annotation class is null. Below programs illustrate getAnnotation() method:Program 1: // Java program to illustrate// getAnnotation() method import java.lang.annotation.*;import java.lang.reflect.AnnotatedType;import java.lang.reflect.Field;import java.util.Arrays; public class GFG { // initialize field with // default value in annotation @annotations(3125462345.32155365326) private double realNumbers; public static void main(String[] args) throws NoSuchFieldException { // create Field object Field field = GFG.class .getDeclaredField("realNumbers"); // apply getAnnotation() annotations annotations = field.getAnnotation( annotations.class); // print results System.out.println(annotations); } @Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) private @interface annotations { double value() default 99.9; }} @GFG$annotations(value=3.1254623453215537E9) Program 2: // Java program to illustrate// getAnnotation() method import java.lang.annotation.*;import java.lang.reflect.AnnotatedType;import java.lang.reflect.Field;import java.util.Arrays; public class GFG { private int @SpecialNumber[] number; public static void main(String[] args) throws NoSuchFieldException { // get Field object Field field = GFG.class .getDeclaredField("number"); // apply getAnnotation() method AnnotatedType annotatedType = field.getAnnotation(); // print the results System.out.println( "Type: " + annotatedType.getType() .getTypeName()); System.out.println( "Annotations: " + Arrays.toString( annotatedType .getAnnotations())); System.out.println( "Declared Annotations: " + Arrays.toString( annotatedType .getDeclaredAnnotations())); } @Target({ ElementType.TYPE_USE }) @Retention(RetentionPolicy.RUNTIME) private @interface SpecialNumber { }} @GFG$annotations(value=WelcomeTOGFG) References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotation– Java-Field Java-Functions java-lang-reflect-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25501, "s": 25473, "text": "\n17 Sep, 2019" }, { "code": null, "e": 25725, "s": 25501, "text": "The getAnnotation() method of java.lang.reflect.Field is used to return returns Field objects’s for the specified type if such an annotation is present, else null.This is important method to get annotation for Field object." }, { "code": null, "e": 25733, "s": 25725, "text": "Syntax:" }, { "code": null, "e": 25808, "s": 25733, "text": "public <T extends Annotation> T\n getAnnotation(Class<T> annotationClass)\n" }, { "code": null, "e": 25912, "s": 25808, "text": "Parameters: This method annotationClass which is the Class object corresponding to the annotation type." }, { "code": null, "e": 26039, "s": 25912, "text": "Return: This method returns this element’s annotation for the specified annotation type if present on this element, else null." }, { "code": null, "e": 26129, "s": 26039, "text": "Exception: This method throws NullPointerException if the given annotation class is null." }, { "code": null, "e": 26189, "s": 26129, "text": "Below programs illustrate getAnnotation() method:Program 1:" }, { "code": "// Java program to illustrate// getAnnotation() method import java.lang.annotation.*;import java.lang.reflect.AnnotatedType;import java.lang.reflect.Field;import java.util.Arrays; public class GFG { // initialize field with // default value in annotation @annotations(3125462345.32155365326) private double realNumbers; public static void main(String[] args) throws NoSuchFieldException { // create Field object Field field = GFG.class .getDeclaredField(\"realNumbers\"); // apply getAnnotation() annotations annotations = field.getAnnotation( annotations.class); // print results System.out.println(annotations); } @Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) private @interface annotations { double value() default 99.9; }}", "e": 27094, "s": 26189, "text": null }, { "code": null, "e": 27140, "s": 27094, "text": "@GFG$annotations(value=3.1254623453215537E9)\n" }, { "code": null, "e": 27151, "s": 27140, "text": "Program 2:" }, { "code": "// Java program to illustrate// getAnnotation() method import java.lang.annotation.*;import java.lang.reflect.AnnotatedType;import java.lang.reflect.Field;import java.util.Arrays; public class GFG { private int @SpecialNumber[] number; public static void main(String[] args) throws NoSuchFieldException { // get Field object Field field = GFG.class .getDeclaredField(\"number\"); // apply getAnnotation() method AnnotatedType annotatedType = field.getAnnotation(); // print the results System.out.println( \"Type: \" + annotatedType.getType() .getTypeName()); System.out.println( \"Annotations: \" + Arrays.toString( annotatedType .getAnnotations())); System.out.println( \"Declared Annotations: \" + Arrays.toString( annotatedType .getDeclaredAnnotations())); } @Target({ ElementType.TYPE_USE }) @Retention(RetentionPolicy.RUNTIME) private @interface SpecialNumber { }}", "e": 28309, "s": 27151, "text": null }, { "code": null, "e": 28347, "s": 28309, "text": "@GFG$annotations(value=WelcomeTOGFG)\n" }, { "code": null, "e": 28445, "s": 28347, "text": "References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotation–" }, { "code": null, "e": 28456, "s": 28445, "text": "Java-Field" }, { "code": null, "e": 28471, "s": 28456, "text": "Java-Functions" }, { "code": null, "e": 28497, "s": 28471, "text": "java-lang-reflect-package" }, { "code": null, "e": 28502, "s": 28497, "text": "Java" }, { "code": null, "e": 28507, "s": 28502, "text": "Java" }, { "code": null, "e": 28605, "s": 28507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28656, "s": 28605, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28686, "s": 28656, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28705, "s": 28686, "text": "Interfaces in Java" }, { "code": null, "e": 28736, "s": 28705, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28754, "s": 28736, "text": "ArrayList in Java" }, { "code": null, "e": 28786, "s": 28754, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28806, "s": 28786, "text": "Stack Class in Java" }, { "code": null, "e": 28830, "s": 28806, "text": "Singleton Class in Java" }, { "code": null, "e": 28862, "s": 28830, "text": "Multidimensional Arrays in Java" } ]
B+ tree Insertion in Data Structure
Here we will see, how to perform the insertion into a B+ Tree. Suppose we have a B+ Tree like below − Example of B+ Tree − To insert an element, the idea is very similar to the B-Tree, if one element is inserted, that will be stored at the leaf node. If that is present in some internal node, then it will also be there, at the leaf as right child of itself. Suppose we want to insert 65 into the tree. So that is greater than 60, and less than 75. Then it will be inserted into the middle sub-tree. Now, 65, will be inserted into node after 63, then that node will be divided into two parts, 65 will go up, and 65 will also be there at the right node of it. B+ Tree after inserting 65. BPlusTreeInsert(root, key) − Input − The root of the tree, and key to insert We will assume, that the key is not present into the list Start from root node, perform exact match for key as ‘key’ till a leaf node. Let the search path be x1, x2, ... , xh. The x1 is first node so root, then xh is leaf node. Each node xi is parent of xi+1 Insert the new object where key is ‘key’, and value is v into xh. i := h while xi overflows, do divide xi into two nodes, by moving the larger half of the keys into a new node p. if xi is leaf node, link p into the linked list among leaf nodes. identify a key k, to be inserted into the parent level along with child pointer pointing p. The choice of k depends on the type of the node xi. If xi is leaf node, we will perform copy up. So smallest key in p, is copied as k to the parent level. On the other hand, if xi is non-leaf node, then we will perform push up. So smallest key in p, will be copied into k, in the parent node. if i = 0, then create a new index node as the new root. In the new root store node with key k, and two child xi and p. return else insert a key k and a child pointer pointing to p, into node xi-1. i := i – 1 end if done
[ { "code": null, "e": 1164, "s": 1062, "text": "Here we will see, how to perform the insertion into a B+ Tree. Suppose we have a B+ Tree like below −" }, { "code": null, "e": 1185, "s": 1164, "text": "Example of B+ Tree −" }, { "code": null, "e": 1421, "s": 1185, "text": "To insert an element, the idea is very similar to the B-Tree, if one element is inserted, that will be stored at the leaf node. If that is present in some internal node, then it will also be there, at the leaf as right child of itself." }, { "code": null, "e": 1721, "s": 1421, "text": "Suppose we want to insert 65 into the tree. So that is greater than 60, and less than 75. Then it will be inserted into the middle sub-tree. Now, 65, will be inserted into node after 63, then that node will be divided into two parts, 65 will go up, and 65 will also be there at the right node of it." }, { "code": null, "e": 1749, "s": 1721, "text": "B+ Tree after inserting 65." }, { "code": null, "e": 1778, "s": 1749, "text": "BPlusTreeInsert(root, key) −" }, { "code": null, "e": 1826, "s": 1778, "text": "Input − The root of the tree, and key to insert" }, { "code": null, "e": 2995, "s": 1826, "text": "We will assume, that the key is not present into the list\nStart from root node, perform exact match for key as ‘key’ till a leaf node. Let the search path\nbe x1, x2, ... , xh. The x1 is first node so root, then xh is leaf node. Each node xi is parent of xi+1\nInsert the new object where key is ‘key’, and value is v into xh.\ni := h\nwhile xi overflows, do\n divide xi into two nodes, by moving the larger half of the keys into a new node p.\n if xi is leaf node, link p into the linked list among leaf nodes.\n identify a key k, to be inserted into the parent level along with child pointer pointing p.\n The choice of k depends on the type of the node xi. If xi is leaf node, we will perform\n copy up. So smallest key in p, is copied as k to the parent level. On the other hand, if xi is\n non-leaf node, then we will perform push up. So smallest key in p, will be copied into k,\n in the parent node.\n if i = 0, then\n create a new index node as the new root. In the new root store node with key k,\n and two child xi and p.\n return\n else\n insert a key k and a child pointer pointing to p, into node xi-1.\n i := i – 1\n end if\ndone" } ]
What is a Graphics Card? - GeeksforGeeks
12 Aug, 2020 Graphics card is a hardware which is used to increase the video memory of a computer, and make its display quality more high-definition. It makes the computer more powerful and gives it the capacity to do more high-level works. The quality of the image depends on the quality of the graphics card. It is very much important for gaming and video editing on a PC. Every game needs a graphics memory to start and it depends on the type of the game, and the requirements are mentioned on the game box. Example : Acer predator –Nvidia GTX 1050 4GB Graphics Card. Alienware 17 –Nvidia Geforce GTX 1070 8GB Graphics Card. Both computers have a high power graphics card for better performance. GPU : GPU stands for Graphics Processing Unit. The power of GPU depend on the model of the GPU. The graphics as an external component is attached on a slot known as an expansion slot. It is the brain of the graphics card and is what creates the visuals that we see on the monitor. Types of Graphics Card : Integrated –The graphics which are built into the motherboard are known as Integrated, are generally used in most laptops, the cannot be easily upgraded.Discrete –It is an external graphics card which is a hardware and added on a motherboard as an extra component. Most people may not need an external graphics card for there work on PC. Basic work like creating files, doing office work, watching movies, listing songs, etc may not need a graphics card. But for the users playing high resolutions games and video editing may need an external component i.e graphics card for there purpose. Integrated –The graphics which are built into the motherboard are known as Integrated, are generally used in most laptops, the cannot be easily upgraded. Discrete –It is an external graphics card which is a hardware and added on a motherboard as an extra component. Most people may not need an external graphics card for there work on PC. Basic work like creating files, doing office work, watching movies, listing songs, etc may not need a graphics card. But for the users playing high resolutions games and video editing may need an external component i.e graphics card for there purpose. Features of Graphics Card : Memory –Graphics card carries its own memory. Memory range could be from 128MB to 2GB of memory. We should buy a card with more memory. More RAM equals higher resolutions, more colors on the screen, and the best special effects. Multiple Screen support –Most new video cards have the ability to connect two monitors to one card. This feature is very important for video editing and hardcore gamer craves that extra real estate as well. You can either see two separate Desktops or make the two monitors into one Desktop. Gaming And Video Editing –The discrete graphics card is not only for a gamer but those who use high-end video editing software also get help as a high-quality graphics card to reduce the rendering time of an image also give a high-def environment. Connection –The graphic card is connected to the monitor using many different ports put the port must be present on both monitor and Graphics card. These are some common ports used to connect graphics card with a monitor.1. VGA 2. HDMI 3. DVI Some motherboards have more than 1 expansion slot so we can add more than one graphics card to make performance better. Many laptops nowadays come with an integrated graphics card in them. 1. VGA 2. HDMI 3. DVI Some motherboards have more than 1 expansion slot so we can add more than one graphics card to make performance better. Many laptops nowadays come with an integrated graphics card in them. Manufacturers of Graphics Card :The two main manufacturers of discrete graphics card are – 1. NVIDIA 2. AMD computer-graphics Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advantages and Disadvantages of OOP Lex Program to count number of words Consensus Algorithms in Blockchain Challenges in Internet of things (IoT) Spatial Filtering and its Types Characteristics of Internet of Things Election algorithm and distributed processing Activation Functions Bubble Sort algorithm using JavaScript Practice Questions for Recursion | Set 2
[ { "code": null, "e": 24257, "s": 24229, "text": "\n12 Aug, 2020" }, { "code": null, "e": 24755, "s": 24257, "text": "Graphics card is a hardware which is used to increase the video memory of a computer, and make its display quality more high-definition. It makes the computer more powerful and gives it the capacity to do more high-level works. The quality of the image depends on the quality of the graphics card. It is very much important for gaming and video editing on a PC. Every game needs a graphics memory to start and it depends on the type of the game, and the requirements are mentioned on the game box." }, { "code": null, "e": 24765, "s": 24755, "text": "Example :" }, { "code": null, "e": 24815, "s": 24765, "text": "Acer predator –Nvidia GTX 1050 4GB Graphics Card." }, { "code": null, "e": 24872, "s": 24815, "text": "Alienware 17 –Nvidia Geforce GTX 1070 8GB Graphics Card." }, { "code": null, "e": 24943, "s": 24872, "text": "Both computers have a high power graphics card for better performance." }, { "code": null, "e": 24949, "s": 24943, "text": "GPU :" }, { "code": null, "e": 24990, "s": 24949, "text": "GPU stands for Graphics Processing Unit." }, { "code": null, "e": 25039, "s": 24990, "text": "The power of GPU depend on the model of the GPU." }, { "code": null, "e": 25127, "s": 25039, "text": "The graphics as an external component is attached on a slot known as an expansion slot." }, { "code": null, "e": 25224, "s": 25127, "text": "It is the brain of the graphics card and is what creates the visuals that we see on the monitor." }, { "code": null, "e": 25249, "s": 25224, "text": "Types of Graphics Card :" }, { "code": null, "e": 25839, "s": 25249, "text": "Integrated –The graphics which are built into the motherboard are known as Integrated, are generally used in most laptops, the cannot be easily upgraded.Discrete –It is an external graphics card which is a hardware and added on a motherboard as an extra component. Most people may not need an external graphics card for there work on PC. Basic work like creating files, doing office work, watching movies, listing songs, etc may not need a graphics card. But for the users playing high resolutions games and video editing may need an external component i.e graphics card for there purpose." }, { "code": null, "e": 25993, "s": 25839, "text": "Integrated –The graphics which are built into the motherboard are known as Integrated, are generally used in most laptops, the cannot be easily upgraded." }, { "code": null, "e": 26430, "s": 25993, "text": "Discrete –It is an external graphics card which is a hardware and added on a motherboard as an extra component. Most people may not need an external graphics card for there work on PC. Basic work like creating files, doing office work, watching movies, listing songs, etc may not need a graphics card. But for the users playing high resolutions games and video editing may need an external component i.e graphics card for there purpose." }, { "code": null, "e": 26458, "s": 26430, "text": "Features of Graphics Card :" }, { "code": null, "e": 26687, "s": 26458, "text": "Memory –Graphics card carries its own memory. Memory range could be from 128MB to 2GB of memory. We should buy a card with more memory. More RAM equals higher resolutions, more colors on the screen, and the best special effects." }, { "code": null, "e": 26978, "s": 26687, "text": "Multiple Screen support –Most new video cards have the ability to connect two monitors to one card. This feature is very important for video editing and hardcore gamer craves that extra real estate as well. You can either see two separate Desktops or make the two monitors into one Desktop." }, { "code": null, "e": 27226, "s": 26978, "text": "Gaming And Video Editing –The discrete graphics card is not only for a gamer but those who use high-end video editing software also get help as a high-quality graphics card to reduce the rendering time of an image also give a high-def environment." }, { "code": null, "e": 27658, "s": 27226, "text": "Connection –The graphic card is connected to the monitor using many different ports put the port must be present on both monitor and Graphics card. These are some common ports used to connect graphics card with a monitor.1. VGA\n2. HDMI\n3. DVI Some motherboards have more than 1 expansion slot so we can add more than one graphics card to make performance better. Many laptops nowadays come with an integrated graphics card in them." }, { "code": null, "e": 27681, "s": 27658, "text": "1. VGA\n2. HDMI\n3. DVI " }, { "code": null, "e": 27870, "s": 27681, "text": "Some motherboards have more than 1 expansion slot so we can add more than one graphics card to make performance better. Many laptops nowadays come with an integrated graphics card in them." }, { "code": null, "e": 27961, "s": 27870, "text": "Manufacturers of Graphics Card :The two main manufacturers of discrete graphics card are –" }, { "code": null, "e": 27979, "s": 27961, "text": "1. NVIDIA\n2. AMD " }, { "code": null, "e": 27997, "s": 27979, "text": "computer-graphics" }, { "code": null, "e": 28002, "s": 27997, "text": "Misc" }, { "code": null, "e": 28007, "s": 28002, "text": "Misc" }, { "code": null, "e": 28012, "s": 28007, "text": "Misc" }, { "code": null, "e": 28110, "s": 28012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28119, "s": 28110, "text": "Comments" }, { "code": null, "e": 28132, "s": 28119, "text": "Old Comments" }, { "code": null, "e": 28168, "s": 28132, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 28205, "s": 28168, "text": "Lex Program to count number of words" }, { "code": null, "e": 28240, "s": 28205, "text": "Consensus Algorithms in Blockchain" }, { "code": null, "e": 28279, "s": 28240, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 28311, "s": 28279, "text": "Spatial Filtering and its Types" }, { "code": null, "e": 28349, "s": 28311, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 28395, "s": 28349, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 28416, "s": 28395, "text": "Activation Functions" }, { "code": null, "e": 28455, "s": 28416, "text": "Bubble Sort algorithm using JavaScript" } ]
Convert Your Python Code into a Windows Application (.exe file) | by Ujjwal Dalmia | Towards Data Science
You wrote an amazing Python application and presented it to your boss. He is impressed and wants to use it on his system. He neither has Python installed on his system and nor he has ever worked on it. You are stuck!!! If the above sounds familiar, then this tutorial will solve your problem. Here, we will learn the process of converting a Python code to a Windows executable file. From now onward, every time you want to share your excellent work with the wider community, you don’t have to worry about setting up the Python environment on their systems. Just create an executable and send it to them. They will be able to use the application, just like you do on your system. For this tutorial, we have written a small Python code that reads a ‘.csv’ file from the Windows folder location. This file has 2 columns, each containing a set of random numbers. The code creates a new column that contains the sum of numbers from the 2 input columns. The modified file is saved at the same folder location as the old one. #### Importing the required libraryimport pandas as pd#### Reading csv filedf = pd.read_csv("C:\\Ujjwal\\New_File_V1.csv")#### Adding 2 columnsdf["Third_Column"] = df["Randome Numbers 1"] + df["Random Numbers 2"]#### Exporting the data to same locationdf.to_csv("C:\\Ujjwal\\New_File_V2.csv",index = False) Sample columns of the input CSV file are as follows: The output file after the code execution looks like below: To convert the Python code into an executable file, we will be using Pyinstaller package. Use the standard ‘pip install’ command to install this package. #### Install Commandpip install pyinstaller Let’s go step by step to convert the Python file to a Windows executable: Open the command prompt— The conversion of the Python script to Windows executable is done using the command line. For this purpose, we have to go to the command prompt. Type “cmd” in your Windows search box and open the command prompt Change folder location — Use the following command and direct the command prompt to the location of your Python code: #### Change Folder Locationcd folder_location Conversion— Use the following command to convert the Python file into a Windows executable: #### Command for conversionpyinstaller --onefile filename The above code will create a single executable file with the same functionality as your python code. The executable file will be available in a new folder, dist, which will be available at the same location as your Python script. Execution — To execute the file, just double click the executable and it will produce the same results as your Python script. There are some common questions/challenges faced by people when working with pyinstaller. This section will answer most of them: Apart from the dist folder, which contains the executable file, other files and folders are getting created. You don’t need them. You can share your executable file without these additional files. Even when you will delete the additional files and folders, your executable will not lose its functionality. Both, creation of the executable file and execution of the executable file is a time-consuming task. For a short script like ours, the creation of the executable took close to 5 mins and the execution takes close to 30 seconds. Since we are importing packages in our Python script, to make the executable self-sufficient, the complete package gets incorporated in the executable file. This increases the size of the executable file. For our case, it was more than 300 MB The most common error which one can face when executing the executable file is “ModuleNotFoundError: No module named module name”. A sample screenshot of this error and the actual error prompt is as follows: #### Error Prompt MessageModuleNotFoundError: No module named 'pandas._libs.tslibs.nattypes' If you encounter an error like this (module name can be different) then take the following steps: Go to the Windows location where the pyinstaller package is installed. Since I am using Anaconda distribution, the following is the location on my system: #### Package LocationC:\Users\Ujjwal\Anaconda3\Lib\site-packages In the pyinstaller package folder, search for the folder named hooks. This folder has hook files for most of the commonly used Python packages. Search for the hook file, for the Python package, which has raised the error. In our case it was Pandas. The sample hook file and its contents are as follows: The reason behind the error is the malfunctioning of the command where ‘hiddenimports’ is getting initialized. Comment this statement and add a new one in which the ‘hiddenimports’ is initialized with the same module name which has raised the error. For our case, it was ‘pandas._libs.tslibs.nattype’. The code line to be added is as follows: #### Code line for hook filehiddenimports = 'pandas._libs.tslibs.nattype' Once the hook file is modified, save it and re-create the new executable. Before recreating, please ensure that the old executable file and associated folders are deleted. If the error persists, continue to add the other missing modules in your hook file. Please note that multiple modules should be added as a list structure. #### Code line after adding multiple moduleshiddenimports = ['pandas._libs.tslibs.np_datetime','pandas._libs.tslibs.nattype','pandas._libs.skiplist'] The final hook file which we used for our example looked as follows: Once all the modules are added, the error will get resolved. In the above tutorial, we have tried addressing a small challenge that most of us have faced at some point in time in our carrier. I hope this tutorial was informative and you learned something new. Will try and bring more interesting topics in future tutorials. Till then:
[ { "code": null, "e": 390, "s": 171, "text": "You wrote an amazing Python application and presented it to your boss. He is impressed and wants to use it on his system. He neither has Python installed on his system and nor he has ever worked on it. You are stuck!!!" }, { "code": null, "e": 850, "s": 390, "text": "If the above sounds familiar, then this tutorial will solve your problem. Here, we will learn the process of converting a Python code to a Windows executable file. From now onward, every time you want to share your excellent work with the wider community, you don’t have to worry about setting up the Python environment on their systems. Just create an executable and send it to them. They will be able to use the application, just like you do on your system." }, { "code": null, "e": 1190, "s": 850, "text": "For this tutorial, we have written a small Python code that reads a ‘.csv’ file from the Windows folder location. This file has 2 columns, each containing a set of random numbers. The code creates a new column that contains the sum of numbers from the 2 input columns. The modified file is saved at the same folder location as the old one." }, { "code": null, "e": 1497, "s": 1190, "text": "#### Importing the required libraryimport pandas as pd#### Reading csv filedf = pd.read_csv(\"C:\\\\Ujjwal\\\\New_File_V1.csv\")#### Adding 2 columnsdf[\"Third_Column\"] = df[\"Randome Numbers 1\"] + df[\"Random Numbers 2\"]#### Exporting the data to same locationdf.to_csv(\"C:\\\\Ujjwal\\\\New_File_V2.csv\",index = False)" }, { "code": null, "e": 1550, "s": 1497, "text": "Sample columns of the input CSV file are as follows:" }, { "code": null, "e": 1609, "s": 1550, "text": "The output file after the code execution looks like below:" }, { "code": null, "e": 1763, "s": 1609, "text": "To convert the Python code into an executable file, we will be using Pyinstaller package. Use the standard ‘pip install’ command to install this package." }, { "code": null, "e": 1807, "s": 1763, "text": "#### Install Commandpip install pyinstaller" }, { "code": null, "e": 1881, "s": 1807, "text": "Let’s go step by step to convert the Python file to a Windows executable:" }, { "code": null, "e": 2117, "s": 1881, "text": "Open the command prompt— The conversion of the Python script to Windows executable is done using the command line. For this purpose, we have to go to the command prompt. Type “cmd” in your Windows search box and open the command prompt" }, { "code": null, "e": 2235, "s": 2117, "text": "Change folder location — Use the following command and direct the command prompt to the location of your Python code:" }, { "code": null, "e": 2281, "s": 2235, "text": "#### Change Folder Locationcd folder_location" }, { "code": null, "e": 2373, "s": 2281, "text": "Conversion— Use the following command to convert the Python file into a Windows executable:" }, { "code": null, "e": 2431, "s": 2373, "text": "#### Command for conversionpyinstaller --onefile filename" }, { "code": null, "e": 2661, "s": 2431, "text": "The above code will create a single executable file with the same functionality as your python code. The executable file will be available in a new folder, dist, which will be available at the same location as your Python script." }, { "code": null, "e": 2787, "s": 2661, "text": "Execution — To execute the file, just double click the executable and it will produce the same results as your Python script." }, { "code": null, "e": 2916, "s": 2787, "text": "There are some common questions/challenges faced by people when working with pyinstaller. This section will answer most of them:" }, { "code": null, "e": 3222, "s": 2916, "text": "Apart from the dist folder, which contains the executable file, other files and folders are getting created. You don’t need them. You can share your executable file without these additional files. Even when you will delete the additional files and folders, your executable will not lose its functionality." }, { "code": null, "e": 3450, "s": 3222, "text": "Both, creation of the executable file and execution of the executable file is a time-consuming task. For a short script like ours, the creation of the executable took close to 5 mins and the execution takes close to 30 seconds." }, { "code": null, "e": 3693, "s": 3450, "text": "Since we are importing packages in our Python script, to make the executable self-sufficient, the complete package gets incorporated in the executable file. This increases the size of the executable file. For our case, it was more than 300 MB" }, { "code": null, "e": 3901, "s": 3693, "text": "The most common error which one can face when executing the executable file is “ModuleNotFoundError: No module named module name”. A sample screenshot of this error and the actual error prompt is as follows:" }, { "code": null, "e": 3995, "s": 3901, "text": "#### Error Prompt MessageModuleNotFoundError: No module named 'pandas._libs.tslibs.nattypes' " }, { "code": null, "e": 4093, "s": 3995, "text": "If you encounter an error like this (module name can be different) then take the following steps:" }, { "code": null, "e": 4248, "s": 4093, "text": "Go to the Windows location where the pyinstaller package is installed. Since I am using Anaconda distribution, the following is the location on my system:" }, { "code": null, "e": 4313, "s": 4248, "text": "#### Package LocationC:\\Users\\Ujjwal\\Anaconda3\\Lib\\site-packages" }, { "code": null, "e": 4616, "s": 4313, "text": "In the pyinstaller package folder, search for the folder named hooks. This folder has hook files for most of the commonly used Python packages. Search for the hook file, for the Python package, which has raised the error. In our case it was Pandas. The sample hook file and its contents are as follows:" }, { "code": null, "e": 4959, "s": 4616, "text": "The reason behind the error is the malfunctioning of the command where ‘hiddenimports’ is getting initialized. Comment this statement and add a new one in which the ‘hiddenimports’ is initialized with the same module name which has raised the error. For our case, it was ‘pandas._libs.tslibs.nattype’. The code line to be added is as follows:" }, { "code": null, "e": 5033, "s": 4959, "text": "#### Code line for hook filehiddenimports = 'pandas._libs.tslibs.nattype'" }, { "code": null, "e": 5360, "s": 5033, "text": "Once the hook file is modified, save it and re-create the new executable. Before recreating, please ensure that the old executable file and associated folders are deleted. If the error persists, continue to add the other missing modules in your hook file. Please note that multiple modules should be added as a list structure." }, { "code": null, "e": 5510, "s": 5360, "text": "#### Code line after adding multiple moduleshiddenimports = ['pandas._libs.tslibs.np_datetime','pandas._libs.tslibs.nattype','pandas._libs.skiplist']" }, { "code": null, "e": 5579, "s": 5510, "text": "The final hook file which we used for our example looked as follows:" }, { "code": null, "e": 5640, "s": 5579, "text": "Once all the modules are added, the error will get resolved." }, { "code": null, "e": 5771, "s": 5640, "text": "In the above tutorial, we have tried addressing a small challenge that most of us have faced at some point in time in our carrier." }, { "code": null, "e": 5839, "s": 5771, "text": "I hope this tutorial was informative and you learned something new." } ]
What is the difference between abstract class and a concrete class in Java?
Following are the notable differences between an abstract class and concrete class. Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); ) But, if a class has at least one abstract method, then the class must be declared abstract. You cannot instantiate an abstract class. An abstract class may contain abstract methods. You need to inherit an abstract class to use it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. public abstract class AbstractExample { public abstract int add(int a, int b); public abstract int subtract(); public void display(){ System.out.println("Hello how are you"); } } You can instantiate a concrete class. A concrete class doesn’t have any abstract methods. It is not mandatory to inherit a concrete class to use it. Live Demo public class ConcreteClassExample { public int add(int a, int b){ int c = a + b; return c; } public int subtract(int a, int b){ int c = a - b; return c; } public void display(){ System.out.println("Hi welcome to Tutorialspoint"); } public static void main(String args[]){ ConcreteClassExample obj = new ConcreteClassExample(); System.out.println(obj.add(25, 347)); System.out.println(obj.subtract(500, 456)); obj.display(); } } 372 44 Hi welcome to Tutorialspoint
[ { "code": null, "e": 1146, "s": 1062, "text": "Following are the notable differences between an abstract class and concrete class." }, { "code": null, "e": 1254, "s": 1146, "text": "Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )" }, { "code": null, "e": 1346, "s": 1254, "text": "But, if a class has at least one abstract method, then the class must be declared abstract." }, { "code": null, "e": 1388, "s": 1346, "text": "You cannot instantiate an abstract class." }, { "code": null, "e": 1436, "s": 1388, "text": "An abstract class may contain abstract methods." }, { "code": null, "e": 1485, "s": 1436, "text": "You need to inherit an abstract class to use it." }, { "code": null, "e": 1590, "s": 1485, "text": "If you inherit an abstract class, you have to provide implementations to all the abstract methods in it." }, { "code": null, "e": 1791, "s": 1590, "text": "public abstract class AbstractExample {\n public abstract int add(int a, int b);\n public abstract int subtract();\n \n public void display(){\n System.out.println(\"Hello how are you\");\n }\n}" }, { "code": null, "e": 1829, "s": 1791, "text": "You can instantiate a concrete class." }, { "code": null, "e": 1881, "s": 1829, "text": "A concrete class doesn’t have any abstract methods." }, { "code": null, "e": 1940, "s": 1881, "text": "It is not mandatory to inherit a concrete class to use it." }, { "code": null, "e": 1951, "s": 1940, "text": " Live Demo" }, { "code": null, "e": 2464, "s": 1951, "text": "public class ConcreteClassExample {\n public int add(int a, int b){\n int c = a + b;\n return c;\n }\n public int subtract(int a, int b){\n int c = a - b;\n return c;\n }\n public void display(){\n System.out.println(\"Hi welcome to Tutorialspoint\");\n }\n public static void main(String args[]){\n ConcreteClassExample obj = new ConcreteClassExample();\n System.out.println(obj.add(25, 347));\n System.out.println(obj.subtract(500, 456));\n \n obj.display();\n }\n}" }, { "code": null, "e": 2501, "s": 2464, "text": "372\n44\nHi welcome to Tutorialspoint\n" } ]
Java Guava | Lists.partition() method with Examples - GeeksforGeeks
04 Feb, 2019 The Lists.partition() method in Guava Library is used to divide the original list into sublists of the same size. The method accepts two parameters. For example: If the original list passed as parameter is [a, b, c, d, e] and the partition size is 3, then the sublists yield are as [[a, b, c], [d, e]]. Syntax: public static <T> List<List<T>> partition(List<T> list, int size) Parameters: The method accepts two parameters: list: The list which is to be divided into sublists based on the partition size. size: The desired size of each sublist. The size of the last sublist may be smaller. Return Value: The method returns the list of consecutive sublists. Each sublist(except possibly the last one) has the size equal to the partition size. Exception: The method Lists.partition() throws IllegalArgumentException if partition size is non-positive. Below examples illustrate the implementation of above method: Example 1: // Java code to show implementation of// Guava's Lists.partition() method import com.google.common.collect.Lists;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a List of Integers List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5); // Using Lists.partition() method to divide // the original list into sublists of the same // size, which are just views of the original list. // The final list may be smaller. List<List<Integer> > lists = Lists.partition(myList, 2); // Displaying the sublists for (List<Integer> sublist: lists) System.out.println(sublist); }} [1, 2] [3, 4] [5] Example 2: // Java code to show implementation of// Guava's Lists.partition() method import com.google.common.collect.Lists;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a List of Characters List<Character> myList = Arrays.asList('H', 'E', 'L', 'L', 'O', 'G', 'E', 'E', 'K', 'S'); // Using Lists.partition() method to divide // the original list into sublists of the same // size, which are just views of the original list. // The final list may be smaller. List<List<Character> > lists = Lists.partition(myList, 3); // Displaying the sublists for (List<Character> sublist: lists) System.out.println(sublist); }} [H, E, L] [L, O, G] [E, E, K] [S] Reference: https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int- Guava-Functions Guava-Lists java-guava Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java Collections in Java Overriding in Java Queue Interface In Java
[ { "code": null, "e": 23859, "s": 23831, "text": "\n04 Feb, 2019" }, { "code": null, "e": 24008, "s": 23859, "text": "The Lists.partition() method in Guava Library is used to divide the original list into sublists of the same size. The method accepts two parameters." }, { "code": null, "e": 24162, "s": 24008, "text": "For example: If the original list passed as parameter is [a, b, c, d, e] and the partition size is 3, then the sublists yield are as [[a, b, c], [d, e]]." }, { "code": null, "e": 24170, "s": 24162, "text": "Syntax:" }, { "code": null, "e": 24236, "s": 24170, "text": "public static <T> List<List<T>> partition(List<T> list, int size)" }, { "code": null, "e": 24283, "s": 24236, "text": "Parameters: The method accepts two parameters:" }, { "code": null, "e": 24364, "s": 24283, "text": "list: The list which is to be divided into sublists based on the partition size." }, { "code": null, "e": 24449, "s": 24364, "text": "size: The desired size of each sublist. The size of the last sublist may be smaller." }, { "code": null, "e": 24601, "s": 24449, "text": "Return Value: The method returns the list of consecutive sublists. Each sublist(except possibly the last one) has the size equal to the partition size." }, { "code": null, "e": 24708, "s": 24601, "text": "Exception: The method Lists.partition() throws IllegalArgumentException if partition size is non-positive." }, { "code": null, "e": 24770, "s": 24708, "text": "Below examples illustrate the implementation of above method:" }, { "code": null, "e": 24781, "s": 24770, "text": "Example 1:" }, { "code": "// Java code to show implementation of// Guava's Lists.partition() method import com.google.common.collect.Lists;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a List of Integers List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5); // Using Lists.partition() method to divide // the original list into sublists of the same // size, which are just views of the original list. // The final list may be smaller. List<List<Integer> > lists = Lists.partition(myList, 2); // Displaying the sublists for (List<Integer> sublist: lists) System.out.println(sublist); }}", "e": 25539, "s": 24781, "text": null }, { "code": null, "e": 25558, "s": 25539, "text": "[1, 2]\n[3, 4]\n[5]\n" }, { "code": null, "e": 25569, "s": 25558, "text": "Example 2:" }, { "code": "// Java code to show implementation of// Guava's Lists.partition() method import com.google.common.collect.Lists;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a List of Characters List<Character> myList = Arrays.asList('H', 'E', 'L', 'L', 'O', 'G', 'E', 'E', 'K', 'S'); // Using Lists.partition() method to divide // the original list into sublists of the same // size, which are just views of the original list. // The final list may be smaller. List<List<Character> > lists = Lists.partition(myList, 3); // Displaying the sublists for (List<Character> sublist: lists) System.out.println(sublist); }}", "e": 26399, "s": 25569, "text": null }, { "code": null, "e": 26434, "s": 26399, "text": "[H, E, L]\n[L, O, G]\n[E, E, K]\n[S]\n" }, { "code": null, "e": 26566, "s": 26434, "text": "Reference: https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-" }, { "code": null, "e": 26582, "s": 26566, "text": "Guava-Functions" }, { "code": null, "e": 26594, "s": 26582, "text": "Guava-Lists" }, { "code": null, "e": 26605, "s": 26594, "text": "java-guava" }, { "code": null, "e": 26610, "s": 26605, "text": "Java" }, { "code": null, "e": 26615, "s": 26610, "text": "Java" }, { "code": null, "e": 26713, "s": 26615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26722, "s": 26713, "text": "Comments" }, { "code": null, "e": 26735, "s": 26722, "text": "Old Comments" }, { "code": null, "e": 26754, "s": 26735, "text": "Interfaces in Java" }, { "code": null, "e": 26786, "s": 26754, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26804, "s": 26786, "text": "ArrayList in Java" }, { "code": null, "e": 26824, "s": 26804, "text": "Stack Class in Java" }, { "code": null, "e": 26856, "s": 26824, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26880, "s": 26856, "text": "Singleton Class in Java" }, { "code": null, "e": 26899, "s": 26880, "text": "LinkedList in Java" }, { "code": null, "e": 26919, "s": 26899, "text": "Collections in Java" }, { "code": null, "e": 26938, "s": 26919, "text": "Overriding in Java" } ]
How to Send and Receive JSON Data to and from the Server
JavaScript can send network requests to the server and load JSON. JS does this using something called AJAX. AJAX stands for Asynchronous JavaScript and XML. JS has an API, fetch, to GET(receive) and POST(send) information to the server. You can use fetch to GET JSON data in the following way − const URL = 'https://jsonplaceholder.typicode.com/todos/1' // Send a GET request without any data to the server fetch(URL, {method: "GET"}) // Get the JSON data from the raw response .then(res => res.json()) // Print the result .then(console.log) This will give the output − { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } You can also POST data to the server using fetch. For example, to create a new todo on the above server, you can post your own data − const URL = 'https://jsonplaceholder.typicode.com/todos' const data = { "userId": 1, "title": "delectus aut autem", "completed": false }; // Send a post request fetch(URL, { method: "POST", body: JSON.stringify(data), headers: { "Content-type": "application/json; charset=UTF-8" } }) This will create a todo on the placeholder API.
[ { "code": null, "e": 1299, "s": 1062, "text": "JavaScript can send network requests to the server and load JSON. JS does this using something called AJAX. AJAX stands for Asynchronous JavaScript and XML. JS has an API, fetch, to GET(receive) and POST(send) information to the server." }, { "code": null, "e": 1357, "s": 1299, "text": "You can use fetch to GET JSON data in the following way −" }, { "code": null, "e": 1610, "s": 1357, "text": "const URL = 'https://jsonplaceholder.typicode.com/todos/1'\n// Send a GET request without any data to the server\nfetch(URL, {method: \"GET\"})\n// Get the JSON data from the raw response\n .then(res => res.json())\n// Print the result\n .then(console.log)" }, { "code": null, "e": 1638, "s": 1610, "text": "This will give the output −" }, { "code": null, "e": 1726, "s": 1638, "text": "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false\n}" }, { "code": null, "e": 1860, "s": 1726, "text": "You can also POST data to the server using fetch. For example, to create\na new todo on the above server, you can post your own data −" }, { "code": null, "e": 2171, "s": 1860, "text": "const URL = 'https://jsonplaceholder.typicode.com/todos'\nconst data = {\n \"userId\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false\n};\n// Send a post request\nfetch(URL, {\n method: \"POST\",\n body: JSON.stringify(data),\n headers: {\n \"Content-type\": \"application/json; charset=UTF-8\"\n }\n})" }, { "code": null, "e": 2219, "s": 2171, "text": "This will create a todo on the placeholder API." } ]
Python | Numpy numpy.transpose() - GeeksforGeeks
07 Mar, 2022 With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass the parameter then you can but it’s not all required. But if you want than remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3) to change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.Returns: ndarray Example #1 : In this example we can see that it’s really easy to transpose an array with just one line. Python3 # importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # before transposeprint(gfg, end ='\n\n') # after transposeprint(gfg.transpose()) [[1 2 3] [4 5 6] [7 8 9]] [[1 4 7] [2 5 8] [3 6 9]] Example #2 : In this example we demonstrate the use of tuples in numpy.transpose(). Python3 # importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2], [4, 5], [7, 8]]) # before transposeprint(gfg, end ='\n\n') # after transposeprint(gfg.transpose(1, 0)) [[1 2] [4 5] [7 8]] [[1 4 7] [2 5 8]] Method 2: Using Numpy ndarray.T object. Python3 # importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # before transposeprint(gfg, end ='\n\n') # after transposeprint(gfg.T) [[1 2 3] [4 5 6] [7 8 9]] [[1 4 7] [2 5 8] [3 6 9]] pulamolusaimohan Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 25084, "s": 25056, "text": "\n07 Mar, 2022" }, { "code": null, "e": 25360, "s": 25084, "text": "With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. " }, { "code": null, "e": 25669, "s": 25360, "text": "Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass the parameter then you can but it’s not all required. But if you want than remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3) to change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.Returns: ndarray " }, { "code": null, "e": 25774, "s": 25669, "text": "Example #1 : In this example we can see that it’s really easy to transpose an array with just one line. " }, { "code": null, "e": 25782, "s": 25774, "text": "Python3" }, { "code": "# importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # before transposeprint(gfg, end ='\\n\\n') # after transposeprint(gfg.transpose())", "e": 26020, "s": 25782, "text": null }, { "code": null, "e": 26077, "s": 26020, "text": "[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[[1 4 7]\n [2 5 8]\n [3 6 9]]" }, { "code": null, "e": 26164, "s": 26079, "text": "Example #2 : In this example we demonstrate the use of tuples in numpy.transpose(). " }, { "code": null, "e": 26172, "s": 26164, "text": "Python3" }, { "code": "# importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2], [4, 5], [7, 8]]) # before transposeprint(gfg, end ='\\n\\n') # after transposeprint(gfg.transpose(1, 0))", "e": 26405, "s": 26172, "text": null }, { "code": null, "e": 26447, "s": 26405, "text": "[[1 2]\n [4 5]\n [7 8]]\n\n[[1 4 7]\n [2 5 8]]" }, { "code": null, "e": 26490, "s": 26449, "text": "Method 2: Using Numpy ndarray.T object." }, { "code": null, "e": 26498, "s": 26490, "text": "Python3" }, { "code": "# importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # before transposeprint(gfg, end ='\\n\\n') # after transposeprint(gfg.T)", "e": 26732, "s": 26498, "text": null }, { "code": null, "e": 26789, "s": 26732, "text": "[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[[1 4 7]\n [2 5 8]\n [3 6 9]]" }, { "code": null, "e": 26806, "s": 26789, "text": "pulamolusaimohan" }, { "code": null, "e": 26819, "s": 26806, "text": "Python-numpy" }, { "code": null, "e": 26826, "s": 26819, "text": "Python" }, { "code": null, "e": 26924, "s": 26826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26933, "s": 26924, "text": "Comments" }, { "code": null, "e": 26946, "s": 26933, "text": "Old Comments" }, { "code": null, "e": 26964, "s": 26946, "text": "Python Dictionary" }, { "code": null, "e": 26999, "s": 26964, "text": "Read a file line by line in Python" }, { "code": null, "e": 27021, "s": 26999, "text": "Enumerate() in Python" }, { "code": null, "e": 27051, "s": 27021, "text": "Iterate over a list in Python" }, { "code": null, "e": 27083, "s": 27051, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27125, "s": 27083, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27151, "s": 27125, "text": "Python String | replace()" }, { "code": null, "e": 27188, "s": 27151, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27231, "s": 27188, "text": "Python program to convert a list to string" } ]
Implementation of Least Recently Used (LRU) page replacement algorithm using Counters - GeeksforGeeks
02 Dec, 2019 Prerequisite – Least Recently Used (LRU) Page Replacement algorithmLeast Recently Used page replacement algorithm replaces the page which is not used recently. Implementation:In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference array. A vector of pair is used to represent the page frames, the 1’st variable of the pair is the page number and the second variable is the current time. When a new page is to be inserted and the frames are full, the page with minimum ctime is deleted (as it is the least recently used page). If the page is accessed again the value of ctime is updated. Note:Least ctime (counter / current time) value represents the least recently used page. Examples: Reference array is : 0, 0, 0, 2, 3, 0, 5, 7, 1, 2, 0, 8 Output : When the number of frames is : 3 The number of page faults are : 9 Reference array is : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 0, 0 Output : When the number of frames is : 3 The number of page faults are : 15 Code: #include <bits/stdc++.h> using namespace std; // To calculate the number of page faultsvoid pageFaults(int frame_size, int* ref, int len, int ctime){ // Count variable to count the // number of page faults int cnt = 0; // Arr to simulate frames vector<pair<int, int> > arr; // To initialise the array for (int i = 0; i < frame_size; i++) { arr.push_back(make_pair(-1, ctime)); } int page; for (int i = 0; i < len; i++) { page = ref[i]; auto it = arr.begin(); for (it = arr.begin(); it != arr.end(); it++) { if (it->first == page) { break; } } // If page is found if (it != arr.end()) { // update the value of // current time it->second = ctime; } // If page is not found else { // Find the page with min value of ctime, // as it will be the least recently used vector<pair<int, int> >::iterator pos; pos = arr.begin(); int min = pos->second; for (auto itr = arr.begin(); itr != arr.end(); itr++) { if (itr->second < min) { pos = itr; min = pos->second; } } // Erase this page from the frame vector arr.erase(pos); // Insert the new page arr.push_back(make_pair(page, ctime)); cnt++; } ctime++; } cout << "The number of page faults is : " << cnt << endl;} int main(){ // This is the reference array int ref[] = { 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 }; int len = sizeof(ref) / sizeof(ref[0]); int frame_size = 3; // Ctime represents current time, // it is incremented for every page int ctime = 0; pageFaults(frame_size, ref, len, ctime);} The number of page faults is : 10 Operating Systems-Memory Management Greedy Operating Systems Operating Systems Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Job Sequencing Problem Difference between Prim's and Kruskal's algorithm for MST Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm Banker's Algorithm in Operating System Types of Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 25689, "s": 25661, "text": "\n02 Dec, 2019" }, { "code": null, "e": 25849, "s": 25689, "text": "Prerequisite – Least Recently Used (LRU) Page Replacement algorithmLeast Recently Used page replacement algorithm replaces the page which is not used recently." }, { "code": null, "e": 26394, "s": 25849, "text": "Implementation:In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference array. A vector of pair is used to represent the page frames, the 1’st variable of the pair is the page number and the second variable is the current time. When a new page is to be inserted and the frames are full, the page with minimum ctime is deleted (as it is the least recently used page). If the page is accessed again the value of ctime is updated." }, { "code": null, "e": 26483, "s": 26394, "text": "Note:Least ctime (counter / current time) value represents the least recently used page." }, { "code": null, "e": 26493, "s": 26483, "text": "Examples:" }, { "code": null, "e": 26772, "s": 26493, "text": "Reference array is : 0, 0, 0, 2, 3, 0, 5, 7, 1, 2, 0, 8\nOutput :\nWhen the number of frames is : 3\nThe number of page faults are : 9\n\nReference array is : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 0, 0\nOutput :\nWhen the number of frames is : 3\nThe number of page faults are : 15 " }, { "code": null, "e": 26778, "s": 26772, "text": "Code:" }, { "code": "#include <bits/stdc++.h> using namespace std; // To calculate the number of page faultsvoid pageFaults(int frame_size, int* ref, int len, int ctime){ // Count variable to count the // number of page faults int cnt = 0; // Arr to simulate frames vector<pair<int, int> > arr; // To initialise the array for (int i = 0; i < frame_size; i++) { arr.push_back(make_pair(-1, ctime)); } int page; for (int i = 0; i < len; i++) { page = ref[i]; auto it = arr.begin(); for (it = arr.begin(); it != arr.end(); it++) { if (it->first == page) { break; } } // If page is found if (it != arr.end()) { // update the value of // current time it->second = ctime; } // If page is not found else { // Find the page with min value of ctime, // as it will be the least recently used vector<pair<int, int> >::iterator pos; pos = arr.begin(); int min = pos->second; for (auto itr = arr.begin(); itr != arr.end(); itr++) { if (itr->second < min) { pos = itr; min = pos->second; } } // Erase this page from the frame vector arr.erase(pos); // Insert the new page arr.push_back(make_pair(page, ctime)); cnt++; } ctime++; } cout << \"The number of page faults is : \" << cnt << endl;} int main(){ // This is the reference array int ref[] = { 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 }; int len = sizeof(ref) / sizeof(ref[0]); int frame_size = 3; // Ctime represents current time, // it is incremented for every page int ctime = 0; pageFaults(frame_size, ref, len, ctime);}", "e": 28648, "s": 26778, "text": null }, { "code": null, "e": 28683, "s": 28648, "text": "The number of page faults is : 10\n" }, { "code": null, "e": 28719, "s": 28683, "text": "Operating Systems-Memory Management" }, { "code": null, "e": 28726, "s": 28719, "text": "Greedy" }, { "code": null, "e": 28744, "s": 28726, "text": "Operating Systems" }, { "code": null, "e": 28762, "s": 28744, "text": "Operating Systems" }, { "code": null, "e": 28769, "s": 28762, "text": "Greedy" }, { "code": null, "e": 28867, "s": 28769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28948, "s": 28867, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 28971, "s": 28948, "text": "Job Sequencing Problem" }, { "code": null, "e": 29029, "s": 28971, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 29100, "s": 29029, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 29168, "s": 29100, "text": "Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm" }, { "code": null, "e": 29207, "s": 29168, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 29234, "s": 29207, "text": "Types of Operating Systems" }, { "code": null, "e": 29274, "s": 29234, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 29301, "s": 29274, "text": "Paging in Operating System" } ]
How to fetch data from MongoDB using Python? - GeeksforGeeks
31 Aug, 2021 MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Pymongo provides various methods for fetching the data from mongodb. Let’s see them one by one. 1) Find One: This method is used to fetch data from collection in mongoDB. It returns first first occurrence. Syntax : find_one() Example: Sample Database: Python3 import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") # Database Namedb = client["database"] # Collection Namecol = db["GeeksForGeeks"] x = col.find_one() print(x) Output : 2) Find All: For all occurrences in the selection use find() method. It works like Select * query of SQL. Syntax : find() Example : Python3 import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") # Database Namedb = client["database"] # Collection Namecol = db["GeeksForGeeks"] x = col.find() for data in x: print(data) Output: 3) Fetching only specific fields: If you want to fetch only some fields then in the find method pass the first parameter as {} and second parameter as 1 for those field that you want to fetch and 0 for those you don’t want to fetch. Syntax: find({},{field_data:bool}) Example: Python3 import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") # Database Namedb = client["database"] # Collection Namecol = db["GeeksForGeeks"] # Fields with values as 1 will# only appear in the resultx = col.find({},{'_id': 0, 'appliance': 1, 'rating': 1, 'company': 1}) for data in x: print(data) Output: kalrap615 Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25339, "s": 25311, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25519, "s": 25339, "text": "MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability." }, { "code": null, "e": 25615, "s": 25519, "text": "Pymongo provides various methods for fetching the data from mongodb. Let’s see them one by one." }, { "code": null, "e": 25734, "s": 25615, "text": "1) Find One: This method is used to fetch data from collection in mongoDB. It returns first first occurrence. Syntax :" }, { "code": null, "e": 25745, "s": 25734, "text": "find_one()" }, { "code": null, "e": 25754, "s": 25745, "text": "Example:" }, { "code": null, "e": 25771, "s": 25754, "text": "Sample Database:" }, { "code": null, "e": 25779, "s": 25771, "text": "Python3" }, { "code": "import pymongo client = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database Namedb = client[\"database\"] # Collection Namecol = db[\"GeeksForGeeks\"] x = col.find_one() print(x)", "e": 25964, "s": 25779, "text": null }, { "code": null, "e": 25973, "s": 25964, "text": "Output :" }, { "code": null, "e": 26090, "s": 25973, "text": "2) Find All: For all occurrences in the selection use find() method. It works like Select * query of SQL. Syntax : " }, { "code": null, "e": 26097, "s": 26090, "text": "find()" }, { "code": null, "e": 26107, "s": 26097, "text": "Example :" }, { "code": null, "e": 26115, "s": 26107, "text": "Python3" }, { "code": "import pymongo client = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database Namedb = client[\"database\"] # Collection Namecol = db[\"GeeksForGeeks\"] x = col.find() for data in x: print(data)", "e": 26317, "s": 26115, "text": null }, { "code": null, "e": 26326, "s": 26317, "text": "Output: " }, { "code": null, "e": 26568, "s": 26326, "text": "3) Fetching only specific fields: If you want to fetch only some fields then in the find method pass the first parameter as {} and second parameter as 1 for those field that you want to fetch and 0 for those you don’t want to fetch. Syntax: " }, { "code": null, "e": 26595, "s": 26568, "text": "find({},{field_data:bool})" }, { "code": null, "e": 26605, "s": 26595, "text": "Example: " }, { "code": null, "e": 26613, "s": 26605, "text": "Python3" }, { "code": "import pymongo client = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database Namedb = client[\"database\"] # Collection Namecol = db[\"GeeksForGeeks\"] # Fields with values as 1 will# only appear in the resultx = col.find({},{'_id': 0, 'appliance': 1, 'rating': 1, 'company': 1}) for data in x: print(data)", "e": 26944, "s": 26613, "text": null }, { "code": null, "e": 26953, "s": 26944, "text": "Output: " }, { "code": null, "e": 26963, "s": 26953, "text": "kalrap615" }, { "code": null, "e": 26978, "s": 26963, "text": "Python-mongoDB" }, { "code": null, "e": 26985, "s": 26978, "text": "Python" }, { "code": null, "e": 27083, "s": 26985, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27101, "s": 27083, "text": "Python Dictionary" }, { "code": null, "e": 27133, "s": 27101, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27155, "s": 27133, "text": "Enumerate() in Python" }, { "code": null, "e": 27197, "s": 27155, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27223, "s": 27197, "text": "Python String | replace()" }, { "code": null, "e": 27252, "s": 27223, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27296, "s": 27252, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27333, "s": 27296, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27375, "s": 27333, "text": "Check if element exists in list in Python" } ]
Angular ng Bootstrap Buttons Component - GeeksforGeeks
06 Jul, 2021 Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article we will know how to use Buttons in angular ng bootstrap. Buttons are used to make a group of buttons. Installation syntax: ng add @ng-bootstrap/ng-bootstrap Approach: First, install the angular ng bootstrap using the above-mentioned command. Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] In app.component.html make a button component. Serve the app using ng serve. Example 1: app.component.html <br/><div class="btn-group btn-group-toggle"> <label class="btn-success" ngbButtonLabel> <input type="checkbox" ngbButton> GeeksforGeeks1 </label> <label class="btn-warning" ngbButtonLabel> <input type="checkbox" ngbButton> GeeksforGeeks2 </label> <label class="btn-danger" ngbButtonLabel> <input type="checkbox" ngbButton> GeeksforGeeks3 </label> <label class="btn-info" ngbButtonLabel> <input type="checkbox" ngbButton> GeeksforGeeks4 </label> <label class="btn-primary" ngbButtonLabel> <input type="checkbox" ngbButton> GeeksforGeeks5 </label> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } Output: Example 2: app.component.html <br/><div class="btn-group btn-group-toggle"> <label class="btn-success" ngbButtonLabel> <input type="radio"> GeeksforGeeks1 </label> <label class="btn-warning" ngbButtonLabel> <input type="radio"> GeeksforGeeks2 </label> <label class="btn-danger" ngbButtonLabel> <input type="radio"> GeeksforGeeks3 </label> <label class="btn-info" ngbButtonLabel> <input type="radio"> GeeksforGeeks4 </label> <label class="btn-primary" ngbButtonLabel> <input type="radio"> GeeksforGeeks5 </label> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } Output: Reference: https://ng-bootstrap.github.io/#/components/buttons/examples Angular-ng-bootstrap AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26538, "s": 26354, "text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites." }, { "code": null, "e": 26656, "s": 26538, "text": "In this article we will know how to use Buttons in angular ng bootstrap. Buttons are used to make a group of buttons." }, { "code": null, "e": 26677, "s": 26656, "text": "Installation syntax:" }, { "code": null, "e": 26711, "s": 26677, "text": "ng add @ng-bootstrap/ng-bootstrap" }, { "code": null, "e": 26721, "s": 26711, "text": "Approach:" }, { "code": null, "e": 26796, "s": 26721, "text": "First, install the angular ng bootstrap using the above-mentioned command." }, { "code": null, "e": 26918, "s": 26796, "text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 27001, "s": 26918, "text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 27048, "s": 27001, "text": "In app.component.html make a button component." }, { "code": null, "e": 27078, "s": 27048, "text": "Serve the app using ng serve." }, { "code": null, "e": 27091, "s": 27080, "text": "Example 1:" }, { "code": null, "e": 27110, "s": 27091, "text": "app.component.html" }, { "code": "<br/><div class=\"btn-group btn-group-toggle\"> <label class=\"btn-success\" ngbButtonLabel> <input type=\"checkbox\" ngbButton> GeeksforGeeks1 </label> <label class=\"btn-warning\" ngbButtonLabel> <input type=\"checkbox\" ngbButton> GeeksforGeeks2 </label> <label class=\"btn-danger\" ngbButtonLabel> <input type=\"checkbox\" ngbButton> GeeksforGeeks3 </label> <label class=\"btn-info\" ngbButtonLabel> <input type=\"checkbox\" ngbButton> GeeksforGeeks4 </label> <label class=\"btn-primary\" ngbButtonLabel> <input type=\"checkbox\" ngbButton> GeeksforGeeks5 </label>", "e": 27700, "s": 27110, "text": null }, { "code": null, "e": 27714, "s": 27700, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 28320, "s": 27714, "text": null }, { "code": null, "e": 28328, "s": 28320, "text": "Output:" }, { "code": null, "e": 28339, "s": 28328, "text": "Example 2:" }, { "code": null, "e": 28358, "s": 28339, "text": "app.component.html" }, { "code": "<br/><div class=\"btn-group btn-group-toggle\"> <label class=\"btn-success\" ngbButtonLabel> <input type=\"radio\"> GeeksforGeeks1 </label> <label class=\"btn-warning\" ngbButtonLabel> <input type=\"radio\"> GeeksforGeeks2 </label> <label class=\"btn-danger\" ngbButtonLabel> <input type=\"radio\"> GeeksforGeeks3 </label> <label class=\"btn-info\" ngbButtonLabel> <input type=\"radio\"> GeeksforGeeks4 </label> <label class=\"btn-primary\" ngbButtonLabel> <input type=\"radio\"> GeeksforGeeks5 </label>", "e": 28880, "s": 28358, "text": null }, { "code": null, "e": 28894, "s": 28880, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 29499, "s": 28894, "text": null }, { "code": null, "e": 29507, "s": 29499, "text": "Output:" }, { "code": null, "e": 29579, "s": 29507, "text": "Reference: https://ng-bootstrap.github.io/#/components/buttons/examples" }, { "code": null, "e": 29600, "s": 29579, "text": "Angular-ng-bootstrap" }, { "code": null, "e": 29610, "s": 29600, "text": "AngularJS" }, { "code": null, "e": 29627, "s": 29610, "text": "Web Technologies" }, { "code": null, "e": 29725, "s": 29627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29760, "s": 29725, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29795, "s": 29760, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29819, "s": 29795, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29854, "s": 29819, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29907, "s": 29854, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29947, "s": 29907, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29980, "s": 29947, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30025, "s": 29980, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30068, "s": 30025, "text": "How to fetch data from an API in ReactJS ?" } ]
Python - Test if String contains any Uppercase character - GeeksforGeeks
11 Oct, 2020 Given a String, Test if it contains any uppercase character. Input : test_str = ‘geeksforgeeks’ Output : False Explanation : No uppercase character in String. Input : test_str = ‘geeksforgEeks’ Output : True Explanation : E is uppercase in String. Method #1 : Using loop + isupper() In this, we iterate for each character in String, check for uppercase using isupper(), if found, String is flagged as True. Python3 # Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using isupper() + loop # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) res = Falsefor ele in test_str: # checking for uppercase character and flagging if ele.isupper(): res = True break # printing resultprint("Does String contain uppercase character : " + str(res)) Output: The original string is : geeksforGeeks Does String contain uppercase character : True Method #2 : Using any() + isupper() In this, we use any() to check for any character if it is a uppercase character. Python3 # Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using any() + isupper() # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # Using any() to check for any element to be uppercaseres = any(ele.isupper() for ele in test_str) # printing resultprint("Does String contain uppercase character : " + str(res)) Output: The original string is : geeksforGeeks Does String contain uppercase character : True Method #3 : Using regex() Appropriate regex can be used to perform this task. This checks for any uppercase in the String. Python3 # Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using re()import re # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # Using regex to check for any element to be uppercaseres = bool(re.match(r'\w*[A-Z]\w*', test_str)) # printing resultprint("Does String contain uppercase character : " + str(res)) Output: The original string is : geeksforGeeks Does String contain uppercase character : True Method #4 : Using any() + ASCII values Checks for each character to be in pool of capital case of ASCII values. Python3 # Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using any() + ASCII values # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # Using ascii values check for any element to be uppercaseres = any(ord(ele) != 32 and ord(ele) <= 64 or ord(ele) >= 91 for ele in test_str) # printing resultprint("Does String contain uppercase character : " + str(res)) Output: The original string is : geeksforGeeks Does String contain uppercase character : True Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26113, "s": 26085, "text": "\n11 Oct, 2020" }, { "code": null, "e": 26174, "s": 26113, "text": "Given a String, Test if it contains any uppercase character." }, { "code": null, "e": 26272, "s": 26174, "text": "Input : test_str = ‘geeksforgeeks’ Output : False Explanation : No uppercase character in String." }, { "code": null, "e": 26362, "s": 26272, "text": "Input : test_str = ‘geeksforgEeks’ Output : True Explanation : E is uppercase in String. " }, { "code": null, "e": 26397, "s": 26362, "text": "Method #1 : Using loop + isupper()" }, { "code": null, "e": 26521, "s": 26397, "text": "In this, we iterate for each character in String, check for uppercase using isupper(), if found, String is flagged as True." }, { "code": null, "e": 26529, "s": 26521, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using isupper() + loop # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) res = Falsefor ele in test_str: # checking for uppercase character and flagging if ele.isupper(): res = True break # printing resultprint(\"Does String contain uppercase character : \" + str(res))", "e": 26989, "s": 26529, "text": null }, { "code": null, "e": 26997, "s": 26989, "text": "Output:" }, { "code": null, "e": 27084, "s": 26997, "text": "The original string is : geeksforGeeks\nDoes String contain uppercase character : True\n" }, { "code": null, "e": 27120, "s": 27084, "text": "Method #2 : Using any() + isupper()" }, { "code": null, "e": 27201, "s": 27120, "text": "In this, we use any() to check for any character if it is a uppercase character." }, { "code": null, "e": 27209, "s": 27201, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using any() + isupper() # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Using any() to check for any element to be uppercaseres = any(ele.isupper() for ele in test_str) # printing resultprint(\"Does String contain uppercase character : \" + str(res))", "e": 27632, "s": 27209, "text": null }, { "code": null, "e": 27640, "s": 27632, "text": "Output:" }, { "code": null, "e": 27727, "s": 27640, "text": "The original string is : geeksforGeeks\nDoes String contain uppercase character : True\n" }, { "code": null, "e": 27753, "s": 27727, "text": "Method #3 : Using regex()" }, { "code": null, "e": 27850, "s": 27753, "text": "Appropriate regex can be used to perform this task. This checks for any uppercase in the String." }, { "code": null, "e": 27858, "s": 27850, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using re()import re # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Using regex to check for any element to be uppercaseres = bool(re.match(r'\\w*[A-Z]\\w*', test_str)) # printing resultprint(\"Does String contain uppercase character : \" + str(res))", "e": 28279, "s": 27858, "text": null }, { "code": null, "e": 28287, "s": 28279, "text": "Output:" }, { "code": null, "e": 28374, "s": 28287, "text": "The original string is : geeksforGeeks\nDoes String contain uppercase character : True\n" }, { "code": null, "e": 28413, "s": 28374, "text": "Method #4 : Using any() + ASCII values" }, { "code": null, "e": 28486, "s": 28413, "text": "Checks for each character to be in pool of capital case of ASCII values." }, { "code": null, "e": 28494, "s": 28486, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if String contains any Uppercase character# Using any() + ASCII values # initializing stringtest_str = 'geeksforGeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Using ascii values check for any element to be uppercaseres = any(ord(ele) != 32 and ord(ele) <= 64 or ord(ele) >= 91 for ele in test_str) # printing resultprint(\"Does String contain uppercase character : \" + str(res))", "e": 28971, "s": 28494, "text": null }, { "code": null, "e": 28979, "s": 28971, "text": "Output:" }, { "code": null, "e": 29066, "s": 28979, "text": "The original string is : geeksforGeeks\nDoes String contain uppercase character : True\n" }, { "code": null, "e": 29089, "s": 29066, "text": "Python string-programs" }, { "code": null, "e": 29096, "s": 29089, "text": "Python" }, { "code": null, "e": 29112, "s": 29096, "text": "Python Programs" }, { "code": null, "e": 29210, "s": 29112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29228, "s": 29210, "text": "Python Dictionary" }, { "code": null, "e": 29263, "s": 29228, "text": "Read a file line by line in Python" }, { "code": null, "e": 29295, "s": 29263, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29317, "s": 29295, "text": "Enumerate() in Python" }, { "code": null, "e": 29359, "s": 29317, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29402, "s": 29359, "text": "Python program to convert a list to string" }, { "code": null, "e": 29424, "s": 29402, "text": "Defaultdict in Python" }, { "code": null, "e": 29463, "s": 29424, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29509, "s": 29463, "text": "Python | Split string into list of characters" } ]
Basic data analysis techniques every data analyst should know, using Python. | by Erfan Nariman | Towards Data Science
In my daily job as a data analyst I see all kinds of data and all kinds of analysis requests from the clients. What I noticed is that certain basic techniques you need in most projects, independent of the type of project you are working on. I’m convinced every data analyst/scientist should have a good understanding of these techniques. So the goal of this article is to take the readers through these techniques and to explain these on a basic level. These are the topics we will go through and discuss: Basic filteringFiltering with multiple conditionsAggregationJoins Basic filtering Filtering with multiple conditions Aggregation Joins For our analysis, we will make use of the pandas library in Python. So if you haven’t installed this library, use one of the following codes in your command prompt to install pandas: # If you use Anaconda, type the following in anaconda promptconda install -c anaconda pandas# If you use pip, type the following in command promptpip install pandas Furthermore I assume you already have a basic knowledge of Python and the pandas library. But no worries if you haven’t touched any of the above, we will go through everything from the bottom up. To be able to go through the mentioned techniques, we need data. We could import a csv file or an excel file, but for now we keep it simple and just create a small dataset with pandas. The following code will generate a pandas dataframe: Which gives us the following dataframe: As can be seen above, it contains ID’s, values and dates. So now we loaded the pandas module and created a dataset, we can start with the first technique. When you want to get a subset of your data based on the values in a column, we are talking about filtering data. In pandas we have multiple ways to do that, for now we look at the most common ones: Using boolean indexing with square brackets []Using boolean indexing with.loc Using boolean indexing with square brackets [] Using boolean indexing with.loc So filtering with square brackets looks as follows: The logic behind filtering in pandas is you pass the condition to the dataframe between the square brackets: df[condition] And gives us the following output: Filtering with .loc looks quite similar: And as expected, it gives us the same output, since we applied the same filter Which one is preferred to use? For basic filters, as we saw above, there’s no difference or preference, it comes down to what you prefer code syntax wise. But when you want to apply more advanced selecting of your data, .loc provides for that and can do more complex selecting and slicing. But that’s not something to worry about right now. We applied our first filter, which was pretty straight forward. But let’s say you want to apply a filter with multiple conditions. How would we do that in pandas? For that we have look at Python operators. 2.1 The & operatorFor example, you want to filter all the rows where ID is equal to C1 and Value is above 100. To apply that filter, we have to chain two conditions with the & operator. That would look like following: And will return the following output: As expected, we get one row back, since only this row met the conditions we set in our filter. 2.2 The | operator The | operator in Python stands for or and will return True if one of the conditions is met. We can show this by applying the following filter: give us all the rows where date is later than 2019–04–10 or Value is greater than 100. In Python code this would look like the following: And will return the following output: As expected all the rows that are returned have a value greater than 100 or have a date after 2019–04–10. Sometimes there’s the need to aggregate data so you can create certain overviews or to do some calculation. In pandas we use groupby for this. So what is groupby exactly? If we quote the pandas documentation: By “group by” we are referring to a process involving one or more of the following steps:* Splitting the data into groups based on some criteria.* Applying a function to each group independently.* Combining the results into a data structure. So basically it’s making groups out of your data based on some indicator, to enable yourself to do some actions on these groups. 3.1 Groupby #1: get total sumLets look at an example. Say we want to get the total value of each group based on ID . This would like like the following in Python code: Which will give us the following output: So if we look at out DataFrame again, we can see that this is correct: For example for ID A1 the total value is 100 + 120 = 220 ,which is correct. 3.2 Groupby #2: get the highest date Pandas provides a big range of function you can use on your groups after using groupby. Let’s look at one more. For example, we can get the highest date per group by using the .max() function. That would look like this: And would give us the following output: Joins are combining two dataframes on a side by side manner based on a common column. Most of the time these columns are referred to askey columns . The term joinis originated from the database language SQL, and was needed because the data modelling of SQL databases is mostly done by using relational modelling. There are many types of joins, and your output will be based on which type of join your perform. Because this is an introductionary tutorial, we will look at the most common one: inner join. In later parts of these series we will look at more complex joins. The inner join is derived from venn diagrams which represents inner (intersection) part of both sets. So when we translate this to our data, an inner join returns the rows which are present in both dataframes. 4.1 Our datasets Because we want to combine two dataframes, we will create new data. These two imaginary dataset represent customers master table and an orders table. With the following code we create two new dataframes: And they look like the following: So one logical analysis we could do on this new data, would be to get the names and city of the customers next to each order in the orders table. This is a typical join problem, matching two dataframes row-wise and enriching the data with more columns. In this case, our key-column is the Customer_ID. In pandas we use the merge method for joining. We will pass the following arguments to this method: Which dataframes you want to join (dfA, dfB).What are the key columns (Customer_ID).Which type of join you want to perform (Inner). Which dataframes you want to join (dfA, dfB). What are the key columns (Customer_ID). Which type of join you want to perform (Inner). There are more arguments we can use in the merge method than the ones listed above, but for now these are sufficient. The merge we want to perform looks like following in pandas: And the output is as we expected, the name and city columns are added next to each corresponding customer_ID. So that was it for this part: basic data analysis techniques every data analyst should know, using Python. You can find the code of this article on my GitHub in the form of a Jupyter Notebook: Link If this article was useful for you, please consider giving this article a like and share this with friends and/or colleagues. For any questions or other discussion, feel free to comment. Find part II here, where we go a bit more advanced.
[ { "code": null, "e": 624, "s": 171, "text": "In my daily job as a data analyst I see all kinds of data and all kinds of analysis requests from the clients. What I noticed is that certain basic techniques you need in most projects, independent of the type of project you are working on. I’m convinced every data analyst/scientist should have a good understanding of these techniques. So the goal of this article is to take the readers through these techniques and to explain these on a basic level." }, { "code": null, "e": 677, "s": 624, "text": "These are the topics we will go through and discuss:" }, { "code": null, "e": 743, "s": 677, "text": "Basic filteringFiltering with multiple conditionsAggregationJoins" }, { "code": null, "e": 759, "s": 743, "text": "Basic filtering" }, { "code": null, "e": 794, "s": 759, "text": "Filtering with multiple conditions" }, { "code": null, "e": 806, "s": 794, "text": "Aggregation" }, { "code": null, "e": 812, "s": 806, "text": "Joins" }, { "code": null, "e": 995, "s": 812, "text": "For our analysis, we will make use of the pandas library in Python. So if you haven’t installed this library, use one of the following codes in your command prompt to install pandas:" }, { "code": null, "e": 1160, "s": 995, "text": "# If you use Anaconda, type the following in anaconda promptconda install -c anaconda pandas# If you use pip, type the following in command promptpip install pandas" }, { "code": null, "e": 1356, "s": 1160, "text": "Furthermore I assume you already have a basic knowledge of Python and the pandas library. But no worries if you haven’t touched any of the above, we will go through everything from the bottom up." }, { "code": null, "e": 1541, "s": 1356, "text": "To be able to go through the mentioned techniques, we need data. We could import a csv file or an excel file, but for now we keep it simple and just create a small dataset with pandas." }, { "code": null, "e": 1594, "s": 1541, "text": "The following code will generate a pandas dataframe:" }, { "code": null, "e": 1634, "s": 1594, "text": "Which gives us the following dataframe:" }, { "code": null, "e": 1692, "s": 1634, "text": "As can be seen above, it contains ID’s, values and dates." }, { "code": null, "e": 1902, "s": 1692, "text": "So now we loaded the pandas module and created a dataset, we can start with the first technique. When you want to get a subset of your data based on the values in a column, we are talking about filtering data." }, { "code": null, "e": 1987, "s": 1902, "text": "In pandas we have multiple ways to do that, for now we look at the most common ones:" }, { "code": null, "e": 2065, "s": 1987, "text": "Using boolean indexing with square brackets []Using boolean indexing with.loc" }, { "code": null, "e": 2112, "s": 2065, "text": "Using boolean indexing with square brackets []" }, { "code": null, "e": 2144, "s": 2112, "text": "Using boolean indexing with.loc" }, { "code": null, "e": 2196, "s": 2144, "text": "So filtering with square brackets looks as follows:" }, { "code": null, "e": 2305, "s": 2196, "text": "The logic behind filtering in pandas is you pass the condition to the dataframe between the square brackets:" }, { "code": null, "e": 2319, "s": 2305, "text": "df[condition]" }, { "code": null, "e": 2354, "s": 2319, "text": "And gives us the following output:" }, { "code": null, "e": 2395, "s": 2354, "text": "Filtering with .loc looks quite similar:" }, { "code": null, "e": 2474, "s": 2395, "text": "And as expected, it gives us the same output, since we applied the same filter" }, { "code": null, "e": 2815, "s": 2474, "text": "Which one is preferred to use? For basic filters, as we saw above, there’s no difference or preference, it comes down to what you prefer code syntax wise. But when you want to apply more advanced selecting of your data, .loc provides for that and can do more complex selecting and slicing. But that’s not something to worry about right now." }, { "code": null, "e": 3021, "s": 2815, "text": "We applied our first filter, which was pretty straight forward. But let’s say you want to apply a filter with multiple conditions. How would we do that in pandas? For that we have look at Python operators." }, { "code": null, "e": 3132, "s": 3021, "text": "2.1 The & operatorFor example, you want to filter all the rows where ID is equal to C1 and Value is above 100." }, { "code": null, "e": 3239, "s": 3132, "text": "To apply that filter, we have to chain two conditions with the & operator. That would look like following:" }, { "code": null, "e": 3277, "s": 3239, "text": "And will return the following output:" }, { "code": null, "e": 3372, "s": 3277, "text": "As expected, we get one row back, since only this row met the conditions we set in our filter." }, { "code": null, "e": 3391, "s": 3372, "text": "2.2 The | operator" }, { "code": null, "e": 3484, "s": 3391, "text": "The | operator in Python stands for or and will return True if one of the conditions is met." }, { "code": null, "e": 3622, "s": 3484, "text": "We can show this by applying the following filter: give us all the rows where date is later than 2019–04–10 or Value is greater than 100." }, { "code": null, "e": 3673, "s": 3622, "text": "In Python code this would look like the following:" }, { "code": null, "e": 3711, "s": 3673, "text": "And will return the following output:" }, { "code": null, "e": 3817, "s": 3711, "text": "As expected all the rows that are returned have a value greater than 100 or have a date after 2019–04–10." }, { "code": null, "e": 3960, "s": 3817, "text": "Sometimes there’s the need to aggregate data so you can create certain overviews or to do some calculation. In pandas we use groupby for this." }, { "code": null, "e": 4026, "s": 3960, "text": "So what is groupby exactly? If we quote the pandas documentation:" }, { "code": null, "e": 4268, "s": 4026, "text": "By “group by” we are referring to a process involving one or more of the following steps:* Splitting the data into groups based on some criteria.* Applying a function to each group independently.* Combining the results into a data structure." }, { "code": null, "e": 4397, "s": 4268, "text": "So basically it’s making groups out of your data based on some indicator, to enable yourself to do some actions on these groups." }, { "code": null, "e": 4565, "s": 4397, "text": "3.1 Groupby #1: get total sumLets look at an example. Say we want to get the total value of each group based on ID . This would like like the following in Python code:" }, { "code": null, "e": 4606, "s": 4565, "text": "Which will give us the following output:" }, { "code": null, "e": 4677, "s": 4606, "text": "So if we look at out DataFrame again, we can see that this is correct:" }, { "code": null, "e": 4753, "s": 4677, "text": "For example for ID A1 the total value is 100 + 120 = 220 ,which is correct." }, { "code": null, "e": 4790, "s": 4753, "text": "3.2 Groupby #2: get the highest date" }, { "code": null, "e": 4983, "s": 4790, "text": "Pandas provides a big range of function you can use on your groups after using groupby. Let’s look at one more. For example, we can get the highest date per group by using the .max() function." }, { "code": null, "e": 5010, "s": 4983, "text": "That would look like this:" }, { "code": null, "e": 5050, "s": 5010, "text": "And would give us the following output:" }, { "code": null, "e": 5199, "s": 5050, "text": "Joins are combining two dataframes on a side by side manner based on a common column. Most of the time these columns are referred to askey columns ." }, { "code": null, "e": 5363, "s": 5199, "text": "The term joinis originated from the database language SQL, and was needed because the data modelling of SQL databases is mostly done by using relational modelling." }, { "code": null, "e": 5621, "s": 5363, "text": "There are many types of joins, and your output will be based on which type of join your perform. Because this is an introductionary tutorial, we will look at the most common one: inner join. In later parts of these series we will look at more complex joins." }, { "code": null, "e": 5831, "s": 5621, "text": "The inner join is derived from venn diagrams which represents inner (intersection) part of both sets. So when we translate this to our data, an inner join returns the rows which are present in both dataframes." }, { "code": null, "e": 5848, "s": 5831, "text": "4.1 Our datasets" }, { "code": null, "e": 5998, "s": 5848, "text": "Because we want to combine two dataframes, we will create new data. These two imaginary dataset represent customers master table and an orders table." }, { "code": null, "e": 6052, "s": 5998, "text": "With the following code we create two new dataframes:" }, { "code": null, "e": 6086, "s": 6052, "text": "And they look like the following:" }, { "code": null, "e": 6388, "s": 6086, "text": "So one logical analysis we could do on this new data, would be to get the names and city of the customers next to each order in the orders table. This is a typical join problem, matching two dataframes row-wise and enriching the data with more columns. In this case, our key-column is the Customer_ID." }, { "code": null, "e": 6488, "s": 6388, "text": "In pandas we use the merge method for joining. We will pass the following arguments to this method:" }, { "code": null, "e": 6620, "s": 6488, "text": "Which dataframes you want to join (dfA, dfB).What are the key columns (Customer_ID).Which type of join you want to perform (Inner)." }, { "code": null, "e": 6666, "s": 6620, "text": "Which dataframes you want to join (dfA, dfB)." }, { "code": null, "e": 6706, "s": 6666, "text": "What are the key columns (Customer_ID)." }, { "code": null, "e": 6754, "s": 6706, "text": "Which type of join you want to perform (Inner)." }, { "code": null, "e": 6872, "s": 6754, "text": "There are more arguments we can use in the merge method than the ones listed above, but for now these are sufficient." }, { "code": null, "e": 6933, "s": 6872, "text": "The merge we want to perform looks like following in pandas:" }, { "code": null, "e": 7043, "s": 6933, "text": "And the output is as we expected, the name and city columns are added next to each corresponding customer_ID." }, { "code": null, "e": 7150, "s": 7043, "text": "So that was it for this part: basic data analysis techniques every data analyst should know, using Python." }, { "code": null, "e": 7241, "s": 7150, "text": "You can find the code of this article on my GitHub in the form of a Jupyter Notebook: Link" }, { "code": null, "e": 7367, "s": 7241, "text": "If this article was useful for you, please consider giving this article a like and share this with friends and/or colleagues." }, { "code": null, "e": 7428, "s": 7367, "text": "For any questions or other discussion, feel free to comment." } ]
Construct a simple HTTP request on TCP protocol - GeeksforGeeks
01 Feb, 2022 HTTP Request : HTTP messages are how data is exchanged between a server and a client. In this, there are two types of messages where one is HTTP client request and the second is the response from the server. Messages in textual form and it is encoded in ASCII form, and span over multiple lines. And messages were openly sent across the connection in the case of HTTP/1.1 and earlier versions of the protocol. In HTTP/2, the once human-readable message is now divided up into HTTP frames, providing optimization and performance improvements. Let’s now see the components of an HTTP request & response by actually creating one. The telnet client helps us connect to other computers on the internet. The format is telnet, hostname, and port. Note – You can also use this online telnet client. Opening a TCP connection to server via telnet Steps to Construct a simple HTTP request on TCP protocol : Step-1 : The default port for HTTP is 80 and the telnet command has us connected to the HTTP port on the geeksforgeeks.org server. We can start sending HTTP requests to the server now. Step-2 : How do we create an HTTP request? Let’s check the HTTP protocol definition doc here to get an idea of how to frame an HTTP request. Request : A request message from a client to server includes, within the first line of that message, the method to be applied to the resource, the identifier of the resource, and the protocol version in use. Request = Request-Line *(( general-header | request-header | entity-header ) CRLF ) CRLF [ message-body ] Request-Line : The Request-Line begins with a method token, followed by the Request-URL and the protocol version, and ending the CRLF.The elements are separated by SP characters. No CR or LF is allowed except in the final CRLF sequence. Request-Line = Method SP Request-URI SP HTTP_Version CRLF HTTP Request specification : Below given is the screenshot for your reference that shows the HTTP request specification. HTTP Request-Response components : From the above figure, different parts of the HTTP communication are: Request Line (HTTP Request) Status Line & Response Header (HTTP Response) Response Body (HTTP Response) Try to figure out what some of these response headers mean & what their uses are – for starters, see Last-Modified, Content-Length, Content-Type If we analyze the network packets transferred to/from our computer during the above communication, we’ll be able to understand some things (192.168.43.197 is the client computer & 192.241.136.170, the server) The client initiates a TCP connection request to the server (Line 1) – this is performed when we execute the telnet command HTTP’s communication happens using this established TCP connection (see the bottom part that lists outs the protocols used for the resource transfer) The client sends the HTTP Request line to the server (Line 6) to which the server responds with the HTTP Status code & data as we saw earlier in the telnet output Note – We can also analyze Network packets using Wire shark this will be done by you. singghakshay sweetyty http Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Stop and Wait ARQ Block Cipher modes of Operation Digital Signatures and Certificates Multiple Access Protocols in Computer Network Cryptography and its Types Routing Information Protocol (RIP) TCP Congestion Control
[ { "code": null, "e": 24430, "s": 24402, "text": "\n01 Feb, 2022" }, { "code": null, "e": 24445, "s": 24430, "text": "HTTP Request :" }, { "code": null, "e": 24638, "s": 24445, "text": "HTTP messages are how data is exchanged between a server and a client. In this, there are two types of messages where one is HTTP client request and the second is the response from the server." }, { "code": null, "e": 24972, "s": 24638, "text": "Messages in textual form and it is encoded in ASCII form, and span over multiple lines. And messages were openly sent across the connection in the case of HTTP/1.1 and earlier versions of the protocol. In HTTP/2, the once human-readable message is now divided up into HTTP frames, providing optimization and performance improvements." }, { "code": null, "e": 25170, "s": 24972, "text": "Let’s now see the components of an HTTP request & response by actually creating one. The telnet client helps us connect to other computers on the internet. The format is telnet, hostname, and port." }, { "code": null, "e": 25178, "s": 25170, "text": "Note – " }, { "code": null, "e": 25222, "s": 25178, "text": "You can also use this online telnet client." }, { "code": null, "e": 25268, "s": 25222, "text": "Opening a TCP connection to server via telnet" }, { "code": null, "e": 25327, "s": 25268, "text": "Steps to Construct a simple HTTP request on TCP protocol :" }, { "code": null, "e": 25336, "s": 25327, "text": "Step-1 :" }, { "code": null, "e": 25512, "s": 25336, "text": "The default port for HTTP is 80 and the telnet command has us connected to the HTTP port on the geeksforgeeks.org server. We can start sending HTTP requests to the server now." }, { "code": null, "e": 25521, "s": 25512, "text": "Step-2 :" }, { "code": null, "e": 25653, "s": 25521, "text": "How do we create an HTTP request? Let’s check the HTTP protocol definition doc here to get an idea of how to frame an HTTP request." }, { "code": null, "e": 26441, "s": 25653, "text": "Request :\n A request message from a client to server includes, within the \n first line of that message, the method to be applied to the resource,\n the identifier of the resource, and the protocol version in use.\n \n Request = Request-Line\n *(( general-header\n | request-header\n | entity-header ) CRLF )\n CRLF\n [ message-body ] \n \nRequest-Line : \n The Request-Line begins with a method token, followed by the \n Request-URL and the protocol version, and ending the CRLF.The\n elements are separated by SP characters. No CR or LF is allowed\n except in the final CRLF sequence.\n \n Request-Line = Method SP Request-URI SP HTTP_Version CRLF" }, { "code": null, "e": 26470, "s": 26441, "text": "HTTP Request specification :" }, { "code": null, "e": 26562, "s": 26470, "text": "Below given is the screenshot for your reference that shows the HTTP request specification." }, { "code": null, "e": 26597, "s": 26562, "text": "HTTP Request-Response components :" }, { "code": null, "e": 26667, "s": 26597, "text": "From the above figure, different parts of the HTTP communication are:" }, { "code": null, "e": 26695, "s": 26667, "text": "Request Line (HTTP Request)" }, { "code": null, "e": 26741, "s": 26695, "text": "Status Line & Response Header (HTTP Response)" }, { "code": null, "e": 26771, "s": 26741, "text": "Response Body (HTTP Response)" }, { "code": null, "e": 26916, "s": 26771, "text": "Try to figure out what some of these response headers mean & what their uses are – for starters, see Last-Modified, Content-Length, Content-Type" }, { "code": null, "e": 27125, "s": 26916, "text": "If we analyze the network packets transferred to/from our computer during the above communication, we’ll be able to understand some things (192.168.43.197 is the client computer & 192.241.136.170, the server)" }, { "code": null, "e": 27249, "s": 27125, "text": "The client initiates a TCP connection request to the server (Line 1) – this is performed when we execute the telnet command" }, { "code": null, "e": 27399, "s": 27249, "text": "HTTP’s communication happens using this established TCP connection (see the bottom part that lists outs the protocols used for the resource transfer)" }, { "code": null, "e": 27562, "s": 27399, "text": "The client sends the HTTP Request line to the server (Line 6) to which the server responds with the HTTP Status code & data as we saw earlier in the telnet output" }, { "code": null, "e": 27570, "s": 27562, "text": "Note – " }, { "code": null, "e": 27649, "s": 27570, "text": "We can also analyze Network packets using Wire shark this will be done by you." }, { "code": null, "e": 27662, "s": 27649, "text": "singghakshay" }, { "code": null, "e": 27671, "s": 27662, "text": "sweetyty" }, { "code": null, "e": 27676, "s": 27671, "text": "http" }, { "code": null, "e": 27694, "s": 27676, "text": "Computer Networks" }, { "code": null, "e": 27712, "s": 27694, "text": "Computer Networks" }, { "code": null, "e": 27810, "s": 27712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27819, "s": 27810, "text": "Comments" }, { "code": null, "e": 27832, "s": 27819, "text": "Old Comments" }, { "code": null, "e": 27867, "s": 27832, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27900, "s": 27867, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27938, "s": 27900, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 27956, "s": 27938, "text": "Stop and Wait ARQ" }, { "code": null, "e": 27988, "s": 27956, "text": "Block Cipher modes of Operation" }, { "code": null, "e": 28024, "s": 27988, "text": "Digital Signatures and Certificates" }, { "code": null, "e": 28070, "s": 28024, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 28097, "s": 28070, "text": "Cryptography and its Types" }, { "code": null, "e": 28132, "s": 28097, "text": "Routing Information Protocol (RIP)" } ]
Check whether right angled triangle is valid or not for large sides in Python
Suppose we have three sides in a list. We have to check whether these three sides are forming a right angled triangle or not. So, if the input is like sides = [8, 10, 6], then the output will be True as (8^2 + 6^2) = 10^2. To solve this, we will follow these steps − sort the list sides if (sides[0]^2 + sides[1]^2) is same as sides[2]^2, thenreturn True return True return False Let us see the following implementation to get better understanding − Live Demo def solve(sides): sides.sort() if (sides[0]*sides[0]) + (sides[1]*sides[1]) == (sides[2]*sides[2]): return True return False sides = [8, 10, 6] print(solve(sides)) [8, 10, 6] True
[ { "code": null, "e": 1188, "s": 1062, "text": "Suppose we have three sides in a list. We have to check whether these three sides are forming a right angled triangle or not." }, { "code": null, "e": 1285, "s": 1188, "text": "So, if the input is like sides = [8, 10, 6], then the output will be True as (8^2 + 6^2) = 10^2." }, { "code": null, "e": 1329, "s": 1285, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1349, "s": 1329, "text": "sort the list sides" }, { "code": null, "e": 1417, "s": 1349, "text": "if (sides[0]^2 + sides[1]^2) is same as sides[2]^2, thenreturn True" }, { "code": null, "e": 1429, "s": 1417, "text": "return True" }, { "code": null, "e": 1442, "s": 1429, "text": "return False" }, { "code": null, "e": 1512, "s": 1442, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1522, "s": 1512, "text": "Live Demo" }, { "code": null, "e": 1705, "s": 1522, "text": "def solve(sides):\n sides.sort()\n if (sides[0]*sides[0]) + (sides[1]*sides[1]) == (sides[2]*sides[2]):\n return True\n return False\n \nsides = [8, 10, 6]\nprint(solve(sides))" }, { "code": null, "e": 1717, "s": 1705, "text": "[8, 10, 6]\n" }, { "code": null, "e": 1722, "s": 1717, "text": "True" } ]
Java Methods
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Why use methods? To reuse code: define the code once, and use it many times. A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions: Create a method inside Main: public class Main { static void myMethod() { // code to be executed } } myMethod() is the name of the method static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial. void means that this method does not have a return value. You will learn more about return values later in this chapter To call a method in Java, write the method's name followed by two parentheses () and a semicolon; In the following example, myMethod() is used to print a text (the action), when it is called: Inside main, call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!" Try it Yourself » A method can also be called multiple times: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); myMethod(); myMethod(); } } // I just got executed! // I just got executed! // I just got executed! Try it Yourself » In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a method. Insert the missing part to call myMethod from main. static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { ; } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 63, "s": 0, "text": "A method is a block of code which only runs when it is called." }, { "code": null, "e": 118, "s": 63, "text": "You can pass data, known as parameters, into a method." }, { "code": null, "e": 201, "s": 118, "text": "Methods are used to perform certain actions, and they are also known as functions." }, { "code": null, "e": 279, "s": 201, "text": "Why use methods? To reuse code: define the code once, and use \nit many times." }, { "code": null, "e": 532, "s": 279, "text": "A method must be declared within a class. It is defined \nwith the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:" }, { "code": null, "e": 561, "s": 532, "text": "Create a method inside Main:" }, { "code": null, "e": 644, "s": 561, "text": "public class Main {\n static void myMethod() {\n // code to be executed\n }\n}\n \n" }, { "code": null, "e": 681, "s": 644, "text": "myMethod() is the name of the method" }, { "code": null, "e": 874, "s": 681, "text": "static means that the method belongs to the \nMain class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial." }, { "code": null, "e": 995, "s": 874, "text": "void means that this method does not have a \nreturn value. You will learn more about return values later in this chapter" }, { "code": null, "e": 1094, "s": 995, "text": "To call a method in Java, write the method's name followed by two \nparentheses () and a semicolon;" }, { "code": null, "e": 1188, "s": 1094, "text": "In the following example, myMethod() is used to print a text (the action), when it is called:" }, { "code": null, "e": 1230, "s": 1188, "text": "Inside main, call the \nmyMethod() method:" }, { "code": null, "e": 1433, "s": 1230, "text": "public class Main {\n static void myMethod() {\n System.out.println(\"I just got executed!\");\n }\n\n public static void main(String[] args) {\n myMethod();\n }\n}\n\n// Outputs \"I just got executed!\"\n \n" }, { "code": null, "e": 1453, "s": 1433, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1497, "s": 1453, "text": "A method can also be called multiple times:" }, { "code": null, "e": 1774, "s": 1497, "text": "public class Main {\n static void myMethod() {\n System.out.println(\"I just got executed!\");\n }\n\n public static void main(String[] args) {\n myMethod();\n myMethod();\n myMethod();\n }\n}\n\n// I just got executed!\n// I just got executed!\n// I just got executed!\n \n \n \n" }, { "code": null, "e": 1794, "s": 1774, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1894, "s": 1794, "text": "In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a method." }, { "code": null, "e": 1946, "s": 1894, "text": "Insert the missing part to call myMethod from main." }, { "code": null, "e": 2068, "s": 1946, "text": "static void myMethod() {\n System.out.println(\"I just got executed!\");\n}\n\npublic static void main(String[] args) {\n ;\n}\n" }, { "code": null, "e": 2087, "s": 2068, "text": "Start the Exercise" }, { "code": null, "e": 2120, "s": 2087, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2162, "s": 2120, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2269, "s": 2162, "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": 2288, "s": 2269, "text": "help@w3schools.com" } ]
Bootstrap - Typography
Bootstrap uses Helvetica Neue, Helvetica, Arial, and sans-serif in its default font stack. Using typography feature of Bootstrap you can create headings, paragraphs, lists and other inline elements. Let see learn each one of these in the following sections. All HTML headings (h1 to h6) are styled in Bootstrap. An example is shown below − <h1>I'm Heading1 h1</h1> <h2>I'm Heading2 h2</h2> <h3>I'm Heading3 h3</h3> <h4>I'm Heading4 h4</h4> <h5>I'm Heading5 h5</h5> <h6>I'm Heading6 h6</h6> The above code segment with Bootstrap will produce following result − To add an inline subheading to any of the headings, simply add <small> around any of the elements or add .small class and you will get smaller text in a lighter color as shown in the example below − <h1>I'm Heading1 h1. <small>I'm secondary Heading1 h1</small></h1> <h2>I'm Heading2 h2. <small>I'm secondary Heading2 h2</small></h2> <h3>I'm Heading3 h3. <small>I'm secondary Heading3 h3</small></h3> <h4>I'm Heading4 h4. <small>I'm secondary Heading4 h4</small></h4> <h5>I'm Heading5 h5. <small>I'm secondary Heading5 h5</small></h5> <h6>I'm Heading6 h6. <small>I'm secondary Heading1 h6</small></h6> The above code segment with Bootstrap will produce following result − To add some emphasis to a paragraph, add class = "lead". This will give you a larger font size, lighter weight, and a taller line height as in the following example − <h2>Lead Example</h2> <p class = "lead">This is an example paragraph demonstrating the use of lead body copy. This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy. This is an example paragraph demonstrating the use of lead body copy.</p> This is an example paragraph demonstrating the use of lead body copy. This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy. HTML's default emphasis tags such as <small> sets text at 85% the size of the parent, <strong> emphasizes a text with heavier font-weight, and <em> emphasizes a text in italics. Bootstrap offers a few classes that can be used to provide emphasis on texts as seen in the following example − <small>This content is within tag</small><br> <strong>This content is within tag</strong><br> <em>This content is within tag and is rendered as italics</em><br> <p class = "text-left">Left aligned text.</p> <p class = "text-center">Center aligned text.</p> <p class = "text-right">Right aligned text.</p> <p class = "text-muted">This content is muted</p> <p class = "text-primary">This content carries a primary class</p> <p class = "text-success">This content carries a success class</p> <p class = "text-info">This content carries a info class</p> <p class = "text-warning">This content carries a warning class</p> <p class = "text-danger">This content carries a danger class</p> Left aligned text. Center aligned text. Right aligned text. This content is muted This content carries a primary class This content carries a success class This content carries a info class This content carries a warning class This content carries a danger class The HTML <abbr> element provides markup for abbreviations or acronyms, like WWW or HTTP. Bootstrap styles <abbr> elements with a light dotted border along the bottom and reveals the full text on hover (as long as you add that text to the <abbr> title attribute). To get a a slightly smaller font size add .initialism to <abbr>. <abbr title = "World Wide Web">WWW</abbr><br> <abbr title = "Real Simple Syndication" class = "initialism">RSS</abbr> Using <address> tag you can display the contact information on your web page. Since the <address> defaults to display: block; you’ll need to use Tags to add line breaks to the enclosed address text. <address> <strong>Some Company, Inc.</strong><br> 007 street<br> Some City, State XXXXX<br> <abbr title = "Phone">P:</abbr> (123) 456-7890 </address> <address> <strong>Full Name</strong><br> <a href = "mailto:#">mailto@somedomain.com</a> </address> You can use the default <blockquote> around any HTML text. Other options include, adding a <small> tag for identifying the source of the quote and right-aligning the blockquote using class .pull-right. The following example demonstrates all these features − <blockquote> <p>This is a default blockquote example. This is a default blockquote example. This is a default blockquote example.This is a default blockquote example. This is a default blockquote example.</p> </blockquote> <blockquote> This is a blockquote with a source title. <small>Someone famous in <cite title = "Source Title">Source Title</cite></small> </blockquote> <blockquote class = "pull-right">This is a blockquote aligned to the right. <small>Someone famous in <cite title = "Source Title">Source Title</cite></small> </blockquote> This is a default blockquote example. This is a default blockquote example. This is a default blockquote example.This is a default blockquote example. This is a default blockquote example. Bootstrap supports ordered lists, unordered lists, and definition lists. Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers. Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers. Unordered lists − An unordered list is a list that doesn’t have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear, then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline. Unordered lists − An unordered list is a list that doesn’t have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear, then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline. Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal. Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal. The following example demonstrates each of these types − <h4>Example of Ordered List</h4> <ol> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ol> <h4>Example of UnOrdered List</h4> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <h4>Example of Unstyled List</h4> <ul class = "list-unstyled"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <h4>Example of Inline List</h4> <ul class = "list-inline"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <h4>Example of Definition List</h4> <dl> <dt>Description 1</dt> <dd>Item 1</dd> <dt>Description 2</dt> <dd>Item 2</dd> </dl> <h4>Example of Horizontal Definition List</h4> <dl class = "dl-horizontal"> <dt>Description 1</dt> <dd>Item 1</dd> <dt>Description 2</dt> <dd>Item 2</dd> </dl> Item 1 Item 2 Item 3 Item 4 Item 1 Item 2 Item 3 Item 4 Item 1 Item 2 Item 3 Item 4 Item 1 Item 2 Item 3 Item 4 Item 1 Item 2 Item 3 Item 4 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3589, "s": 3331, "text": "Bootstrap uses Helvetica Neue, Helvetica, Arial, and sans-serif in its default font stack. Using typography feature of Bootstrap you can create headings, paragraphs, lists and other inline elements. Let see learn each one of these in the following sections." }, { "code": null, "e": 3671, "s": 3589, "text": "All HTML headings (h1 to h6) are styled in Bootstrap. An example is shown below −" }, { "code": null, "e": 3821, "s": 3671, "text": "<h1>I'm Heading1 h1</h1>\n<h2>I'm Heading2 h2</h2>\n<h3>I'm Heading3 h3</h3>\n<h4>I'm Heading4 h4</h4>\n<h5>I'm Heading5 h5</h5>\n<h6>I'm Heading6 h6</h6>" }, { "code": null, "e": 3891, "s": 3821, "text": "The above code segment with Bootstrap will produce following result −" }, { "code": null, "e": 4090, "s": 3891, "text": "To add an inline subheading to any of the headings, simply add <small> around any of the elements or add .small class and you will get smaller text in a lighter color as shown in the example below −" }, { "code": null, "e": 4493, "s": 4090, "text": "<h1>I'm Heading1 h1. <small>I'm secondary Heading1 h1</small></h1> \n<h2>I'm Heading2 h2. <small>I'm secondary Heading2 h2</small></h2>\n<h3>I'm Heading3 h3. <small>I'm secondary Heading3 h3</small></h3>\n<h4>I'm Heading4 h4. <small>I'm secondary Heading4 h4</small></h4>\n<h5>I'm Heading5 h5. <small>I'm secondary Heading5 h5</small></h5>\n<h6>I'm Heading6 h6. <small>I'm secondary Heading1 h6</small></h6>" }, { "code": null, "e": 4563, "s": 4493, "text": "The above code segment with Bootstrap will produce following result −" }, { "code": null, "e": 4730, "s": 4563, "text": "To add some emphasis to a paragraph, add class = \"lead\". This will give you a larger font size, lighter weight, and a taller line height as in the following example −" }, { "code": null, "e": 5141, "s": 4730, "text": "<h2>Lead Example</h2>\n<p class = \"lead\">This is an example paragraph demonstrating \n the use of lead body copy. This is an example paragraph \n demonstrating the use of lead body copy.This is an example \n paragraph demonstrating the use of lead body copy.This is an \n example paragraph demonstrating the use of lead body copy.\n This is an example paragraph demonstrating the use of lead body copy.</p>" }, { "code": null, "e": 5488, "s": 5141, "text": "This is an example paragraph demonstrating the use of lead body copy. This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy.This is an example paragraph demonstrating the use of lead body copy." }, { "code": null, "e": 5666, "s": 5488, "text": "HTML's default emphasis tags such as <small> sets text at 85% the size of the parent, <strong> emphasizes a text with heavier font-weight, and <em> emphasizes a text in italics." }, { "code": null, "e": 5778, "s": 5666, "text": "Bootstrap offers a few classes that can be used to provide emphasis on texts as seen in the following example −" }, { "code": null, "e": 6461, "s": 5778, "text": "<small>This content is within tag</small><br>\n<strong>This content is within tag</strong><br>\n<em>This content is within tag and is rendered as italics</em><br>\n\n<p class = \"text-left\">Left aligned text.</p>\n<p class = \"text-center\">Center aligned text.</p>\n<p class = \"text-right\">Right aligned text.</p>\n<p class = \"text-muted\">This content is muted</p>\n<p class = \"text-primary\">This content carries a primary class</p>\n<p class = \"text-success\">This content carries a success class</p>\n<p class = \"text-info\">This content carries a info class</p>\n<p class = \"text-warning\">This content carries a warning class</p>\n<p class = \"text-danger\">This content carries a danger class</p>" }, { "code": null, "e": 6480, "s": 6461, "text": "Left aligned text." }, { "code": null, "e": 6501, "s": 6480, "text": "Center aligned text." }, { "code": null, "e": 6521, "s": 6501, "text": "Right aligned text." }, { "code": null, "e": 6543, "s": 6521, "text": "This content is muted" }, { "code": null, "e": 6580, "s": 6543, "text": "This content carries a primary class" }, { "code": null, "e": 6617, "s": 6580, "text": "This content carries a success class" }, { "code": null, "e": 6651, "s": 6617, "text": "This content carries a info class" }, { "code": null, "e": 6688, "s": 6651, "text": "This content carries a warning class" }, { "code": null, "e": 6724, "s": 6688, "text": "This content carries a danger class" }, { "code": null, "e": 7052, "s": 6724, "text": "The HTML <abbr> element provides markup for abbreviations or acronyms, like WWW or HTTP. Bootstrap styles <abbr> elements with a light dotted border along the bottom and reveals the full text on hover (as long as you add that text to the <abbr> title attribute). To get a a slightly smaller font size add .initialism to <abbr>." }, { "code": null, "e": 7170, "s": 7052, "text": "<abbr title = \"World Wide Web\">WWW</abbr><br>\n<abbr title = \"Real Simple Syndication\" class = \"initialism\">RSS</abbr>" }, { "code": null, "e": 7315, "s": 7170, "text": "Using <address> tag you can display the contact information on your web page. Since the <address> defaults to display: block; you’ll need to use" }, { "code": null, "e": 7369, "s": 7315, "text": "Tags to add line breaks to the enclosed address text." }, { "code": null, "e": 7637, "s": 7369, "text": "<address>\n <strong>Some Company, Inc.</strong><br>\n 007 street<br>\n Some City, State XXXXX<br>\n <abbr title = \"Phone\">P:</abbr> (123) 456-7890\n</address>\n\n<address>\n <strong>Full Name</strong><br>\n <a href = \"mailto:#\">mailto@somedomain.com</a>\n</address>" }, { "code": null, "e": 7896, "s": 7637, "text": "You can use the default <blockquote> around any HTML text. Other options include, adding a <small> tag for identifying the source of the quote and right-aligning the blockquote using class .pull-right. The following example demonstrates all these features −" }, { "code": null, "e": 8477, "s": 7896, "text": "<blockquote>\n <p>This is a default blockquote example. This is a default \n blockquote example. This is a default blockquote \n example.This is a default blockquote example. This is a \n default blockquote example.</p>\n</blockquote>\n\n<blockquote>\n This is a blockquote with a source title.\n <small>Someone famous in <cite title = \"Source Title\">Source Title</cite></small>\n</blockquote>\n\n<blockquote class = \"pull-right\">This is a blockquote aligned to the right.\n <small>Someone famous in <cite title = \"Source Title\">Source Title</cite></small>\n</blockquote>" }, { "code": null, "e": 8673, "s": 8477, "text": "\n This is a default blockquote example. This is a default blockquote example. This is a default blockquote example.This is a default blockquote example. This is a default blockquote example." }, { "code": null, "e": 8746, "s": 8673, "text": "Bootstrap supports ordered lists, unordered lists, and definition lists." }, { "code": null, "e": 8860, "s": 8746, "text": "Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers." }, { "code": null, "e": 8974, "s": 8860, "text": "Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers." }, { "code": null, "e": 9291, "s": 8974, "text": "Unordered lists − An unordered list is a list that doesn’t have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear, then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline." }, { "code": null, "e": 9608, "s": 9291, "text": "Unordered lists − An unordered list is a list that doesn’t have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear, then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline." }, { "code": null, "e": 9970, "s": 9608, "text": "Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal." }, { "code": null, "e": 10332, "s": 9970, "text": "Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal." }, { "code": null, "e": 10389, "s": 10332, "text": "The following example demonstrates each of these types −" }, { "code": null, "e": 11236, "s": 10389, "text": "<h4>Example of Ordered List</h4>\n<ol>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n</ol>\n\n<h4>Example of UnOrdered List</h4>\n\n<ul>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n</ul>\n\n<h4>Example of Unstyled List</h4>\n\n<ul class = \"list-unstyled\">\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n</ul>\n\n<h4>Example of Inline List</h4>\n\n<ul class = \"list-inline\">\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n</ul>\n\n<h4>Example of Definition List</h4>\n\n<dl>\n <dt>Description 1</dt>\n <dd>Item 1</dd>\n <dt>Description 2</dt>\n <dd>Item 2</dd>\n</dl>\n\n<h4>Example of Horizontal Definition List</h4>\n\n<dl class = \"dl-horizontal\">\n <dt>Description 1</dt>\n <dd>Item 1</dd>\n <dt>Description 2</dt>\n <dd>Item 2</dd>\n</dl>" }, { "code": null, "e": 11266, "s": 11236, "text": "\nItem 1\nItem 2\nItem 3\nItem 4\n" }, { "code": null, "e": 11273, "s": 11266, "text": "Item 1" }, { "code": null, "e": 11280, "s": 11273, "text": "Item 2" }, { "code": null, "e": 11287, "s": 11280, "text": "Item 3" }, { "code": null, "e": 11294, "s": 11287, "text": "Item 4" }, { "code": null, "e": 11301, "s": 11294, "text": "Item 1" }, { "code": null, "e": 11308, "s": 11301, "text": "Item 2" }, { "code": null, "e": 11315, "s": 11308, "text": "Item 3" }, { "code": null, "e": 11322, "s": 11315, "text": "Item 4" }, { "code": null, "e": 11329, "s": 11322, "text": "Item 1" }, { "code": null, "e": 11336, "s": 11329, "text": "Item 2" }, { "code": null, "e": 11343, "s": 11336, "text": "Item 3" }, { "code": null, "e": 11350, "s": 11343, "text": "Item 4" }, { "code": null, "e": 11357, "s": 11350, "text": "Item 1" }, { "code": null, "e": 11364, "s": 11357, "text": "Item 2" }, { "code": null, "e": 11371, "s": 11364, "text": "Item 3" }, { "code": null, "e": 11378, "s": 11371, "text": "Item 4" }, { "code": null, "e": 11411, "s": 11378, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 11425, "s": 11411, "text": " Anadi Sharma" }, { "code": null, "e": 11460, "s": 11425, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11477, "s": 11460, "text": " Frahaan Hussain" }, { "code": null, "e": 11514, "s": 11477, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 11542, "s": 11514, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11575, "s": 11542, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 11587, "s": 11575, "text": " Azaz Patel" }, { "code": null, "e": 11622, "s": 11587, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11639, "s": 11622, "text": " Muhammad Ismail" }, { "code": null, "e": 11672, "s": 11639, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 11692, "s": 11672, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 11699, "s": 11692, "text": " Print" }, { "code": null, "e": 11710, "s": 11699, "text": " Add Notes" } ]
Find n/k th node in Linked list | Practice | GeeksforGeeks
Given a singly linked list and a number k. Write a function to find the (N/k)th element, where N is the number of elements in the list. We need to consider ceil value in case of decimals. Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case consists of an integer N. The second line consists of N spaced integers.The last line consists of an integer k. Output: Print the data value of (N/k)th node in the Linked List. User Task: The task is to complete the function fractional_node() which should find the n/kth node in the linked list and return its data value. Constraints: 1 <= T <= 100 1 <= N <= 100 Example: Input: 2 6 1 2 3 4 5 6 2 5 2 7 9 3 5 3 Output: 3 7 Explanation: Testcase 1: 6/2th element is the 3rd(1-based indexing) element which is 3. 0 neelasatyasai935 days ago #PYTHON(from mechanical) import mathdef fractionalNodes(head,k): #add code here temp=head c=0 r=0 while temp!=None: c+=1 temp=temp.next i=math.ceil(c/k) temp=head while r!=i-1: r+=1 temp=temp.next return temp +1 shahabuddinbravo402 weeks ago int fractional_node(struct Node *head, int k){ float N=0; //why in float???? because float/int = float and int/int=int Node *ptr=head; while(ptr!=NULL){ ptr=ptr->next; N++; } int index=1; while(head!=NULL){ if(index==ceil(N/k)){ return head->data; } head=head->next; index++; } } 0 uma052 weeks ago Java 1 Pass soln class GfG { public static int nknode(Node head, int k) { // add your code here Node p1=head; Node p2=head; int p1Pos=1; int p2Pos=1; while(p1.next!=null){ p1=p1.next; p1Pos++; int reqPos=(int)Math.ceil((1.0*p1Pos)/k); while(p2Pos<reqPos){ p2=p2.next; p2Pos++; } } return p2.data; } } 0 bipulharsh1233 weeks ago bool kthExists(Node *ptr, int k){ while(k--){ if(!ptr) return false; ptr = ptr->next; } if(!ptr) return false; return true;}Node *kthNode(Node *ptr, int k){ while(k--){ ptr = ptr->next; } return ptr;}int fractional_node(struct Node *head, int k){ // your code here Node *kitr=head, *itr=head; while(kthExists(kitr, k)){ kitr = kthNode(kitr, k); itr = itr->next; } return itr->data;} 0 2016yashpratap1 month ago class GfG{ public static int nknode(Node head, int k) { Node cur = head; int len = 0; while(cur.next!=null) { len++; cur=cur.next; } int x = (int)Math.ceil(len/(int)k); if(head == null || k<0) { return -1; } Node temp = head; for(int i=0; i!=x;i++) { temp = temp.next; } int num = temp.data; return num; } } +1 technophyle11 month ago Simple and easy Code : int fractional_node(struct Node *head, int k) { // your code here Node* tmp=head; int len=0; while(tmp!=NULL) { len++; tmp=tmp->next; } tmp=head; if(k==0)return tmp->data; tmp=head; for(int i=1; i<ceil((float)len/k); i++){ tmp=tmp->next; } return tmp->data; } 0 0niharika22 months ago int fractional_node(struct Node *head, int k) { Node *trav = head; int n=0; while(trav){ n++; trav = trav->next; } trav = head; int i=1, ind=ceil(n/(k+0.0)); while((i++)<ind){ trav = trav->next; } return trav->data; } 0 mridulbhaskarabc2 months ago import math def fractionalNodes(head,k): #add code here node_traverse = head node_ref = head count = 1 while(node_traverse.next): count+=1 node_traverse = node_traverse.next index = math.ceil(count/k) if(index==1): return head else: for i in range(index-1): node_ref = node_ref.next return node_ref #Contributed By: Mridul Bhaskar 0 chhitizgoyal2 months ago Java Solution. Node temp=head; int len=0; while(temp!=null){ len++; temp=temp.next; } temp = head; int nk = (len+k-1)/k; for(int i=0; i<nk-1; i++){ temp=temp.next; } return temp.data; } 0 shreshthchaturvedi24013 months ago C Language Code : int fractional_node(struct Node *head, int k){ struct Node*ptr=head; float count=0.0; while(ptr!=NULL){ count++; ptr=ptr->next; } ptr=head;float x=ceil(count/k); for(int i=1; i<x; i++){ ptr=ptr->next; } return (ptr->data);} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 426, "s": 238, "text": "Given a singly linked list and a number k. Write a function to find the (N/k)th element, where N is the number of elements in the list. We need to consider ceil value in case of decimals." }, { "code": null, "e": 659, "s": 426, "text": "Input:\nThe first line of input contains an integer T denoting the number of test cases. The first line of each test case consists of an integer N. The second line consists of N spaced integers.The last line consists of an integer k." }, { "code": null, "e": 724, "s": 659, "text": "Output:\nPrint the data value of (N/k)th node in the Linked List." }, { "code": null, "e": 869, "s": 724, "text": "User Task:\nThe task is to complete the function fractional_node() which should find the n/kth node in the linked list and return its data value." }, { "code": null, "e": 911, "s": 869, "text": "Constraints: \n1 <= T <= 100\n1 <= N <= 100" }, { "code": null, "e": 959, "s": 911, "text": "Example:\nInput:\n2\n6\n1 2 3 4 5 6\n2\n5\n2 7 9 3 5\n3" }, { "code": null, "e": 971, "s": 959, "text": "Output:\n3\n7" }, { "code": null, "e": 1061, "s": 971, "text": "Explanation:\nTestcase 1: 6/2th element is the 3rd(1-based indexing) element which is 3.\n " }, { "code": null, "e": 1063, "s": 1061, "text": "0" }, { "code": null, "e": 1089, "s": 1063, "text": "neelasatyasai935 days ago" }, { "code": null, "e": 1115, "s": 1089, "text": "#PYTHON(from mechanical) " }, { "code": null, "e": 1394, "s": 1115, "text": "import mathdef fractionalNodes(head,k): #add code here temp=head c=0 r=0 while temp!=None: c+=1 temp=temp.next i=math.ceil(c/k) temp=head while r!=i-1: r+=1 temp=temp.next return temp" }, { "code": null, "e": 1397, "s": 1394, "text": "+1" }, { "code": null, "e": 1427, "s": 1397, "text": "shahabuddinbravo402 weeks ago" }, { "code": null, "e": 1777, "s": 1427, "text": "int fractional_node(struct Node *head, int k){ float N=0; //why in float???? because float/int = float and int/int=int Node *ptr=head; while(ptr!=NULL){ ptr=ptr->next; N++; } int index=1; while(head!=NULL){ if(index==ceil(N/k)){ return head->data; } head=head->next; index++; } }" }, { "code": null, "e": 1779, "s": 1777, "text": "0" }, { "code": null, "e": 1796, "s": 1779, "text": "uma052 weeks ago" }, { "code": null, "e": 1813, "s": 1796, "text": "Java 1 Pass soln" }, { "code": null, "e": 2298, "s": 1813, "text": "class GfG\n{\n public static int nknode(Node head, int k)\n {\n // add your code here\n Node p1=head;\n Node p2=head;\n \n int p1Pos=1;\n int p2Pos=1;\n \n while(p1.next!=null){\n p1=p1.next;\n p1Pos++;\n \n int reqPos=(int)Math.ceil((1.0*p1Pos)/k);\n \n while(p2Pos<reqPos){\n p2=p2.next;\n p2Pos++;\n }\n }\n \n return p2.data;\n }\n}" }, { "code": null, "e": 2300, "s": 2298, "text": "0" }, { "code": null, "e": 2325, "s": 2300, "text": "bipulharsh1233 weeks ago" }, { "code": null, "e": 2778, "s": 2325, "text": "bool kthExists(Node *ptr, int k){ while(k--){ if(!ptr) return false; ptr = ptr->next; } if(!ptr) return false; return true;}Node *kthNode(Node *ptr, int k){ while(k--){ ptr = ptr->next; } return ptr;}int fractional_node(struct Node *head, int k){ // your code here Node *kitr=head, *itr=head; while(kthExists(kitr, k)){ kitr = kthNode(kitr, k); itr = itr->next; } return itr->data;}" }, { "code": null, "e": 2780, "s": 2778, "text": "0" }, { "code": null, "e": 2806, "s": 2780, "text": "2016yashpratap1 month ago" }, { "code": null, "e": 3251, "s": 2806, "text": "class GfG{ public static int nknode(Node head, int k) { Node cur = head; int len = 0; while(cur.next!=null) { len++; cur=cur.next; } int x = (int)Math.ceil(len/(int)k); if(head == null || k<0) { return -1; } Node temp = head; for(int i=0; i!=x;i++) { temp = temp.next; } int num = temp.data; return num; } }" }, { "code": null, "e": 3254, "s": 3251, "text": "+1" }, { "code": null, "e": 3278, "s": 3254, "text": "technophyle11 month ago" }, { "code": null, "e": 3301, "s": 3278, "text": "Simple and easy Code :" }, { "code": null, "e": 3637, "s": 3301, "text": "int fractional_node(struct Node *head, int k)\n{\n // your code here\n Node* tmp=head;\n int len=0;\n while(tmp!=NULL)\n {\n len++;\n tmp=tmp->next;\n }\n tmp=head;\n if(k==0)return tmp->data;\n tmp=head;\n for(int i=1; i<ceil((float)len/k); i++){\n tmp=tmp->next;\n }\n return tmp->data;\n}" }, { "code": null, "e": 3639, "s": 3637, "text": "0" }, { "code": null, "e": 3662, "s": 3639, "text": "0niharika22 months ago" }, { "code": null, "e": 3936, "s": 3662, "text": "int fractional_node(struct Node *head, int k)\n{\n Node *trav = head; int n=0;\n while(trav){\n n++;\n trav = trav->next;\n }\n trav = head;\n int i=1, ind=ceil(n/(k+0.0));\n while((i++)<ind){\n trav = trav->next;\n }\n return trav->data;\n}" }, { "code": null, "e": 3938, "s": 3936, "text": "0" }, { "code": null, "e": 3967, "s": 3938, "text": "mridulbhaskarabc2 months ago" }, { "code": null, "e": 4408, "s": 3969, "text": "import math\ndef fractionalNodes(head,k):\n #add code here\n node_traverse = head\n node_ref = head\n count = 1\n while(node_traverse.next):\n count+=1\n node_traverse = node_traverse.next\n index = math.ceil(count/k)\n if(index==1):\n return head\n else:\n for i in range(index-1):\n node_ref = node_ref.next\n return node_ref" }, { "code": null, "e": 4440, "s": 4408, "text": "#Contributed By: Mridul Bhaskar" }, { "code": null, "e": 4444, "s": 4442, "text": "0" }, { "code": null, "e": 4469, "s": 4444, "text": "chhitizgoyal2 months ago" }, { "code": null, "e": 4484, "s": 4469, "text": "Java Solution." }, { "code": null, "e": 4726, "s": 4484, "text": " Node temp=head; int len=0; while(temp!=null){ len++; temp=temp.next; } temp = head; int nk = (len+k-1)/k; for(int i=0; i<nk-1; i++){ temp=temp.next; } return temp.data; }" }, { "code": null, "e": 4728, "s": 4726, "text": "0" }, { "code": null, "e": 4763, "s": 4728, "text": "shreshthchaturvedi24013 months ago" }, { "code": null, "e": 4781, "s": 4763, "text": "C Language Code :" }, { "code": null, "e": 5043, "s": 4781, "text": "int fractional_node(struct Node *head, int k){ struct Node*ptr=head; float count=0.0; while(ptr!=NULL){ count++; ptr=ptr->next; } ptr=head;float x=ceil(count/k); for(int i=1; i<x; i++){ ptr=ptr->next; } return (ptr->data);} " }, { "code": null, "e": 5189, "s": 5043, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5225, "s": 5189, "text": " Login to access your submissions. " }, { "code": null, "e": 5235, "s": 5225, "text": "\nProblem\n" }, { "code": null, "e": 5245, "s": 5235, "text": "\nContest\n" }, { "code": null, "e": 5308, "s": 5245, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5456, "s": 5308, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5664, "s": 5456, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5770, "s": 5664, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Implement Queue in Java using Array and Generics? - GeeksforGeeks
24 Oct, 2021 The queue is a linear data structure that follows the FIFO rule (first in first out). We can implement Queue for not only Integers but also Strings, Float, or Characters. There are 5 primary operations in Queue: enqueue() adds element x to the front of the queuedequeue() removes the last element of the queuefront() returns the front elementrear() returns the rear elementempty() returns whether the queue is empty or not enqueue() adds element x to the front of the queue dequeue() removes the last element of the queue front() returns the front element rear() returns the rear element empty() returns whether the queue is empty or not Note: Time complexity is of order 1 for all operations Implementation: Example Java // Java Program to Implement Queue using Array and Generics // Importing input output classesimport java.io.*;// Importing all utility classesimport java.util.*; // Class 1// Helper Class(user defined - generic queue class)class queue<T> { // front and rear variables are initially initiated to // -1 pointing to no element that control queue int front = -1, rear = -1; // Creating an object of ArrayList class of T type ArrayList<T> A = new ArrayList<>(); // Method 1 // Returns value of element at front T front() { // If it is not pointing to any element in queue if (front == -1) return null; // else return the front element return A.get(front); } // Method 2 // Returns value of element at rear T rear() { // If it is not pointing to any element in queue if (rear == -1) return null; return A.get(rear); } // Method 3 // Inserts element at the front of queue void enqueue(T X) { // If queue is empty if (this.empty()) { front = 0; rear = 0; A.add(X); } // If queue is not empty else { front++; if (A.size() > front) { // Mov front pointer to next A.set(front, X); } else // Add element to the queue A.add(X); } } // Method 4 // Deletes elements from the rear from queue void dequeue() { // if queue doesn't have any elements if (this.empty()) // Display message when queue is already empty System.out.println("Queue is already empty"); // If queue has only one element else if (front == rear) { // Both are pointing to same element front = rear = -1; } // If queue has more than one element else { // Increment the rear rear++; } } // Method 5 // Checks whether the queue is empty boolean empty() { // Both are initialized to same value // as assigned at declaration means no queue made if (front == -1 && rear == -1) return true; return false; } // Method 6 // Print the queue // @Override public String toString() { if (this.empty()) return ""; String Ans = ""; for (int i = rear; i < front; i++) { Ans += String.valueOf(A.get(i)) + "->"; } Ans += String.valueOf(A.get(front)); return Ans; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Case 1 : Integer Queue // Creating object of queue Class (user defined) // Declaring object of integer type queue<Integer> q1 = new queue<>(); // Pushing elements to the integer object created // Custom input integer entries q1.enqueue(5); q1.enqueue(10); q1.enqueue(20); // Print the queue after inserting integer elements System.out.println( "q1 after enqueue of 3 elements:\n" + q1); q1.dequeue(); System.out.println("q1 after dequeue :\n" + q1); // Case 2 : String Queue // Creating object of queue Class (user defined) // Declaring object of string type queue<String> q2 = new queue<>(); // Pushing elements to the String object created // Custom input string entries q2.enqueue("hello"); q2.enqueue("world"); q2.enqueue("GFG"); // Print the queue after inserting string elements System.out.println( "\nq2 after enqueue of 3 elements:\n" + q2); // Printing front and rear of the above queue System.out.println("q2 front = " + q2.front() + ", q2 rear = " + q2.rear()); // Case 3 : Float Queue // Creating object of queue Class (user defined) // Declaring object of float type queue<Float> q3 = new queue<>(); // Display message only System.out.println( "\nCreated new Float type queue q3..."); // Display whether queue is empty or not // using the empty() method System.out.println( "Checking if queue is empty or not :\n" + q3.empty()); }} q1 after enqueue of 3 elements: 5->10->20 q1 after dequeue : 10->20 q2 after enqueue of 3 elements: hello->world->GFG q2 front = GFG, q2 rear = hello Created new Float type queue q3... Checking if queue is empty or not : true anikakapoor adnanirshad158 java-queue Java Java Programs Queue Java Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23635, "s": 23607, "text": "\n24 Oct, 2021" }, { "code": null, "e": 23847, "s": 23635, "text": "The queue is a linear data structure that follows the FIFO rule (first in first out). We can implement Queue for not only Integers but also Strings, Float, or Characters. There are 5 primary operations in Queue:" }, { "code": null, "e": 24058, "s": 23847, "text": "enqueue() adds element x to the front of the queuedequeue() removes the last element of the queuefront() returns the front elementrear() returns the rear elementempty() returns whether the queue is empty or not" }, { "code": null, "e": 24109, "s": 24058, "text": "enqueue() adds element x to the front of the queue" }, { "code": null, "e": 24157, "s": 24109, "text": "dequeue() removes the last element of the queue" }, { "code": null, "e": 24191, "s": 24157, "text": "front() returns the front element" }, { "code": null, "e": 24223, "s": 24191, "text": "rear() returns the rear element" }, { "code": null, "e": 24273, "s": 24223, "text": "empty() returns whether the queue is empty or not" }, { "code": null, "e": 24328, "s": 24273, "text": "Note: Time complexity is of order 1 for all operations" }, { "code": null, "e": 24344, "s": 24328, "text": "Implementation:" }, { "code": null, "e": 24352, "s": 24344, "text": "Example" }, { "code": null, "e": 24357, "s": 24352, "text": "Java" }, { "code": "// Java Program to Implement Queue using Array and Generics // Importing input output classesimport java.io.*;// Importing all utility classesimport java.util.*; // Class 1// Helper Class(user defined - generic queue class)class queue<T> { // front and rear variables are initially initiated to // -1 pointing to no element that control queue int front = -1, rear = -1; // Creating an object of ArrayList class of T type ArrayList<T> A = new ArrayList<>(); // Method 1 // Returns value of element at front T front() { // If it is not pointing to any element in queue if (front == -1) return null; // else return the front element return A.get(front); } // Method 2 // Returns value of element at rear T rear() { // If it is not pointing to any element in queue if (rear == -1) return null; return A.get(rear); } // Method 3 // Inserts element at the front of queue void enqueue(T X) { // If queue is empty if (this.empty()) { front = 0; rear = 0; A.add(X); } // If queue is not empty else { front++; if (A.size() > front) { // Mov front pointer to next A.set(front, X); } else // Add element to the queue A.add(X); } } // Method 4 // Deletes elements from the rear from queue void dequeue() { // if queue doesn't have any elements if (this.empty()) // Display message when queue is already empty System.out.println(\"Queue is already empty\"); // If queue has only one element else if (front == rear) { // Both are pointing to same element front = rear = -1; } // If queue has more than one element else { // Increment the rear rear++; } } // Method 5 // Checks whether the queue is empty boolean empty() { // Both are initialized to same value // as assigned at declaration means no queue made if (front == -1 && rear == -1) return true; return false; } // Method 6 // Print the queue // @Override public String toString() { if (this.empty()) return \"\"; String Ans = \"\"; for (int i = rear; i < front; i++) { Ans += String.valueOf(A.get(i)) + \"->\"; } Ans += String.valueOf(A.get(front)); return Ans; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Case 1 : Integer Queue // Creating object of queue Class (user defined) // Declaring object of integer type queue<Integer> q1 = new queue<>(); // Pushing elements to the integer object created // Custom input integer entries q1.enqueue(5); q1.enqueue(10); q1.enqueue(20); // Print the queue after inserting integer elements System.out.println( \"q1 after enqueue of 3 elements:\\n\" + q1); q1.dequeue(); System.out.println(\"q1 after dequeue :\\n\" + q1); // Case 2 : String Queue // Creating object of queue Class (user defined) // Declaring object of string type queue<String> q2 = new queue<>(); // Pushing elements to the String object created // Custom input string entries q2.enqueue(\"hello\"); q2.enqueue(\"world\"); q2.enqueue(\"GFG\"); // Print the queue after inserting string elements System.out.println( \"\\nq2 after enqueue of 3 elements:\\n\" + q2); // Printing front and rear of the above queue System.out.println(\"q2 front = \" + q2.front() + \", q2 rear = \" + q2.rear()); // Case 3 : Float Queue // Creating object of queue Class (user defined) // Declaring object of float type queue<Float> q3 = new queue<>(); // Display message only System.out.println( \"\\nCreated new Float type queue q3...\"); // Display whether queue is empty or not // using the empty() method System.out.println( \"Checking if queue is empty or not :\\n\" + q3.empty()); }}", "e": 28756, "s": 24357, "text": null }, { "code": null, "e": 28984, "s": 28756, "text": "q1 after enqueue of 3 elements:\n5->10->20\nq1 after dequeue :\n10->20\n\nq2 after enqueue of 3 elements:\nhello->world->GFG\nq2 front = GFG, q2 rear = hello\n\nCreated new Float type queue q3...\nChecking if queue is empty or not :\ntrue" }, { "code": null, "e": 28996, "s": 28984, "text": "anikakapoor" }, { "code": null, "e": 29011, "s": 28996, "text": "adnanirshad158" }, { "code": null, "e": 29022, "s": 29011, "text": "java-queue" }, { "code": null, "e": 29027, "s": 29022, "text": "Java" }, { "code": null, "e": 29041, "s": 29027, "text": "Java Programs" }, { "code": null, "e": 29047, "s": 29041, "text": "Queue" }, { "code": null, "e": 29052, "s": 29047, "text": "Java" }, { "code": null, "e": 29058, "s": 29052, "text": "Queue" }, { "code": null, "e": 29156, "s": 29058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29165, "s": 29156, "text": "Comments" }, { "code": null, "e": 29178, "s": 29165, "text": "Old Comments" }, { "code": null, "e": 29208, "s": 29178, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29223, "s": 29208, "text": "Stream In Java" }, { "code": null, "e": 29244, "s": 29223, "text": "Constructors in Java" }, { "code": null, "e": 29290, "s": 29244, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29309, "s": 29290, "text": "Exceptions in Java" }, { "code": null, "e": 29353, "s": 29309, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 29379, "s": 29353, "text": "Java Programming Examples" }, { "code": null, "e": 29413, "s": 29379, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29460, "s": 29413, "text": "Implementing a Linked List in Java using Class" } ]
Machine Translation with Transformers Using Pytorch | by Raymond Cheng | Towards Data Science
Translation, or more formally, machine translation, is one of the most popular tasks in Natural Language Processing (NLP) that deals with translating from one language to another. In the early days, translation is initially done by simply substituting words in one language to words in another. However, doing that does not yield good results since languages are fundamentally different so a higher level of understanding (e.g. phrases/sentences) is needed. With the advent of deep learning, modern software now adopts statistical and neural techniques, which are proven to be more effective when doing translation. Of course, everyone has access to the powerful Google Translate, but in case you want to know how to implement translation in code, this article will teach you how. This article will show how you can easily implement translation with a simple API provided by Huggingface Transformers, a library based on Pytorch. Now without further ado, let’s get started! Install Library English to German Translation Example Custom Language Translation Example Before installing the Transformers library, you will need to have a working version of Pytorch installed. You can install Pytorch by going to its official website. After installing Pytorch, you can install Transformers by: pip install transformers Now, we are ready to do the translation! If you want to do English to German Translation, then you can start by importing the relevant pipeline module in Transformers: from transformers import pipeline The pipeline is an easy method of doing inference on different tasks by using a simple API. You can learn more about the pipeline module here. To do English to German translation, you need a model that is fine-tuned specifically on this task. T5 is a model that has been trained on the massive c4 dataset that contains a dataset for English-German translation, and thus we can directly use this model for the translation pipeline (we are using the t5-base variant): translation = pipeline(“translation_en_to_de”)## same with ## translation = pipeline("translation_en_to_de", model="t5-base", tokenizer="t5-base") Note that we didn’t specify any model in this line of code because by default, t5-base is used for translation. If you want to specify your own model and tokenizer, you can add a model and tokenizer by specifying the model and tokenizer parameter (if they are provided within Huggingface), or build your own model and tokenizer as will be demonstrated in the next example (if provided by the community). For more details on the translation pipeline, you can refer to the official documentation here. Then, you can define the text you want to translate. Let’s try to translate this: I like to study Data Science and Machine Learning text = "I like to study Data Science and Machine Learning" Finally, now you can use the API provided by the pipeline to translate and set a max_length (e.g. 40 tokens): translated_text = translation(text, max_length=40)[0]['translation_text']print(translated_text) Voila! After tens of seconds, we get the German translation: Ich studiere gerne Datenwissenschaft und maschinelles Lernen If you want to do a translation of any two custom languages, say English to Chinese, then you need a model that is specifically fine-tuned on that specific task. Fortunately, with the community established by Huggingface, you most likely don’t need to collect your own dataset and fine-tune your model on it. You can directly head over to Huggingface’s model website to see a list of translation models trained on different language pairs. For our case to translate from English to Chinese, we can use the English-to-Chinese pretrained model by HelsinkiNLP and directly use it. To start, we first import the necessary modules: from transformers import AutoModelWithLMHead, AutoTokenizer Then, we can build our model and tokenizer via: model = AutoModelWithLMHead.from_pretrained("Helsinki-NLP/opus-mt-en-zh")tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-zh") Now, we can feed in the language pairs we want to translate, model, and tokenizer into the pipeline: translation = pipeline("translation_en_to_zh", model=model, tokenizer=tokenizer) Similar to the previous example, we can use the same code to define our text and translate: text = "I like to study Data Science and Machine Learning"translated_text = translation(text, max_length=40)[0]['translation_text']print(translated_text) After waiting for several seconds, you should see the Chinese version of the text! 我喜欢学习数据科学和机器学习 Congratulations! Now you should be able to know how to implement translation using the pretrained models offered by Huggingface and the community around it. In case you want to see what the complete code looks like, here’s the Jupyter code: from transformers import pipeline translation = pipeline("translation_en_to_de") ## same with ## translation = pipeline("translation_en_to_de", model="t5-base", tokenizer="t5-base") text = "I like to study Data Science and Machine Learning" translated_text = translation(text, max_length=40)[0]['translation_text'] print(translated_text) Ich studiere gerne Datenwissenschaft und maschinelles Lernen from transformers import AutoModelWithLMHead, AutoTokenizer model = AutoModelWithLMHead.from_pretrained("Helsinki-NLP/opus-mt-en-zh") tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-zh") translation = pipeline("translation_en_to_zh", model=model, tokenizer=tokenizer) text = "I like to study Data Science and Machine Learning" translated_text = translation(text, max_length=40)[0]['translation_text'] print(translated_text) 我喜欢学习数据科学和机器学习 And that’s all! If you have any questions, please feel free to ask questions below. If you like my work, you can follow me and sign up for my newsletter so that you will get informed whenever I publish a new article! You can also take a look at my previous articles if you like. See you all next time :D towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com [1] Transformers Github, Huggingface [2] Transformers Official Documentation, Huggingface [3] Pytorch Official Website, Facebook AI Research [4] Raffel, Colin, et al. “Exploring the limits of transfer learning with a unified text-to-text transformer.” arXiv preprint arXiv:1910.10683 (2019). [5] Tensorflow Datasets, Google
[ { "code": null, "e": 788, "s": 172, "text": "Translation, or more formally, machine translation, is one of the most popular tasks in Natural Language Processing (NLP) that deals with translating from one language to another. In the early days, translation is initially done by simply substituting words in one language to words in another. However, doing that does not yield good results since languages are fundamentally different so a higher level of understanding (e.g. phrases/sentences) is needed. With the advent of deep learning, modern software now adopts statistical and neural techniques, which are proven to be more effective when doing translation." }, { "code": null, "e": 1101, "s": 788, "text": "Of course, everyone has access to the powerful Google Translate, but in case you want to know how to implement translation in code, this article will teach you how. This article will show how you can easily implement translation with a simple API provided by Huggingface Transformers, a library based on Pytorch." }, { "code": null, "e": 1145, "s": 1101, "text": "Now without further ado, let’s get started!" }, { "code": null, "e": 1161, "s": 1145, "text": "Install Library" }, { "code": null, "e": 1199, "s": 1161, "text": "English to German Translation Example" }, { "code": null, "e": 1235, "s": 1199, "text": "Custom Language Translation Example" }, { "code": null, "e": 1399, "s": 1235, "text": "Before installing the Transformers library, you will need to have a working version of Pytorch installed. You can install Pytorch by going to its official website." }, { "code": null, "e": 1458, "s": 1399, "text": "After installing Pytorch, you can install Transformers by:" }, { "code": null, "e": 1483, "s": 1458, "text": "pip install transformers" }, { "code": null, "e": 1651, "s": 1483, "text": "Now, we are ready to do the translation! If you want to do English to German Translation, then you can start by importing the relevant pipeline module in Transformers:" }, { "code": null, "e": 1685, "s": 1651, "text": "from transformers import pipeline" }, { "code": null, "e": 1828, "s": 1685, "text": "The pipeline is an easy method of doing inference on different tasks by using a simple API. You can learn more about the pipeline module here." }, { "code": null, "e": 2151, "s": 1828, "text": "To do English to German translation, you need a model that is fine-tuned specifically on this task. T5 is a model that has been trained on the massive c4 dataset that contains a dataset for English-German translation, and thus we can directly use this model for the translation pipeline (we are using the t5-base variant):" }, { "code": null, "e": 2298, "s": 2151, "text": "translation = pipeline(“translation_en_to_de”)## same with ## translation = pipeline(\"translation_en_to_de\", model=\"t5-base\", tokenizer=\"t5-base\")" }, { "code": null, "e": 2798, "s": 2298, "text": "Note that we didn’t specify any model in this line of code because by default, t5-base is used for translation. If you want to specify your own model and tokenizer, you can add a model and tokenizer by specifying the model and tokenizer parameter (if they are provided within Huggingface), or build your own model and tokenizer as will be demonstrated in the next example (if provided by the community). For more details on the translation pipeline, you can refer to the official documentation here." }, { "code": null, "e": 2880, "s": 2798, "text": "Then, you can define the text you want to translate. Let’s try to translate this:" }, { "code": null, "e": 2930, "s": 2880, "text": "I like to study Data Science and Machine Learning" }, { "code": null, "e": 2989, "s": 2930, "text": "text = \"I like to study Data Science and Machine Learning\"" }, { "code": null, "e": 3099, "s": 2989, "text": "Finally, now you can use the API provided by the pipeline to translate and set a max_length (e.g. 40 tokens):" }, { "code": null, "e": 3195, "s": 3099, "text": "translated_text = translation(text, max_length=40)[0]['translation_text']print(translated_text)" }, { "code": null, "e": 3256, "s": 3195, "text": "Voila! After tens of seconds, we get the German translation:" }, { "code": null, "e": 3317, "s": 3256, "text": "Ich studiere gerne Datenwissenschaft und maschinelles Lernen" }, { "code": null, "e": 3757, "s": 3317, "text": "If you want to do a translation of any two custom languages, say English to Chinese, then you need a model that is specifically fine-tuned on that specific task. Fortunately, with the community established by Huggingface, you most likely don’t need to collect your own dataset and fine-tune your model on it. You can directly head over to Huggingface’s model website to see a list of translation models trained on different language pairs." }, { "code": null, "e": 3944, "s": 3757, "text": "For our case to translate from English to Chinese, we can use the English-to-Chinese pretrained model by HelsinkiNLP and directly use it. To start, we first import the necessary modules:" }, { "code": null, "e": 4004, "s": 3944, "text": "from transformers import AutoModelWithLMHead, AutoTokenizer" }, { "code": null, "e": 4052, "s": 4004, "text": "Then, we can build our model and tokenizer via:" }, { "code": null, "e": 4197, "s": 4052, "text": "model = AutoModelWithLMHead.from_pretrained(\"Helsinki-NLP/opus-mt-en-zh\")tokenizer = AutoTokenizer.from_pretrained(\"Helsinki-NLP/opus-mt-en-zh\")" }, { "code": null, "e": 4298, "s": 4197, "text": "Now, we can feed in the language pairs we want to translate, model, and tokenizer into the pipeline:" }, { "code": null, "e": 4379, "s": 4298, "text": "translation = pipeline(\"translation_en_to_zh\", model=model, tokenizer=tokenizer)" }, { "code": null, "e": 4471, "s": 4379, "text": "Similar to the previous example, we can use the same code to define our text and translate:" }, { "code": null, "e": 4625, "s": 4471, "text": "text = \"I like to study Data Science and Machine Learning\"translated_text = translation(text, max_length=40)[0]['translation_text']print(translated_text)" }, { "code": null, "e": 4708, "s": 4625, "text": "After waiting for several seconds, you should see the Chinese version of the text!" }, { "code": null, "e": 4723, "s": 4708, "text": "我喜欢学习数据科学和机器学习" }, { "code": null, "e": 4964, "s": 4723, "text": "Congratulations! Now you should be able to know how to implement translation using the pretrained models offered by Huggingface and the community around it. In case you want to see what the complete code looks like, here’s the Jupyter code:" }, { "code": null, "e": 4999, "s": 4964, "text": "from transformers import pipeline\n" }, { "code": null, "e": 5149, "s": 4999, "text": "translation = pipeline(\"translation_en_to_de\")\n## same with \n## translation = pipeline(\"translation_en_to_de\", model=\"t5-base\", tokenizer=\"t5-base\")\n" }, { "code": null, "e": 5209, "s": 5149, "text": "text = \"I like to study Data Science and Machine Learning\"\n" }, { "code": null, "e": 5307, "s": 5209, "text": "translated_text = translation(text, max_length=40)[0]['translation_text']\nprint(translated_text)\n" }, { "code": null, "e": 5369, "s": 5307, "text": "Ich studiere gerne Datenwissenschaft und maschinelles Lernen\n" }, { "code": null, "e": 5577, "s": 5369, "text": "from transformers import AutoModelWithLMHead, AutoTokenizer\n\nmodel = AutoModelWithLMHead.from_pretrained(\"Helsinki-NLP/opus-mt-en-zh\")\ntokenizer = AutoTokenizer.from_pretrained(\"Helsinki-NLP/opus-mt-en-zh\")\n" }, { "code": null, "e": 5659, "s": 5577, "text": "translation = pipeline(\"translation_en_to_zh\", model=model, tokenizer=tokenizer)\n" }, { "code": null, "e": 5719, "s": 5659, "text": "text = \"I like to study Data Science and Machine Learning\"\n" }, { "code": null, "e": 5817, "s": 5719, "text": "translated_text = translation(text, max_length=40)[0]['translation_text']\nprint(translated_text)\n" }, { "code": null, "e": 5833, "s": 5817, "text": "我喜欢学习数据科学和机器学习\n" }, { "code": null, "e": 6137, "s": 5833, "text": "And that’s all! If you have any questions, please feel free to ask questions below. If you like my work, you can follow me and sign up for my newsletter so that you will get informed whenever I publish a new article! You can also take a look at my previous articles if you like. See you all next time :D" }, { "code": null, "e": 6160, "s": 6137, "text": "towardsdatascience.com" }, { "code": null, "e": 6183, "s": 6160, "text": "towardsdatascience.com" }, { "code": null, "e": 6206, "s": 6183, "text": "towardsdatascience.com" }, { "code": null, "e": 6229, "s": 6206, "text": "towardsdatascience.com" }, { "code": null, "e": 6252, "s": 6229, "text": "towardsdatascience.com" }, { "code": null, "e": 6289, "s": 6252, "text": "[1] Transformers Github, Huggingface" }, { "code": null, "e": 6342, "s": 6289, "text": "[2] Transformers Official Documentation, Huggingface" }, { "code": null, "e": 6393, "s": 6342, "text": "[3] Pytorch Official Website, Facebook AI Research" }, { "code": null, "e": 6544, "s": 6393, "text": "[4] Raffel, Colin, et al. “Exploring the limits of transfer learning with a unified text-to-text transformer.” arXiv preprint arXiv:1910.10683 (2019)." } ]
The enigma of Adjusted R Squared in regression analysis | by Sanjay Nandakumar | Towards Data Science
“Truth does not consist in minute accuracy of detail; but in conveying a right impression.” Henry Alford Regression analysis is one of the most fundamental but commanding machine learning techniques which is still predominant and made a way for many advanced kinds of research in the industry. Although there are a handful of advanced regression techniques already serving the purpose of predicting the continuous variables like bagging, boosting, support vectors, etc, linear regression principles remain the first choice for most of the researchers if the data perpetuates a rectilinear fashion when represented on a multidimensional space. One of the most widely used evaluation metrics for the linear regression models is R squared aka Coefficient of determination. R squared is considered as a goodness of fit metric which in most of the time ranges around 0 to 1. Higher the value of R Squared examined as higher the coherence and predictive ability of the model. But as with most of the other evaluation metrics in machine learning, R Squared has also some restraints which make it give imprecise indications sometimes by signifying an indigent model with an extremely high value. In this article, we will discuss the calculation procedure of R Squared, its limitations, and how these limitations can be overridden using an advanced evaluation metric called Adjusted R Squared. The intuition of R Squared in regression analysisLimitations of R SquaredImportance of Adjusted R Squared The intuition of R Squared in regression analysis Limitations of R Squared Importance of Adjusted R Squared We will start with an example use case. Consider that we have a machine learning problem to predict the height of a person using his/her weight, father’s height, and mother’s height as independent variables. We have the following data for research- Here, our target variable is Height and predictor variables are - Father’s height (in cm)Mother’s height (in cm)Weight of the person (in kg) Father’s height (in cm) Mother’s height (in cm) Weight of the person (in kg) It is clear from the data that there exists a linear relationship between the predictor variables and the target variable. Hence, it is a typical idea to move forward with a multiple linear regression algorithm for building the model to serve our prediction purpose. Let’s assume that we have a train ratio of 0.7 and we considered the first 7 records as train data and the rest of the 3 records as test data. We completed our linear regression model and now, we need to evaluate our model to know how close can be our prediction to reality. Here, comes the R Squared, one of the most popular performance evaluation metrics to measure the strength and closeness of prediction. R Squared = 1- (SSR/SST) where, SSR = Sum of Squared Residuals SST = Sum of Squared Total Consider that our prediction for the test data is as follows- Let’s calculate the R Squared for our model using the sklearn library ( We will discuss the in-depth intuition of its mathematical derivation after that ) #Import necessary packages and librariesimport numpy as np import pandas as pdfrom sklearn.linear_model import LinearRegression#Create input data as a dictionaryinput_dict = {"PersonId": [1,2,3,4,5,6,7,8,9,10],"Father's height" [136.5,149.8,174.07,168.05,185.8,170.45,180.75,148.15,154.46,158.11],"Mother's height" : [126.5,143.8,167.07,165.05,182.8,160.45,170.75,140.25,148.46,147.11],"Weight" : [50,60,79,85,60,65,75,55,62,67] ,"Person's Height": [116.5,139.8,184.07,198.05,145.8,160.45,180.75,128.15,144.46,156.11]}#Convert dictionary into a pandas dataframedata = pd.DataFrame(input_dict) #Split the data into train data and test dataX_train = data.head(7)X_test = data.tail(3)#Remove UniqueId and target variabledel X_train["PersonId"]del X_train["Person's Height"]#Remove UniqueId and target variabledel X_test["PersonId"]del X_test["Person's Height"]y_train = data.head(7)y_test = data.tail(3)#Remove UniqueId and predictor variablesdel y_train["PersonId"]del y_train["Father's height"]del y_train["Mother's height"]del y_train["Weight"]#Remove UniqueId and predictor variablesdel y_test["PersonId"]del y_test["Father's height"]del y_test["Mother's height"]del y_test["Weight"]#Perform linear regression using sklearn libraryregressor = LinearRegression()regressor.fit(X_train,y_train) predictions = regressor.predict(X_test)#sklearn's inbuilt method for computing the RSquared of the modelrsquared = regressor.score(X_test, y_test)#Predictions of testdataprint(predictions) #R Sqaured of the modelprint(rsquared) Here, R Squared = 0.963. As per the characteristics of this metric, this looks like a very good value. But is it enough to confirm the confidence regarding the predictive ability of this model? No. Let’s check Adjusted R Squared also for this model- #Adjusted RSquared of the modeln=len(data) #number of recordsp=len(data.columns)-2 #number of features .i.e. columns excluding uniqueId and target variableadjr= 1-(1-score)*(n-1)/(n-p-1)print(adjr) Oops !!! It is less than R squared. Moreover, there is a drop of around 2% in the confidence from R Squared (0.963) to Adjusted R Squared (0.945). Why there was a drop in Adjusted R Squared?What is the real intuitive meaning conveyed by this difference?How it will reflect in real-time use cases?Does R Squared always belong to a value between 0 and 1 or are there any exceptional cases that we often miss out? Why there was a drop in Adjusted R Squared? What is the real intuitive meaning conveyed by this difference? How it will reflect in real-time use cases? Does R Squared always belong to a value between 0 and 1 or are there any exceptional cases that we often miss out? Let’s know the answers... R Squared = 1- (SSR/SST) Here, SST stands for Sum of Squared Total which is an indication of nothing but “how much do the predicted points get varies from the mean of the target variable”. Mean is nothing but a regression line here. SST = Sum (Square (Each data point — Mean of the target variable)) Mathematically, where, n = Number of observations y = Observed value of the target variable y̅ = Mean value of the target variable For example, If we want to build a regression model to predict the height of a person with weight as the independent variable then a possible prediction without much effort is to calculate the mean height of all persons belonging to our sample and consider it as the prediction. The red line in the following diagram shows the mean value of the height of all the persons belonging to our sample. Now come to SSR, SSR stands for Sum of Squared Residuals. This residual is calculated from the model which we built from our mathematical approach (Linear regression, Bayesian regression, Polynomial regression, or any other approach). If we use a sophisticated approach rather than using a naive approach like mean then our accuracy will increase. SSR = Sum (Square (Each data point — Each corresponding data point in the regression line)) Mathematically, where, n = Number of observations y = Observed value of the target variable ŷ = Predicted value of the target variable In the above diagram, let’s consider that the blue line indicates the predictions from a sophisticated model with a high-level mathematical analysis. We can see that it has higher accuracy than the red line. Now come to the formula, R Squared = 1- (SSR/SST) Here, SST will be a large number because it is a very poor model (red line). SSR will be a small number because it is the best model we developed after much mathematical analysis (blue line). So, SSR/SST will be a very small number (It will become very small whenever SSR decreases). So, 1- (SSR/SST) will be a large number. So we can infer that whenever R Squared goes higher, it means the model is too good. This is a generic case but this cannot be applied in many cases where multiple independent variables are present. In the example, we had only one independent variable and one target variable but in the real case, we will have 100’s of independent variables for a single dependent variable. The actual problem is that, out of 100’s of independent variables- Some variables will have a very high correlation with the target variable. Some variables will have a very small correlation with the target variable. Also, some independent variables will not correlate at all. If there is no correlation then what happens is that — “ Our model will automatically try to establish a relationship with dependent and independent variables and proceed with mathematical calculations assuming that the researcher has already eliminated the unwanted independent variables.” For example, For predicting the height of a person, we will have the following independent variables Weight ( High correlation ) Phone number( No correlation ) Location ( Low correlation ) Age ( High correlation ) Gender ( Low correlation ) Here, only weight and age are enough to build an accurate model but the model will assume that the phone number will also influence the height and represent it in a multidimensional space. When a regression plane is built through these 5 independent variables, its gradient, intercept, cost, and residual will automatically adjust to increase the accuracy. When the accuracy gets increases artificially, obviously R squared will also increase. In such scenarios, the regression plane will touch all the edges of the original data points in the multidimensional space. It will make the SSR a very small number and that will eventually make the R Squared a very high number but when test data is introduced, such models will fail miserably. That is the reason why a high R Squared value does not guarantee an accurate model. For overcoming the challenge mentioned above, we have an additional metric called Adjusted R Squared. Adjusted R Squared= 1 — [ ( (1 — R Squared) * (n-1) ) / (n-p-1) ] where, p = number of independent variables. n = number of records in the data set. For a simple representation, we can rewrite the above formula like this- Adjusted R Squared= 1 — (A * B) where, A = 1 — R Squared B = (n-1) / (n-p-1) From the above formula, we can impulsively consider the following inferences- When the number of predictor variables increases, it will decrease the whole value of B. When the value of R Squared increases, it will decrease the whole value of A. Hence technically, it penalizes the value of both A and B if either R Squared is high or the number of predictor variables is high. If we multiply both A and B then it will be a much smaller number. If we subtract the product of A and B from 1 then it will be a value definitively less than 1 unless the value of p = 1. Not only the difference between R Squared and Adjusted R squared but also the value of Adjusted R Squared itself can be considered as a goodness of fit metric replacing the limitations of R Squared for evaluating the envisaged consistency of the model. In summary, whenever the number of independent variables gets increases, it will penalize the formula so that the total value will come down. It is least affected by the increase of independent variables. Hence, Adjusted R Squared will more accurately indicate the performance of the model than the R Squared. Yes. It can be also a negative value in some rare scenarios. Since, R squared = 1 — ( SSR / SST ) It is calculated on an assumption that the average line of the target which is a perpendicular line of the y-axis is the worst fit a model can have at a maximum riskiest case. SST is the squared difference between this average line and original data points. Similarly, SSR is the squared difference between the predicted data points (by the model plane) and original data points. SSR/SST gives a ratio that indicates, “How SSR is worst with respect to SST ? ”. If your model can somewhat build a plane that is comparatively good than the worst, then in 99% cases SSR< SST. It eventually makes R squared as positive if you substitute it in the equation. But what if SSR >SST? This means that your regression plane is worse than the mean line (SST). In this case, R squared will be negative. But it happens only in 1% of cases or smaller. Despite being a well-known and mass accepted performance evaluation measure, R Squared suffers from many debased inference deliver-ability in some conditions which are not in its scope. However, it is to be accepted there is no magic wand that can completely represent the inherent disposition of a regression model to 100%. The Adjusted R Squared is such a metric that can domesticate the limitations of R Squared to a great extent and that remains as a prime reason for being the pet of data scientists across the globe. Although it is not in the scope of this article, please have a look at some other performance evaluation metrics which we usually use in regression and forecasting here like MAE, MSE, RMSE, MAPE, etc. It will give you a more congenital perspective of model evaluation dealing with continuous variables apart from what we have discussed here so far. I hope that now you got an intuitive understanding of the principle and derivation of R Squared and Adjusted R Squared and how they need to be implemented at the right places and right timings. You can connect with me via the following platforms- QuoraLinkedInGmail — sanjayjsw05@gmail.com Quora LinkedIn Gmail — sanjayjsw05@gmail.com Sougata Deb, A Novel Robust R-Squared Measure and Its Applications in Linear Regression (2016)Kazhurio Ohtani and Hisashi Tanizaki, Exact distribution of R2 and Adjusted R2 in a linear regression model with multivariate t error terms (2004)Carrodus, M.L., and Giles, D.E.A, The exact distribution of R2 when regression disturbances are autocorrelated, Economics Letters, 38, 375–380 (1992) Sougata Deb, A Novel Robust R-Squared Measure and Its Applications in Linear Regression (2016) Kazhurio Ohtani and Hisashi Tanizaki, Exact distribution of R2 and Adjusted R2 in a linear regression model with multivariate t error terms (2004) Carrodus, M.L., and Giles, D.E.A, The exact distribution of R2 when regression disturbances are autocorrelated, Economics Letters, 38, 375–380 (1992) Thanks for reading!!!
[ { "code": null, "e": 264, "s": 172, "text": "“Truth does not consist in minute accuracy of detail; but in conveying a right impression.”" }, { "code": null, "e": 277, "s": 264, "text": "Henry Alford" }, { "code": null, "e": 1142, "s": 277, "text": "Regression analysis is one of the most fundamental but commanding machine learning techniques which is still predominant and made a way for many advanced kinds of research in the industry. Although there are a handful of advanced regression techniques already serving the purpose of predicting the continuous variables like bagging, boosting, support vectors, etc, linear regression principles remain the first choice for most of the researchers if the data perpetuates a rectilinear fashion when represented on a multidimensional space. One of the most widely used evaluation metrics for the linear regression models is R squared aka Coefficient of determination. R squared is considered as a goodness of fit metric which in most of the time ranges around 0 to 1. Higher the value of R Squared examined as higher the coherence and predictive ability of the model." }, { "code": null, "e": 1557, "s": 1142, "text": "But as with most of the other evaluation metrics in machine learning, R Squared has also some restraints which make it give imprecise indications sometimes by signifying an indigent model with an extremely high value. In this article, we will discuss the calculation procedure of R Squared, its limitations, and how these limitations can be overridden using an advanced evaluation metric called Adjusted R Squared." }, { "code": null, "e": 1663, "s": 1557, "text": "The intuition of R Squared in regression analysisLimitations of R SquaredImportance of Adjusted R Squared" }, { "code": null, "e": 1713, "s": 1663, "text": "The intuition of R Squared in regression analysis" }, { "code": null, "e": 1738, "s": 1713, "text": "Limitations of R Squared" }, { "code": null, "e": 1771, "s": 1738, "text": "Importance of Adjusted R Squared" }, { "code": null, "e": 1979, "s": 1771, "text": "We will start with an example use case. Consider that we have a machine learning problem to predict the height of a person using his/her weight, father’s height, and mother’s height as independent variables." }, { "code": null, "e": 2020, "s": 1979, "text": "We have the following data for research-" }, { "code": null, "e": 2086, "s": 2020, "text": "Here, our target variable is Height and predictor variables are -" }, { "code": null, "e": 2161, "s": 2086, "text": "Father’s height (in cm)Mother’s height (in cm)Weight of the person (in kg)" }, { "code": null, "e": 2185, "s": 2161, "text": "Father’s height (in cm)" }, { "code": null, "e": 2209, "s": 2185, "text": "Mother’s height (in cm)" }, { "code": null, "e": 2238, "s": 2209, "text": "Weight of the person (in kg)" }, { "code": null, "e": 2505, "s": 2238, "text": "It is clear from the data that there exists a linear relationship between the predictor variables and the target variable. Hence, it is a typical idea to move forward with a multiple linear regression algorithm for building the model to serve our prediction purpose." }, { "code": null, "e": 2648, "s": 2505, "text": "Let’s assume that we have a train ratio of 0.7 and we considered the first 7 records as train data and the rest of the 3 records as test data." }, { "code": null, "e": 2780, "s": 2648, "text": "We completed our linear regression model and now, we need to evaluate our model to know how close can be our prediction to reality." }, { "code": null, "e": 2915, "s": 2780, "text": "Here, comes the R Squared, one of the most popular performance evaluation metrics to measure the strength and closeness of prediction." }, { "code": null, "e": 2940, "s": 2915, "text": "R Squared = 1- (SSR/SST)" }, { "code": null, "e": 2947, "s": 2940, "text": "where," }, { "code": null, "e": 2978, "s": 2947, "text": "SSR = Sum of Squared Residuals" }, { "code": null, "e": 3005, "s": 2978, "text": "SST = Sum of Squared Total" }, { "code": null, "e": 3067, "s": 3005, "text": "Consider that our prediction for the test data is as follows-" }, { "code": null, "e": 3222, "s": 3067, "text": "Let’s calculate the R Squared for our model using the sklearn library ( We will discuss the in-depth intuition of its mathematical derivation after that )" }, { "code": null, "e": 3817, "s": 3222, "text": "#Import necessary packages and librariesimport numpy as np import pandas as pdfrom sklearn.linear_model import LinearRegression#Create input data as a dictionaryinput_dict = {\"PersonId\": [1,2,3,4,5,6,7,8,9,10],\"Father's height\" [136.5,149.8,174.07,168.05,185.8,170.45,180.75,148.15,154.46,158.11],\"Mother's height\" : [126.5,143.8,167.07,165.05,182.8,160.45,170.75,140.25,148.46,147.11],\"Weight\" : [50,60,79,85,60,65,75,55,62,67] ,\"Person's Height\": [116.5,139.8,184.07,198.05,145.8,160.45,180.75,128.15,144.46,156.11]}#Convert dictionary into a pandas dataframedata = pd.DataFrame(input_dict)" }, { "code": null, "e": 4713, "s": 3817, "text": "#Split the data into train data and test dataX_train = data.head(7)X_test = data.tail(3)#Remove UniqueId and target variabledel X_train[\"PersonId\"]del X_train[\"Person's Height\"]#Remove UniqueId and target variabledel X_test[\"PersonId\"]del X_test[\"Person's Height\"]y_train = data.head(7)y_test = data.tail(3)#Remove UniqueId and predictor variablesdel y_train[\"PersonId\"]del y_train[\"Father's height\"]del y_train[\"Mother's height\"]del y_train[\"Weight\"]#Remove UniqueId and predictor variablesdel y_test[\"PersonId\"]del y_test[\"Father's height\"]del y_test[\"Mother's height\"]del y_test[\"Weight\"]#Perform linear regression using sklearn libraryregressor = LinearRegression()regressor.fit(X_train,y_train) predictions = regressor.predict(X_test)#sklearn's inbuilt method for computing the RSquared of the modelrsquared = regressor.score(X_test, y_test)#Predictions of testdataprint(predictions)" }, { "code": null, "e": 4752, "s": 4713, "text": "#R Sqaured of the modelprint(rsquared)" }, { "code": null, "e": 4855, "s": 4752, "text": "Here, R Squared = 0.963. As per the characteristics of this metric, this looks like a very good value." }, { "code": null, "e": 4946, "s": 4855, "text": "But is it enough to confirm the confidence regarding the predictive ability of this model?" }, { "code": null, "e": 4950, "s": 4946, "text": "No." }, { "code": null, "e": 5002, "s": 4950, "text": "Let’s check Adjusted R Squared also for this model-" }, { "code": null, "e": 5200, "s": 5002, "text": "#Adjusted RSquared of the modeln=len(data) #number of recordsp=len(data.columns)-2 #number of features .i.e. columns excluding uniqueId and target variableadjr= 1-(1-score)*(n-1)/(n-p-1)print(adjr)" }, { "code": null, "e": 5347, "s": 5200, "text": "Oops !!! It is less than R squared. Moreover, there is a drop of around 2% in the confidence from R Squared (0.963) to Adjusted R Squared (0.945)." }, { "code": null, "e": 5611, "s": 5347, "text": "Why there was a drop in Adjusted R Squared?What is the real intuitive meaning conveyed by this difference?How it will reflect in real-time use cases?Does R Squared always belong to a value between 0 and 1 or are there any exceptional cases that we often miss out?" }, { "code": null, "e": 5655, "s": 5611, "text": "Why there was a drop in Adjusted R Squared?" }, { "code": null, "e": 5719, "s": 5655, "text": "What is the real intuitive meaning conveyed by this difference?" }, { "code": null, "e": 5763, "s": 5719, "text": "How it will reflect in real-time use cases?" }, { "code": null, "e": 5878, "s": 5763, "text": "Does R Squared always belong to a value between 0 and 1 or are there any exceptional cases that we often miss out?" }, { "code": null, "e": 5904, "s": 5878, "text": "Let’s know the answers..." }, { "code": null, "e": 5929, "s": 5904, "text": "R Squared = 1- (SSR/SST)" }, { "code": null, "e": 6137, "s": 5929, "text": "Here, SST stands for Sum of Squared Total which is an indication of nothing but “how much do the predicted points get varies from the mean of the target variable”. Mean is nothing but a regression line here." }, { "code": null, "e": 6204, "s": 6137, "text": "SST = Sum (Square (Each data point — Mean of the target variable))" }, { "code": null, "e": 6220, "s": 6204, "text": "Mathematically," }, { "code": null, "e": 6227, "s": 6220, "text": "where," }, { "code": null, "e": 6254, "s": 6227, "text": "n = Number of observations" }, { "code": null, "e": 6296, "s": 6254, "text": "y = Observed value of the target variable" }, { "code": null, "e": 6335, "s": 6296, "text": "y̅ = Mean value of the target variable" }, { "code": null, "e": 6348, "s": 6335, "text": "For example," }, { "code": null, "e": 6731, "s": 6348, "text": "If we want to build a regression model to predict the height of a person with weight as the independent variable then a possible prediction without much effort is to calculate the mean height of all persons belonging to our sample and consider it as the prediction. The red line in the following diagram shows the mean value of the height of all the persons belonging to our sample." }, { "code": null, "e": 6748, "s": 6731, "text": "Now come to SSR," }, { "code": null, "e": 7079, "s": 6748, "text": "SSR stands for Sum of Squared Residuals. This residual is calculated from the model which we built from our mathematical approach (Linear regression, Bayesian regression, Polynomial regression, or any other approach). If we use a sophisticated approach rather than using a naive approach like mean then our accuracy will increase." }, { "code": null, "e": 7171, "s": 7079, "text": "SSR = Sum (Square (Each data point — Each corresponding data point in the regression line))" }, { "code": null, "e": 7187, "s": 7171, "text": "Mathematically," }, { "code": null, "e": 7194, "s": 7187, "text": "where," }, { "code": null, "e": 7221, "s": 7194, "text": "n = Number of observations" }, { "code": null, "e": 7263, "s": 7221, "text": "y = Observed value of the target variable" }, { "code": null, "e": 7307, "s": 7263, "text": "ŷ = Predicted value of the target variable" }, { "code": null, "e": 7515, "s": 7307, "text": "In the above diagram, let’s consider that the blue line indicates the predictions from a sophisticated model with a high-level mathematical analysis. We can see that it has higher accuracy than the red line." }, { "code": null, "e": 7540, "s": 7515, "text": "Now come to the formula," }, { "code": null, "e": 7565, "s": 7540, "text": "R Squared = 1- (SSR/SST)" }, { "code": null, "e": 7571, "s": 7565, "text": "Here," }, { "code": null, "e": 7642, "s": 7571, "text": "SST will be a large number because it is a very poor model (red line)." }, { "code": null, "e": 7757, "s": 7642, "text": "SSR will be a small number because it is the best model we developed after much mathematical analysis (blue line)." }, { "code": null, "e": 7849, "s": 7757, "text": "So, SSR/SST will be a very small number (It will become very small whenever SSR decreases)." }, { "code": null, "e": 7890, "s": 7849, "text": "So, 1- (SSR/SST) will be a large number." }, { "code": null, "e": 7975, "s": 7890, "text": "So we can infer that whenever R Squared goes higher, it means the model is too good." }, { "code": null, "e": 8332, "s": 7975, "text": "This is a generic case but this cannot be applied in many cases where multiple independent variables are present. In the example, we had only one independent variable and one target variable but in the real case, we will have 100’s of independent variables for a single dependent variable. The actual problem is that, out of 100’s of independent variables-" }, { "code": null, "e": 8407, "s": 8332, "text": "Some variables will have a very high correlation with the target variable." }, { "code": null, "e": 8483, "s": 8407, "text": "Some variables will have a very small correlation with the target variable." }, { "code": null, "e": 8543, "s": 8483, "text": "Also, some independent variables will not correlate at all." }, { "code": null, "e": 8834, "s": 8543, "text": "If there is no correlation then what happens is that — “ Our model will automatically try to establish a relationship with dependent and independent variables and proceed with mathematical calculations assuming that the researcher has already eliminated the unwanted independent variables.”" }, { "code": null, "e": 8847, "s": 8834, "text": "For example," }, { "code": null, "e": 8935, "s": 8847, "text": "For predicting the height of a person, we will have the following independent variables" }, { "code": null, "e": 8963, "s": 8935, "text": "Weight ( High correlation )" }, { "code": null, "e": 8994, "s": 8963, "text": "Phone number( No correlation )" }, { "code": null, "e": 9023, "s": 8994, "text": "Location ( Low correlation )" }, { "code": null, "e": 9048, "s": 9023, "text": "Age ( High correlation )" }, { "code": null, "e": 9075, "s": 9048, "text": "Gender ( Low correlation )" }, { "code": null, "e": 9519, "s": 9075, "text": "Here, only weight and age are enough to build an accurate model but the model will assume that the phone number will also influence the height and represent it in a multidimensional space. When a regression plane is built through these 5 independent variables, its gradient, intercept, cost, and residual will automatically adjust to increase the accuracy. When the accuracy gets increases artificially, obviously R squared will also increase." }, { "code": null, "e": 9814, "s": 9519, "text": "In such scenarios, the regression plane will touch all the edges of the original data points in the multidimensional space. It will make the SSR a very small number and that will eventually make the R Squared a very high number but when test data is introduced, such models will fail miserably." }, { "code": null, "e": 9898, "s": 9814, "text": "That is the reason why a high R Squared value does not guarantee an accurate model." }, { "code": null, "e": 10000, "s": 9898, "text": "For overcoming the challenge mentioned above, we have an additional metric called Adjusted R Squared." }, { "code": null, "e": 10066, "s": 10000, "text": "Adjusted R Squared= 1 — [ ( (1 — R Squared) * (n-1) ) / (n-p-1) ]" }, { "code": null, "e": 10073, "s": 10066, "text": "where," }, { "code": null, "e": 10110, "s": 10073, "text": "p = number of independent variables." }, { "code": null, "e": 10149, "s": 10110, "text": "n = number of records in the data set." }, { "code": null, "e": 10222, "s": 10149, "text": "For a simple representation, we can rewrite the above formula like this-" }, { "code": null, "e": 10254, "s": 10222, "text": "Adjusted R Squared= 1 — (A * B)" }, { "code": null, "e": 10261, "s": 10254, "text": "where," }, { "code": null, "e": 10279, "s": 10261, "text": "A = 1 — R Squared" }, { "code": null, "e": 10299, "s": 10279, "text": "B = (n-1) / (n-p-1)" }, { "code": null, "e": 10377, "s": 10299, "text": "From the above formula, we can impulsively consider the following inferences-" }, { "code": null, "e": 10466, "s": 10377, "text": "When the number of predictor variables increases, it will decrease the whole value of B." }, { "code": null, "e": 10544, "s": 10466, "text": "When the value of R Squared increases, it will decrease the whole value of A." }, { "code": null, "e": 10676, "s": 10544, "text": "Hence technically, it penalizes the value of both A and B if either R Squared is high or the number of predictor variables is high." }, { "code": null, "e": 10743, "s": 10676, "text": "If we multiply both A and B then it will be a much smaller number." }, { "code": null, "e": 10864, "s": 10743, "text": "If we subtract the product of A and B from 1 then it will be a value definitively less than 1 unless the value of p = 1." }, { "code": null, "e": 11117, "s": 10864, "text": "Not only the difference between R Squared and Adjusted R squared but also the value of Adjusted R Squared itself can be considered as a goodness of fit metric replacing the limitations of R Squared for evaluating the envisaged consistency of the model." }, { "code": null, "e": 11427, "s": 11117, "text": "In summary, whenever the number of independent variables gets increases, it will penalize the formula so that the total value will come down. It is least affected by the increase of independent variables. Hence, Adjusted R Squared will more accurately indicate the performance of the model than the R Squared." }, { "code": null, "e": 11488, "s": 11427, "text": "Yes. It can be also a negative value in some rare scenarios." }, { "code": null, "e": 11525, "s": 11488, "text": "Since, R squared = 1 — ( SSR / SST )" }, { "code": null, "e": 11905, "s": 11525, "text": "It is calculated on an assumption that the average line of the target which is a perpendicular line of the y-axis is the worst fit a model can have at a maximum riskiest case. SST is the squared difference between this average line and original data points. Similarly, SSR is the squared difference between the predicted data points (by the model plane) and original data points." }, { "code": null, "e": 12178, "s": 11905, "text": "SSR/SST gives a ratio that indicates, “How SSR is worst with respect to SST ? ”. If your model can somewhat build a plane that is comparatively good than the worst, then in 99% cases SSR< SST. It eventually makes R squared as positive if you substitute it in the equation." }, { "code": null, "e": 12362, "s": 12178, "text": "But what if SSR >SST? This means that your regression plane is worse than the mean line (SST). In this case, R squared will be negative. But it happens only in 1% of cases or smaller." }, { "code": null, "e": 12885, "s": 12362, "text": "Despite being a well-known and mass accepted performance evaluation measure, R Squared suffers from many debased inference deliver-ability in some conditions which are not in its scope. However, it is to be accepted there is no magic wand that can completely represent the inherent disposition of a regression model to 100%. The Adjusted R Squared is such a metric that can domesticate the limitations of R Squared to a great extent and that remains as a prime reason for being the pet of data scientists across the globe." }, { "code": null, "e": 13234, "s": 12885, "text": "Although it is not in the scope of this article, please have a look at some other performance evaluation metrics which we usually use in regression and forecasting here like MAE, MSE, RMSE, MAPE, etc. It will give you a more congenital perspective of model evaluation dealing with continuous variables apart from what we have discussed here so far." }, { "code": null, "e": 13428, "s": 13234, "text": "I hope that now you got an intuitive understanding of the principle and derivation of R Squared and Adjusted R Squared and how they need to be implemented at the right places and right timings." }, { "code": null, "e": 13481, "s": 13428, "text": "You can connect with me via the following platforms-" }, { "code": null, "e": 13524, "s": 13481, "text": "QuoraLinkedInGmail — sanjayjsw05@gmail.com" }, { "code": null, "e": 13530, "s": 13524, "text": "Quora" }, { "code": null, "e": 13539, "s": 13530, "text": "LinkedIn" }, { "code": null, "e": 13569, "s": 13539, "text": "Gmail — sanjayjsw05@gmail.com" }, { "code": null, "e": 13959, "s": 13569, "text": "Sougata Deb, A Novel Robust R-Squared Measure and Its Applications in Linear Regression (2016)Kazhurio Ohtani and Hisashi Tanizaki, Exact distribution of R2 and Adjusted R2 in a linear regression model with multivariate t error terms (2004)Carrodus, M.L., and Giles, D.E.A, The exact distribution of R2 when regression disturbances are autocorrelated, Economics Letters, 38, 375–380 (1992)" }, { "code": null, "e": 14054, "s": 13959, "text": "Sougata Deb, A Novel Robust R-Squared Measure and Its Applications in Linear Regression (2016)" }, { "code": null, "e": 14201, "s": 14054, "text": "Kazhurio Ohtani and Hisashi Tanizaki, Exact distribution of R2 and Adjusted R2 in a linear regression model with multivariate t error terms (2004)" }, { "code": null, "e": 14351, "s": 14201, "text": "Carrodus, M.L., and Giles, D.E.A, The exact distribution of R2 when regression disturbances are autocorrelated, Economics Letters, 38, 375–380 (1992)" } ]
Weka - Quick Guide
The foundation of any Machine Learning application is data - not just a little data but a huge data which is termed as Big Data in the current terminology. To train the machine to analyze big data, you need to have several considerations on the data − The data must be clean. It should not contain null values. Besides, not all the columns in the data table would be useful for the type of analytics that you are trying to achieve. The irrelevant data columns or ‘features’ as termed in Machine Learning terminology, must be removed before the data is fed into a machine learning algorithm. In short, your big data needs lots of preprocessing before it can be used for Machine Learning. Once the data is ready, you would apply various Machine Learning algorithms such as classification, regression, clustering and so on to solve the problem at your end. The type of algorithms that you apply is based largely on your domain knowledge. Even within the same type, for example classification, there are several algorithms available. You may like to test the different algorithms under the same class to build an efficient machine learning model. While doing so, you would prefer visualization of the processed data and thus you also require visualization tools. In the upcoming chapters, you will learn about Weka, a software that accomplishes all the above with ease and lets you work with big data comfortably. WEKA - an open source software provides tools for data preprocessing, implementation of several Machine Learning algorithms, and visualization tools so that you can develop machine learning techniques and apply them to real-world data mining problems. What WEKA offers is summarized in the following diagram − If you observe the beginning of the flow of the image, you will understand that there are many stages in dealing with Big Data to make it suitable for machine learning − First, you will start with the raw data collected from the field. This data may contain several null values and irrelevant fields. You use the data preprocessing tools provided in WEKA to cleanse the data. Then, you would save the preprocessed data in your local storage for applying ML algorithms. Next, depending on the kind of ML model that you are trying to develop you would select one of the options such as Classify, Cluster, or Associate. The Attributes Selection allows the automatic selection of features to create a reduced dataset. Note that under each category, WEKA provides the implementation of several algorithms. You would select an algorithm of your choice, set the desired parameters and run it on the dataset. Then, WEKA would give you the statistical output of the model processing. It provides you a visualization tool to inspect the data. The various models can be applied on the same dataset. You can then compare the outputs of different models and select the best that meets your purpose. Thus, the use of WEKA results in a quicker development of machine learning models on the whole. Now that we have seen what WEKA is and what it does, in the next chapter let us learn how to install WEKA on your local computer. To install WEKA on your machine, visit WEKA’s official website and download the installation file. WEKA supports installation on Windows, Mac OS X and Linux. You just need to follow the instructions on this page to install WEKA for your OS. The steps for installing on Mac are as follows − Download the Mac installation file. Double click on the downloaded weka-3-8-3-corretto-jvm.dmg file. You will see the following screen on successful installation. Click on the weak-3-8-3-corretto-jvm icon to start Weka. Optionally you may start it from the command line − java -jar weka.jar The WEKA GUI Chooser application will start and you would see the following screen − The GUI Chooser application allows you to run five different types of applications as listed here − Explorer Experimenter KnowledgeFlow Workbench Simple CLI We will be using Explorer in this tutorial. In this chapter, let us look into various functionalities that the explorer provides for working with big data. When you click on the Explorer button in the Applications selector, it opens the following screen − On the top, you will see several tabs as listed here − Preprocess Classify Cluster Associate Select Attributes Visualize Under these tabs, there are several pre-implemented machine learning algorithms. Let us look into each of them in detail now. Initially as you open the explorer, only the Preprocess tab is enabled. The first step in machine learning is to preprocess the data. Thus, in the Preprocess option, you will select the data file, process it and make it fit for applying the various machine learning algorithms. The Classify tab provides you several machine learning algorithms for the classification of your data. To list a few, you may apply algorithms such as Linear Regression, Logistic Regression, Support Vector Machines, Decision Trees, RandomTree, RandomForest, NaiveBayes, and so on. The list is very exhaustive and provides both supervised and unsupervised machine learning algorithms. Under the Cluster tab, there are several clustering algorithms provided - such as SimpleKMeans, FilteredClusterer, HierarchicalClusterer, and so on. Under the Associate tab, you would find Apriori, FilteredAssociator and FPGrowth. Select Attributes allows you feature selections based on several algorithms such as ClassifierSubsetEval, PrinicipalComponents, etc. Lastly, the Visualize option allows you to visualize your processed data for analysis. As you noticed, WEKA provides several ready-to-use algorithms for testing and building your machine learning applications. To use WEKA effectively, you must have a sound knowledge of these algorithms, how they work, which one to choose under what circumstances, what to look for in their processed output, and so on. In short, you must have a solid foundation in machine learning to use WEKA effectively in building your apps. In the upcoming chapters, you will study each tab in the explorer in depth. In this chapter, we start with the first tab that you use to preprocess the data. This is common to all algorithms that you would apply to your data for building the model and is a common step for all subsequent operations in WEKA. For a machine learning algorithm to give acceptable accuracy, it is important that you must cleanse your data first. This is because the raw data collected from the field may contain null values, irrelevant columns and so on. In this chapter, you will learn how to preprocess the raw data and create a clean, meaningful dataset for further use. First, you will learn to load the data file into the WEKA explorer. The data can be loaded from the following sources − Local file system Web Database In this chapter, we will see all the three options of loading data in detail. Just under the Machine Learning tabs that you studied in the previous lesson, you would find the following three buttons − Open file ... Open URL ... Open DB ... Click on the Open file ... button. A directory navigator window opens as shown in the following screen − Now, navigate to the folder where your data files are stored. WEKA installation comes up with many sample databases for you to experiment. These are available in the data folder of the WEKA installation. For learning purpose, select any data file from this folder. The contents of the file would be loaded in the WEKA environment. We will very soon learn how to inspect and process this loaded data. Before that, let us look at how to load the data file from the Web. Once you click on the Open URL ... button, you can see a window as follows − We will open the file from a public URL Type the following URL in the popup box − https://storm.cis.fordham.edu/~gweiss/data-mining/weka-data/weather.nominal.arff You may specify any other URL where your data is stored. The Explorer will load the data from the remote site into its environment. Once you click on the Open DB ... button, you can see a window as follows − Set the connection string to your database, set up the query for data selection, process the query and load the selected records in WEKA. WEKA supports a large number of file formats for the data. Here is the complete list − arff arff.gz bsi csv dat data json json.gz libsvm m names xrff xrff.gz The types of files that it supports are listed in the drop-down list box at the bottom of the screen. This is shown in the screenshot given below. As you would notice it supports several formats including CSV and JSON. The default file type is Arff. An Arff file contains two sections - header and data. The header describes the attribute types. The data section contains a comma separated list of data. As an example for Arff format, the Weather data file loaded from the WEKA sample databases is shown below − From the screenshot, you can infer the following points − The @relation tag defines the name of the database. The @relation tag defines the name of the database. The @attribute tag defines the attributes. The @attribute tag defines the attributes. The @data tag starts the list of data rows each containing the comma separated fields. The @data tag starts the list of data rows each containing the comma separated fields. The attributes can take nominal values as in the case of outlook shown here − The attributes can take nominal values as in the case of outlook shown here − @attribute outlook (sunny, overcast, rainy) The attributes can take real values as in this case − The attributes can take real values as in this case − @attribute temperature real You can also set a Target or a Class variable called play as shown here − You can also set a Target or a Class variable called play as shown here − @attribute play (yes, no) The Target assumes two nominal values yes or no. The Target assumes two nominal values yes or no. The Explorer can load the data in any of the earlier mentioned formats. As arff is the preferred format in WEKA, you may load the data from any format and save it to arff format for later use. After preprocessing the data, just save it to arff format for further analysis. Now that you have learned how to load data into WEKA, in the next chapter, you will learn how to preprocess the data. The data that is collected from the field contains many unwanted things that leads to wrong analysis. For example, the data may contain null fields, it may contain columns that are irrelevant to the current analysis, and so on. Thus, the data must be preprocessed to meet the requirements of the type of analysis you are seeking. This is the done in the preprocessing module. To demonstrate the available features in preprocessing, we will use the Weather database that is provided in the installation. Using the Open file ... option under the Preprocess tag select the weather-nominal.arff file. When you open the file, your screen looks like as shown here − This screen tells us several things about the loaded data, which are discussed further in this chapter. Let us first look at the highlighted Current relation sub window. It shows the name of the database that is currently loaded. You can infer two points from this sub window − There are 14 instances - the number of rows in the table. There are 14 instances - the number of rows in the table. The table contains 5 attributes - the fields, which are discussed in the upcoming sections. The table contains 5 attributes - the fields, which are discussed in the upcoming sections. On the left side, notice the Attributes sub window that displays the various fields in the database. The weather database contains five fields - outlook, temperature, humidity, windy and play. When you select an attribute from this list by clicking on it, further details on the attribute itself are displayed on the right hand side. Let us select the temperature attribute first. When you click on it, you would see the following screen − In the Selected Attribute subwindow, you can observe the following − The name and the type of the attribute are displayed. The name and the type of the attribute are displayed. The type for the temperature attribute is Nominal. The type for the temperature attribute is Nominal. The number of Missing values is zero. The number of Missing values is zero. There are three distinct values with no unique value. There are three distinct values with no unique value. The table underneath this information shows the nominal values for this field as hot, mild and cold. The table underneath this information shows the nominal values for this field as hot, mild and cold. It also shows the count and weight in terms of a percentage for each nominal value. It also shows the count and weight in terms of a percentage for each nominal value. At the bottom of the window, you see the visual representation of the class values. If you click on the Visualize All button, you will be able to see all features in one single window as shown here − Many a time, the data that you want to use for model building comes with many irrelevant fields. For example, the customer database may contain his mobile number which is relevant in analysing his credit rating. To remove Attribute/s select them and click on the Remove button at the bottom. The selected attributes would be removed from the database. After you fully preprocess the data, you can save it for model building. Next, you will learn to preprocess the data by applying filters on this data. Some of the machine learning techniques such as association rule mining requires categorical data. To illustrate the use of filters, we will use weather-numeric.arff database that contains two numeric attributes - temperature and humidity. We will convert these to nominal by applying a filter on our raw data. Click on the Choose button in the Filter subwindow and select the following filter − weka→filters→supervised→attribute→Discretize Click on the Apply button and examine the temperature and/or humidity attribute. You will notice that these have changed from numeric to nominal types. Let us look into another filter now. Suppose you want to select the best attributes for deciding the play. Select and apply the following filter − weka→filters→supervised→attribute→AttributeSelection You will notice that it removes the temperature and humidity attributes from the database. After you are satisfied with the preprocessing of your data, save the data by clicking the Save ... button. You will use this saved file for model building. In the next chapter, we will explore the model building using several predefined ML algorithms. Many machine learning applications are classification related. For example, you may like to classify a tumor as malignant or benign. You may like to decide whether to play an outside game depending on the weather conditions. Generally, this decision is dependent on several features/conditions of the weather. So you may prefer to use a tree classifier to make your decision of whether to play or not. In this chapter, we will learn how to build such a tree classifier on weather data to decide on the playing conditions. We will use the preprocessed weather data file from the previous lesson. Open the saved file by using the Open file ... option under the Preprocess tab, click on the Classify tab, and you would see the following screen − Before you learn about the available classifiers, let us examine the Test options. You will notice four testing options as listed below − Training set Supplied test set Cross-validation Percentage split Unless you have your own training set or a client supplied test set, you would use cross-validation or percentage split options. Under cross-validation, you can set the number of folds in which entire data would be split and used during each iteration of training. In the percentage split, you will split the data between training and testing using the set split percentage. Now, keep the default play option for the output class − Next, you will select the classifier. Click on the Choose button and select the following classifier − weka→classifiers>trees>J48 This is shown in the screenshot below − Click on the Start button to start the classification process. After a while, the classification results would be presented on your screen as shown here − Let us examine the output shown on the right hand side of the screen. It says the size of the tree is 6. You will very shortly see the visual representation of the tree. In the Summary, it says that the correctly classified instances as 2 and the incorrectly classified instances as 3, It also says that the Relative absolute error is 110%. It also shows the Confusion Matrix. Going into the analysis of these results is beyond the scope of this tutorial. However, you can easily make out from these results that the classification is not acceptable and you will need more data for analysis, to refine your features selection, rebuild the model and so on until you are satisfied with the model’s accuracy. Anyway, that’s what WEKA is all about. It allows you to test your ideas quickly. To see the visual representation of the results, right click on the result in the Result list box. Several options would pop up on the screen as shown here − Select Visualize tree to get a visual representation of the traversal tree as seen in the screenshot below − Selecting Visualize classifier errors would plot the results of classification as shown here − A cross represents a correctly classified instance while squares represents incorrectly classified instances. At the lower left corner of the plot you see a cross that indicates if outlook is sunny then play the game. So this is a correctly classified instance. To locate instances, you can introduce some jitter in it by sliding the jitter slide bar. The current plot is outlook versus play. These are indicated by the two drop down list boxes at the top of the screen. Now, try a different selection in each of these boxes and notice how the X & Y axes change. The same can be achieved by using the horizontal strips on the right hand side of the plot. Each strip represents an attribute. Left click on the strip sets the selected attribute on the X-axis while a right click would set it on the Y-axis. There are several other plots provided for your deeper analysis. Use them judiciously to fine tune your model. One such plot of Cost/Benefit analysis is shown below for your quick reference. Explaining the analysis in these charts is beyond the scope of this tutorial. The reader is encouraged to brush up their knowledge of analysis of machine learning algorithms. In the next chapter, we will learn the next set of machine learning algorithms, that is clustering. A clustering algorithm finds groups of similar instances in the entire dataset. WEKA supports several clustering algorithms such as EM, FilteredClusterer, HierarchicalClusterer, SimpleKMeans and so on. You should understand these algorithms completely to fully exploit the WEKA capabilities. As in the case of classification, WEKA allows you to visualize the detected clusters graphically. To demonstrate the clustering, we will use the provided iris database. The data set contains three classes of 50 instances each. Each class refers to a type of iris plant. In the WEKA explorer select the Preprocess tab. Click on the Open file ... option and select the iris.arff file in the file selection dialog. When you load the data, the screen looks like as shown below − You can observe that there are 150 instances and 5 attributes. The names of attributes are listed as sepallength, sepalwidth, petallength, petalwidth and class. The first four attributes are of numeric type while the class is a nominal type with 3 distinct values. Examine each attribute to understand the features of the database. We will not do any preprocessing on this data and straight-away proceed to model building. Click on the Cluster TAB to apply the clustering algorithms to our loaded data. Click on the Choose button. You will see the following screen − Now, select EM as the clustering algorithm. In the Cluster mode sub window, select the Classes to clusters evaluation option as shown in the screenshot below − Click on the Start button to process the data. After a while, the results will be presented on the screen. Next, let us study the results. The output of the data processing is shown in the screen below − From the output screen, you can observe that − There are 5 clustered instances detected in the database. There are 5 clustered instances detected in the database. The Cluster 0 represents setosa, Cluster 1 represents virginica, Cluster 2 represents versicolor, while the last two clusters do not have any class associated with them. The Cluster 0 represents setosa, Cluster 1 represents virginica, Cluster 2 represents versicolor, while the last two clusters do not have any class associated with them. If you scroll up the output window, you will also see some statistics that gives the mean and standard deviation for each of the attributes in the various detected clusters. This is shown in the screenshot given below − Next, we will look at the visual representation of the clusters. To visualize the clusters, right click on the EM result in the Result list. You will see the following options − Select Visualize cluster assignments. You will see the following output − As in the case of classification, you will notice the distinction between the correctly and incorrectly identified instances. You can play around by changing the X and Y axes to analyze the results. You may use jittering as in the case of classification to find out the concentration of correctly identified instances. The operations in visualization plot are similar to the one you studied in the case of classification. To demonstrate the power of WEKA, let us now look into an application of another clustering algorithm. In the WEKA explorer, select the HierarchicalClusterer as your ML algorithm as shown in the screenshot shown below − Choose the Cluster mode selection to Classes to cluster evaluation, and click on the Start button. You will see the following output − Notice that in the Result list, there are two results listed: the first one is the EM result and the second one is the current Hierarchical. Likewise, you can apply multiple ML algorithms to the same dataset and quickly compare their results. If you examine the tree produced by this algorithm, you will see the following output − In the next chapter, you will study the Associate type of ML algorithms. It was observed that people who buy beer also buy diapers at the same time. That is there is an association in buying beer and diapers together. Though this seems not well convincing, this association rule was mined from huge databases of supermarkets. Similarly, an association may be found between peanut butter and bread. Finding such associations becomes vital for supermarkets as they would stock diapers next to beers so that customers can locate both items easily resulting in an increased sale for the supermarket. The Apriori algorithm is one such algorithm in ML that finds out the probable associations and creates association rules. WEKA provides the implementation of the Apriori algorithm. You can define the minimum support and an acceptable confidence level while computing these rules. You will apply the Apriori algorithm to the supermarket data provided in the WEKA installation. In the WEKA explorer, open the Preprocess tab, click on the Open file ... button and select supermarket.arff database from the installation folder. After the data is loaded you will see the following screen − The database contains 4627 instances and 217 attributes. You can easily understand how difficult it would be to detect the association between such a large number of attributes. Fortunately, this task is automated with the help of Apriori algorithm. Click on the Associate TAB and click on the Choose button. Select the Apriori association as shown in the screenshot − To set the parameters for the Apriori algorithm, click on its name, a window will pop up as shown below that allows you to set the parameters − After you set the parameters, click the Start button. After a while you will see the results as shown in the screenshot below − At the bottom, you will find the detected best rules of associations. This will help the supermarket in stocking their products in appropriate shelves. When a database contains a large number of attributes, there will be several attributes which do not become significant in the analysis that you are currently seeking. Thus, removing the unwanted attributes from the dataset becomes an important task in developing a good machine learning model. You may examine the entire dataset visually and decide on the irrelevant attributes. This could be a huge task for databases containing a large number of attributes like the supermarket case that you saw in an earlier lesson. Fortunately, WEKA provides an automated tool for feature selection. This chapter demonstrate this feature on a database containing a large number of attributes. In the Preprocess tag of the WEKA explorer, select the labor.arff file for loading into the system. When you load the data, you will see the following screen − Notice that there are 17 attributes. Our task is to create a reduced dataset by eliminating some of the attributes which are irrelevant to our analysis. Click on the Select attributesTAB.You will see the following screen − Under the Attribute Evaluator and Search Method, you will find several options. We will just use the defaults here. In the Attribute Selection Mode, use full training set option. Click on the Start button to process the dataset. You will see the following output − At the bottom of the result window, you will get the list of Selected attributes. To get the visual representation, right click on the result in the Result list. The output is shown in the following screenshot − Clicking on any of the squares will give you the data plot for your further analysis. A typical data plot is shown below − This is similar to the ones we have seen in the earlier chapters. Play around with the different options available to analyze the results. You have seen so far the power of WEKA in quickly developing machine learning models. What we used is a graphical tool called Explorer for developing these models. WEKA also provides a command line interface that gives you more power than provided in the explorer. Clicking the Simple CLI button in the GUI Chooser application starts this command line interface which is shown in the screenshot below − Type your commands in the input box at the bottom. You will be able to do all that you have done so far in the explorer plus much more. Refer to WEKA documentation (https://www.cs.waikato.ac.nz/ml/weka/documentation.html) for further details. Lastly, WEKA is developed in Java and provides an interface to its API. So if you are a Java developer and keen to include WEKA ML implementations in your own Java projects, you can do so easily. WEKA is a powerful tool for developing machine learning models. It provides implementation of several most widely used ML algorithms. Before these algorithms are applied to your dataset, it also allows you to preprocess the data. The types of algorithms that are supported are classified under Classify, Cluster, Associate, and Select attributes. The result at various stages of processing can be visualized with a beautiful and powerful visual representation. This makes it easier for a Data Scientist to quickly apply the various machine learning techniques on his dataset, compare the results and create the best model for the final use. 6 Lectures 3 hours DATAhill Solutions Srinivas Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 1950, "s": 1794, "text": "The foundation of any Machine Learning application is data - not just a little data but a huge data which is termed as Big Data in the current terminology." }, { "code": null, "e": 2046, "s": 1950, "text": "To train the machine to analyze big data, you need to have several considerations on the data −" }, { "code": null, "e": 2070, "s": 2046, "text": "The data must be clean." }, { "code": null, "e": 2105, "s": 2070, "text": "It should not contain null values." }, { "code": null, "e": 2385, "s": 2105, "text": "Besides, not all the columns in the data table would be useful for the type of analytics that you are trying to achieve. The irrelevant data columns or ‘features’ as termed in Machine Learning terminology, must be removed before the data is fed into a machine learning algorithm." }, { "code": null, "e": 2648, "s": 2385, "text": "In short, your big data needs lots of preprocessing before it can be used for Machine Learning. Once the data is ready, you would apply various Machine Learning algorithms such as classification, regression, clustering and so on to solve the problem at your end." }, { "code": null, "e": 3053, "s": 2648, "text": "The type of algorithms that you apply is based largely on your domain knowledge. Even within the same type, for example classification, there are several algorithms available. You may like to test the different algorithms under the same class to build an efficient machine learning model. While doing so, you would prefer visualization of the processed data and thus you also require visualization tools." }, { "code": null, "e": 3204, "s": 3053, "text": "In the upcoming chapters, you will learn about Weka, a software that accomplishes all the above with ease and lets you work with big data comfortably." }, { "code": null, "e": 3514, "s": 3204, "text": "WEKA - an open source software provides tools for data preprocessing, implementation of several Machine Learning algorithms, and visualization tools so that you can develop machine learning techniques and apply them to real-world data mining problems. What WEKA offers is summarized in the following diagram −" }, { "code": null, "e": 3684, "s": 3514, "text": "If you observe the beginning of the flow of the image, you will understand that there are many stages in dealing with Big Data to make it suitable for machine learning −" }, { "code": null, "e": 3890, "s": 3684, "text": "First, you will start with the raw data collected from the field. This data may contain several null values and irrelevant fields. You use the data preprocessing tools provided in WEKA to cleanse the data." }, { "code": null, "e": 3983, "s": 3890, "text": "Then, you would save the preprocessed data in your local storage for applying ML algorithms." }, { "code": null, "e": 4228, "s": 3983, "text": "Next, depending on the kind of ML model that you are trying to develop you would select one of the options such as Classify, Cluster, or Associate. The Attributes Selection allows the automatic selection of features to create a reduced dataset." }, { "code": null, "e": 4415, "s": 4228, "text": "Note that under each category, WEKA provides the implementation of several algorithms. You would select an algorithm of your choice, set the desired parameters and run it on the dataset." }, { "code": null, "e": 4547, "s": 4415, "text": "Then, WEKA would give you the statistical output of the model processing. It provides you a visualization tool to inspect the data." }, { "code": null, "e": 4700, "s": 4547, "text": "The various models can be applied on the same dataset. You can then compare the outputs of different models and select the best that meets your purpose." }, { "code": null, "e": 4796, "s": 4700, "text": "Thus, the use of WEKA results in a quicker development of machine learning models on the whole." }, { "code": null, "e": 4926, "s": 4796, "text": "Now that we have seen what WEKA is and what it does, in the next chapter let us learn how to install WEKA on your local computer." }, { "code": null, "e": 5167, "s": 4926, "text": "To install WEKA on your machine, visit WEKA’s official website and download the installation file. WEKA supports installation on Windows, Mac OS X and Linux. You just need to follow the instructions on this page to install WEKA for your OS." }, { "code": null, "e": 5216, "s": 5167, "text": "The steps for installing on Mac are as follows −" }, { "code": null, "e": 5252, "s": 5216, "text": "Download the Mac installation file." }, { "code": null, "e": 5317, "s": 5252, "text": "Double click on the downloaded weka-3-8-3-corretto-jvm.dmg file." }, { "code": null, "e": 5379, "s": 5317, "text": "You will see the following screen on successful installation." }, { "code": null, "e": 5436, "s": 5379, "text": "Click on the weak-3-8-3-corretto-jvm icon to start Weka." }, { "code": null, "e": 5488, "s": 5436, "text": "Optionally you may start it from the command line −" }, { "code": null, "e": 5508, "s": 5488, "text": "java -jar weka.jar\n" }, { "code": null, "e": 5593, "s": 5508, "text": "The WEKA GUI Chooser application will start and you would see the following screen −" }, { "code": null, "e": 5693, "s": 5593, "text": "The GUI Chooser application allows you to run five different types of applications as listed here −" }, { "code": null, "e": 5702, "s": 5693, "text": "Explorer" }, { "code": null, "e": 5715, "s": 5702, "text": "Experimenter" }, { "code": null, "e": 5729, "s": 5715, "text": "KnowledgeFlow" }, { "code": null, "e": 5739, "s": 5729, "text": "Workbench" }, { "code": null, "e": 5750, "s": 5739, "text": "Simple CLI" }, { "code": null, "e": 5794, "s": 5750, "text": "We will be using Explorer in this tutorial." }, { "code": null, "e": 5906, "s": 5794, "text": "In this chapter, let us look into various functionalities that the explorer provides for working with big data." }, { "code": null, "e": 6006, "s": 5906, "text": "When you click on the Explorer button in the Applications selector, it opens the following screen −" }, { "code": null, "e": 6061, "s": 6006, "text": "On the top, you will see several tabs as listed here −" }, { "code": null, "e": 6072, "s": 6061, "text": "Preprocess" }, { "code": null, "e": 6081, "s": 6072, "text": "Classify" }, { "code": null, "e": 6089, "s": 6081, "text": "Cluster" }, { "code": null, "e": 6099, "s": 6089, "text": "Associate" }, { "code": null, "e": 6117, "s": 6099, "text": "Select Attributes" }, { "code": null, "e": 6127, "s": 6117, "text": "Visualize" }, { "code": null, "e": 6253, "s": 6127, "text": "Under these tabs, there are several pre-implemented machine learning algorithms. Let us look into each of them in detail now." }, { "code": null, "e": 6531, "s": 6253, "text": "Initially as you open the explorer, only the Preprocess tab is enabled. The first step in machine learning is to preprocess the data. Thus, in the Preprocess option, you will select the data file, process it and make it fit for applying the various machine learning algorithms." }, { "code": null, "e": 6915, "s": 6531, "text": "The Classify tab provides you several machine learning algorithms for the classification of your data. To list a few, you may apply algorithms such as Linear Regression, Logistic Regression, Support Vector Machines, Decision Trees, RandomTree, RandomForest, NaiveBayes, and so on. The list is very exhaustive and provides both supervised and unsupervised machine learning algorithms." }, { "code": null, "e": 7064, "s": 6915, "text": "Under the Cluster tab, there are several clustering algorithms provided - such as SimpleKMeans, FilteredClusterer, HierarchicalClusterer, and so on." }, { "code": null, "e": 7146, "s": 7064, "text": "Under the Associate tab, you would find Apriori, FilteredAssociator and FPGrowth." }, { "code": null, "e": 7279, "s": 7146, "text": "Select Attributes allows you feature selections based on several algorithms such as ClassifierSubsetEval, PrinicipalComponents, etc." }, { "code": null, "e": 7366, "s": 7279, "text": "Lastly, the Visualize option allows you to visualize your processed data for analysis." }, { "code": null, "e": 7793, "s": 7366, "text": "As you noticed, WEKA provides several ready-to-use algorithms for testing and building your machine learning applications. To use WEKA effectively, you must have a sound knowledge of these algorithms, how they work, which one to choose under what circumstances, what to look for in their processed output, and so on. In short, you must have a solid foundation in machine learning to use WEKA effectively in building your apps." }, { "code": null, "e": 7869, "s": 7793, "text": "In the upcoming chapters, you will study each tab in the explorer in depth." }, { "code": null, "e": 8101, "s": 7869, "text": "In this chapter, we start with the first tab that you use to preprocess the data. This is common to all algorithms that you would apply to your data for building the model and is a common step for all subsequent operations in WEKA." }, { "code": null, "e": 8327, "s": 8101, "text": "For a machine learning algorithm to give acceptable accuracy, it is important that you must cleanse your data first. This is because the raw data collected from the field may contain null values, irrelevant columns and so on." }, { "code": null, "e": 8446, "s": 8327, "text": "In this chapter, you will learn how to preprocess the raw data and create a clean, meaningful dataset for further use." }, { "code": null, "e": 8566, "s": 8446, "text": "First, you will learn to load the data file into the WEKA explorer. The data can be loaded from the following sources −" }, { "code": null, "e": 8584, "s": 8566, "text": "Local file system" }, { "code": null, "e": 8588, "s": 8584, "text": "Web" }, { "code": null, "e": 8597, "s": 8588, "text": "Database" }, { "code": null, "e": 8675, "s": 8597, "text": "In this chapter, we will see all the three options of loading data in detail." }, { "code": null, "e": 8798, "s": 8675, "text": "Just under the Machine Learning tabs that you studied in the previous lesson, you would find the following three buttons −" }, { "code": null, "e": 8812, "s": 8798, "text": "Open file ..." }, { "code": null, "e": 8825, "s": 8812, "text": "Open URL ..." }, { "code": null, "e": 8837, "s": 8825, "text": "Open DB ..." }, { "code": null, "e": 8942, "s": 8837, "text": "Click on the Open file ... button. A directory navigator window opens as shown in the following screen −" }, { "code": null, "e": 9146, "s": 8942, "text": "Now, navigate to the folder where your data files are stored. WEKA installation comes up with many sample databases for you to experiment. These are available in the data folder of the WEKA installation." }, { "code": null, "e": 9410, "s": 9146, "text": "For learning purpose, select any data file from this folder. The contents of the file would be loaded in the WEKA environment. We will very soon learn how to inspect and process this loaded data. Before that, let us look at how to load the data file from the Web." }, { "code": null, "e": 9487, "s": 9410, "text": "Once you click on the Open URL ... button, you can see a window as follows −" }, { "code": null, "e": 9569, "s": 9487, "text": "We will open the file from a public URL Type the following URL in the popup box −" }, { "code": null, "e": 9650, "s": 9569, "text": "https://storm.cis.fordham.edu/~gweiss/data-mining/weka-data/weather.nominal.arff" }, { "code": null, "e": 9782, "s": 9650, "text": "You may specify any other URL where your data is stored. The Explorer will load the data from the remote site into its environment." }, { "code": null, "e": 9858, "s": 9782, "text": "Once you click on the Open DB ... button, you can see a window as follows −" }, { "code": null, "e": 9996, "s": 9858, "text": "Set the connection string to your database, set up the query for data selection, process the query and load the selected records in WEKA." }, { "code": null, "e": 10083, "s": 9996, "text": "WEKA supports a large number of file formats for the data. Here is the complete list −" }, { "code": null, "e": 10088, "s": 10083, "text": "arff" }, { "code": null, "e": 10096, "s": 10088, "text": "arff.gz" }, { "code": null, "e": 10100, "s": 10096, "text": "bsi" }, { "code": null, "e": 10104, "s": 10100, "text": "csv" }, { "code": null, "e": 10108, "s": 10104, "text": "dat" }, { "code": null, "e": 10113, "s": 10108, "text": "data" }, { "code": null, "e": 10118, "s": 10113, "text": "json" }, { "code": null, "e": 10126, "s": 10118, "text": "json.gz" }, { "code": null, "e": 10133, "s": 10126, "text": "libsvm" }, { "code": null, "e": 10135, "s": 10133, "text": "m" }, { "code": null, "e": 10141, "s": 10135, "text": "names" }, { "code": null, "e": 10146, "s": 10141, "text": "xrff" }, { "code": null, "e": 10154, "s": 10146, "text": "xrff.gz" }, { "code": null, "e": 10301, "s": 10154, "text": "The types of files that it supports are listed in the drop-down list box at the bottom of the screen. This is shown in the screenshot given below." }, { "code": null, "e": 10404, "s": 10301, "text": "As you would notice it supports several formats including CSV and JSON. The default file type is Arff." }, { "code": null, "e": 10458, "s": 10404, "text": "An Arff file contains two sections - header and data." }, { "code": null, "e": 10500, "s": 10458, "text": "The header describes the attribute types." }, { "code": null, "e": 10558, "s": 10500, "text": "The data section contains a comma separated list of data." }, { "code": null, "e": 10666, "s": 10558, "text": "As an example for Arff format, the Weather data file loaded from the WEKA sample databases is shown below −" }, { "code": null, "e": 10724, "s": 10666, "text": "From the screenshot, you can infer the following points −" }, { "code": null, "e": 10776, "s": 10724, "text": "The @relation tag defines the name of the database." }, { "code": null, "e": 10828, "s": 10776, "text": "The @relation tag defines the name of the database." }, { "code": null, "e": 10871, "s": 10828, "text": "The @attribute tag defines the attributes." }, { "code": null, "e": 10914, "s": 10871, "text": "The @attribute tag defines the attributes." }, { "code": null, "e": 11001, "s": 10914, "text": "The @data tag starts the list of data rows each containing the comma separated fields." }, { "code": null, "e": 11088, "s": 11001, "text": "The @data tag starts the list of data rows each containing the comma separated fields." }, { "code": null, "e": 11166, "s": 11088, "text": "The attributes can take nominal values as in the case of outlook shown here −" }, { "code": null, "e": 11244, "s": 11166, "text": "The attributes can take nominal values as in the case of outlook shown here −" }, { "code": null, "e": 11289, "s": 11244, "text": "@attribute outlook (sunny, overcast, rainy)\n" }, { "code": null, "e": 11343, "s": 11289, "text": "The attributes can take real values as in this case −" }, { "code": null, "e": 11397, "s": 11343, "text": "The attributes can take real values as in this case −" }, { "code": null, "e": 11426, "s": 11397, "text": "@attribute temperature real\n" }, { "code": null, "e": 11500, "s": 11426, "text": "You can also set a Target or a Class variable called play as shown here −" }, { "code": null, "e": 11574, "s": 11500, "text": "You can also set a Target or a Class variable called play as shown here −" }, { "code": null, "e": 11601, "s": 11574, "text": "@attribute play (yes, no)\n" }, { "code": null, "e": 11650, "s": 11601, "text": "The Target assumes two nominal values yes or no." }, { "code": null, "e": 11699, "s": 11650, "text": "The Target assumes two nominal values yes or no." }, { "code": null, "e": 11972, "s": 11699, "text": "The Explorer can load the data in any of the earlier mentioned formats. As arff is the preferred format in WEKA, you may load the data from any format and save it to arff format for later use. After preprocessing the data, just save it to arff format for further analysis." }, { "code": null, "e": 12090, "s": 11972, "text": "Now that you have learned how to load data into WEKA, in the next chapter, you will learn how to preprocess the data." }, { "code": null, "e": 12466, "s": 12090, "text": "The data that is collected from the field contains many unwanted things that leads to wrong analysis. For example, the data may contain null fields, it may contain columns that are irrelevant to the current analysis, and so on. Thus, the data must be preprocessed to meet the requirements of the type of analysis you are seeking. This is the done in the preprocessing module." }, { "code": null, "e": 12593, "s": 12466, "text": "To demonstrate the available features in preprocessing, we will use the Weather database that is provided in the installation." }, { "code": null, "e": 12687, "s": 12593, "text": "Using the Open file ... option under the Preprocess tag select the weather-nominal.arff file." }, { "code": null, "e": 12750, "s": 12687, "text": "When you open the file, your screen looks like as shown here −" }, { "code": null, "e": 12854, "s": 12750, "text": "This screen tells us several things about the loaded data, which are discussed further in this chapter." }, { "code": null, "e": 13028, "s": 12854, "text": "Let us first look at the highlighted Current relation sub window. It shows the name of the database that is currently loaded. You can infer two points from this sub window −" }, { "code": null, "e": 13086, "s": 13028, "text": "There are 14 instances - the number of rows in the table." }, { "code": null, "e": 13144, "s": 13086, "text": "There are 14 instances - the number of rows in the table." }, { "code": null, "e": 13236, "s": 13144, "text": "The table contains 5 attributes - the fields, which are discussed in the upcoming sections." }, { "code": null, "e": 13328, "s": 13236, "text": "The table contains 5 attributes - the fields, which are discussed in the upcoming sections." }, { "code": null, "e": 13429, "s": 13328, "text": "On the left side, notice the Attributes sub window that displays the various fields in the database." }, { "code": null, "e": 13662, "s": 13429, "text": "The weather database contains five fields - outlook, temperature, humidity, windy and play. When you select an attribute from this list by clicking on it, further details on the attribute itself are displayed on the right hand side." }, { "code": null, "e": 13768, "s": 13662, "text": "Let us select the temperature attribute first. When you click on it, you would see the following screen −" }, { "code": null, "e": 13837, "s": 13768, "text": "In the Selected Attribute subwindow, you can observe the following −" }, { "code": null, "e": 13891, "s": 13837, "text": "The name and the type of the attribute are displayed." }, { "code": null, "e": 13945, "s": 13891, "text": "The name and the type of the attribute are displayed." }, { "code": null, "e": 13996, "s": 13945, "text": "The type for the temperature attribute is Nominal." }, { "code": null, "e": 14047, "s": 13996, "text": "The type for the temperature attribute is Nominal." }, { "code": null, "e": 14085, "s": 14047, "text": "The number of Missing values is zero." }, { "code": null, "e": 14123, "s": 14085, "text": "The number of Missing values is zero." }, { "code": null, "e": 14177, "s": 14123, "text": "There are three distinct values with no unique value." }, { "code": null, "e": 14231, "s": 14177, "text": "There are three distinct values with no unique value." }, { "code": null, "e": 14332, "s": 14231, "text": "The table underneath this information shows the nominal values for this field as hot, mild and cold." }, { "code": null, "e": 14433, "s": 14332, "text": "The table underneath this information shows the nominal values for this field as hot, mild and cold." }, { "code": null, "e": 14517, "s": 14433, "text": "It also shows the count and weight in terms of a percentage for each nominal value." }, { "code": null, "e": 14601, "s": 14517, "text": "It also shows the count and weight in terms of a percentage for each nominal value." }, { "code": null, "e": 14685, "s": 14601, "text": "At the bottom of the window, you see the visual representation of the class values." }, { "code": null, "e": 14801, "s": 14685, "text": "If you click on the Visualize All button, you will be able to see all features in one single window as shown here −" }, { "code": null, "e": 15013, "s": 14801, "text": "Many a time, the data that you want to use for model building comes with many irrelevant fields. For example, the customer database may contain his mobile number which is relevant in analysing his credit rating." }, { "code": null, "e": 15093, "s": 15013, "text": "To remove Attribute/s select them and click on the Remove button at the bottom." }, { "code": null, "e": 15226, "s": 15093, "text": "The selected attributes would be removed from the database. After you fully preprocess the data, you can save it for model building." }, { "code": null, "e": 15304, "s": 15226, "text": "Next, you will learn to preprocess the data by applying filters on this data." }, { "code": null, "e": 15544, "s": 15304, "text": "Some of the machine learning techniques such as association rule mining requires categorical data. To illustrate the use of filters, we will use weather-numeric.arff database that contains two numeric attributes - temperature and humidity." }, { "code": null, "e": 15700, "s": 15544, "text": "We will convert these to nominal by applying a filter on our raw data. Click on the Choose button in the Filter subwindow and select the following filter −" }, { "code": null, "e": 15745, "s": 15700, "text": "weka→filters→supervised→attribute→Discretize" }, { "code": null, "e": 15897, "s": 15745, "text": "Click on the Apply button and examine the temperature and/or humidity attribute. You will notice that these have changed from numeric to nominal types." }, { "code": null, "e": 16044, "s": 15897, "text": "Let us look into another filter now. Suppose you want to select the best attributes for deciding the play. Select and apply the following filter −" }, { "code": null, "e": 16097, "s": 16044, "text": "weka→filters→supervised→attribute→AttributeSelection" }, { "code": null, "e": 16188, "s": 16097, "text": "You will notice that it removes the temperature and humidity attributes from the database." }, { "code": null, "e": 16345, "s": 16188, "text": "After you are satisfied with the preprocessing of your data, save the data by clicking the Save ... button. You will use this saved file for model building." }, { "code": null, "e": 16441, "s": 16345, "text": "In the next chapter, we will explore the model building using several predefined ML algorithms." }, { "code": null, "e": 16843, "s": 16441, "text": "Many machine learning applications are classification related. For example, you may like to classify a tumor as malignant or benign. You may like to decide whether to play an outside game depending on the weather conditions. Generally, this decision is dependent on several features/conditions of the weather. So you may prefer to use a tree classifier to make your decision of whether to play or not." }, { "code": null, "e": 16963, "s": 16843, "text": "In this chapter, we will learn how to build such a tree classifier on weather data to decide on the playing conditions." }, { "code": null, "e": 17184, "s": 16963, "text": "We will use the preprocessed weather data file from the previous lesson. Open the saved file by using the Open file ... option under the Preprocess tab, click on the Classify tab, and you would see the following screen −" }, { "code": null, "e": 17322, "s": 17184, "text": "Before you learn about the available classifiers, let us examine the Test options. You will notice four testing options as listed below −" }, { "code": null, "e": 17335, "s": 17322, "text": "Training set" }, { "code": null, "e": 17353, "s": 17335, "text": "Supplied test set" }, { "code": null, "e": 17370, "s": 17353, "text": "Cross-validation" }, { "code": null, "e": 17388, "s": 17370, "text": "Percentage split " }, { "code": null, "e": 17763, "s": 17388, "text": "Unless you have your own training set or a client supplied test set, you would use cross-validation or percentage split options. Under cross-validation, you can set the number of folds in which entire data would be split and used during each iteration of training. In the percentage split, you will split the data between training and testing using the set split percentage." }, { "code": null, "e": 17820, "s": 17763, "text": "Now, keep the default play option for the output class −" }, { "code": null, "e": 17858, "s": 17820, "text": "Next, you will select the classifier." }, { "code": null, "e": 17923, "s": 17858, "text": "Click on the Choose button and select the following classifier −" }, { "code": null, "e": 17950, "s": 17923, "text": "weka→classifiers>trees>J48" }, { "code": null, "e": 17990, "s": 17950, "text": "This is shown in the screenshot below −" }, { "code": null, "e": 18145, "s": 17990, "text": "Click on the Start button to start the classification process. After a while, the classification results would be presented on your screen as shown here −" }, { "code": null, "e": 18215, "s": 18145, "text": "Let us examine the output shown on the right hand side of the screen." }, { "code": null, "e": 18932, "s": 18215, "text": "It says the size of the tree is 6. You will very shortly see the visual representation of the tree. In the Summary, it says that the correctly classified instances as 2 and the incorrectly classified instances as 3, It also says that the Relative absolute error is 110%. It also shows the Confusion Matrix. Going into the analysis of these results is beyond the scope of this tutorial. However, you can easily make out from these results that the classification is not acceptable and you will need more data for analysis, to refine your features selection, rebuild the model and so on until you are satisfied with the model’s accuracy. Anyway, that’s what WEKA is all about. It allows you to test your ideas quickly." }, { "code": null, "e": 19090, "s": 18932, "text": "To see the visual representation of the results, right click on the result in the Result list box. Several options would pop up on the screen as shown here −" }, { "code": null, "e": 19199, "s": 19090, "text": "Select Visualize tree to get a visual representation of the traversal tree as seen in the screenshot below −" }, { "code": null, "e": 19294, "s": 19199, "text": "Selecting Visualize classifier errors would plot the results of classification as shown here −" }, { "code": null, "e": 19646, "s": 19294, "text": "A cross represents a correctly classified instance while squares represents incorrectly classified instances. At the lower left corner of the plot you see a cross that indicates if outlook is sunny then play the game. So this is a correctly classified instance. To locate instances, you can introduce some jitter in it by sliding the jitter slide bar." }, { "code": null, "e": 19765, "s": 19646, "text": "The current plot is outlook versus play. These are indicated by the two drop down list boxes at the top of the screen." }, { "code": null, "e": 20099, "s": 19765, "text": "Now, try a different selection in each of these boxes and notice how the X & Y axes change. The same can be achieved by using the horizontal strips on the right hand side of the plot. Each strip represents an attribute. Left click on the strip sets the selected attribute on the X-axis while a right click would set it on the Y-axis." }, { "code": null, "e": 20290, "s": 20099, "text": "There are several other plots provided for your deeper analysis. Use them judiciously to fine tune your model. One such plot of Cost/Benefit analysis is shown below for your quick reference." }, { "code": null, "e": 20465, "s": 20290, "text": "Explaining the analysis in these charts is beyond the scope of this tutorial. The reader is encouraged to brush up their knowledge of analysis of machine learning algorithms." }, { "code": null, "e": 20565, "s": 20465, "text": "In the next chapter, we will learn the next set of machine learning algorithms, that is clustering." }, { "code": null, "e": 20857, "s": 20565, "text": "A clustering algorithm finds groups of similar instances in the entire dataset. WEKA supports several clustering algorithms such as EM, FilteredClusterer, HierarchicalClusterer, SimpleKMeans and so on. You should understand these algorithms completely to fully exploit the WEKA capabilities." }, { "code": null, "e": 21127, "s": 20857, "text": "As in the case of classification, WEKA allows you to visualize the detected clusters graphically. To demonstrate the clustering, we will use the provided iris database. The data set contains three classes of 50 instances each. Each class refers to a type of iris plant." }, { "code": null, "e": 21332, "s": 21127, "text": "In the WEKA explorer select the Preprocess tab. Click on the Open file ... option and select the iris.arff file in the file selection dialog. When you load the data, the screen looks like as shown below −" }, { "code": null, "e": 21755, "s": 21332, "text": "You can observe that there are 150 instances and 5 attributes. The names of attributes are listed as sepallength, sepalwidth, petallength, petalwidth and class. The first four attributes are of numeric type while the class is a nominal type with 3 distinct values. Examine each attribute to understand the features of the database. We will not do any preprocessing on this data and straight-away proceed to model building." }, { "code": null, "e": 21899, "s": 21755, "text": "Click on the Cluster TAB to apply the clustering algorithms to our loaded data. Click on the Choose button. You will see the following screen −" }, { "code": null, "e": 22059, "s": 21899, "text": "Now, select EM as the clustering algorithm. In the Cluster mode sub window, select the Classes to clusters evaluation option as shown in the screenshot below −" }, { "code": null, "e": 22166, "s": 22059, "text": "Click on the Start button to process the data. After a while, the results will be presented on the screen." }, { "code": null, "e": 22198, "s": 22166, "text": "Next, let us study the results." }, { "code": null, "e": 22263, "s": 22198, "text": "The output of the data processing is shown in the screen below −" }, { "code": null, "e": 22310, "s": 22263, "text": "From the output screen, you can observe that −" }, { "code": null, "e": 22368, "s": 22310, "text": "There are 5 clustered instances detected in the database." }, { "code": null, "e": 22426, "s": 22368, "text": "There are 5 clustered instances detected in the database." }, { "code": null, "e": 22596, "s": 22426, "text": "The Cluster 0 represents setosa, Cluster 1 represents virginica, Cluster 2 represents versicolor, while the last two clusters do not have any class associated with them." }, { "code": null, "e": 22766, "s": 22596, "text": "The Cluster 0 represents setosa, Cluster 1 represents virginica, Cluster 2 represents versicolor, while the last two clusters do not have any class associated with them." }, { "code": null, "e": 22986, "s": 22766, "text": "If you scroll up the output window, you will also see some statistics that gives the mean and standard deviation for each of the attributes in the various detected clusters. This is shown in the screenshot given below −" }, { "code": null, "e": 23051, "s": 22986, "text": "Next, we will look at the visual representation of the clusters." }, { "code": null, "e": 23164, "s": 23051, "text": "To visualize the clusters, right click on the EM result in the Result list. You will see the following options −" }, { "code": null, "e": 23238, "s": 23164, "text": "Select Visualize cluster assignments. You will see the following output −" }, { "code": null, "e": 23660, "s": 23238, "text": "As in the case of classification, you will notice the distinction between the correctly and incorrectly identified instances. You can play around by changing the X and Y axes to analyze the results. You may use jittering as in the case of classification to find out the concentration of correctly identified instances. The operations in visualization plot are similar to the one you studied in the case of classification." }, { "code": null, "e": 23880, "s": 23660, "text": "To demonstrate the power of WEKA, let us now look into an application of another clustering algorithm. In the WEKA explorer, select the HierarchicalClusterer as your ML algorithm as shown in the screenshot shown below −" }, { "code": null, "e": 24015, "s": 23880, "text": "Choose the Cluster mode selection to Classes to cluster evaluation, and click on the Start button. You will see the following output −" }, { "code": null, "e": 24258, "s": 24015, "text": "Notice that in the Result list, there are two results listed: the first one is the EM result and the second one is the current Hierarchical. Likewise, you can apply multiple ML algorithms to the same dataset and quickly compare their results." }, { "code": null, "e": 24346, "s": 24258, "text": "If you examine the tree produced by this algorithm, you will see the following output −" }, { "code": null, "e": 24419, "s": 24346, "text": "In the next chapter, you will study the Associate type of ML algorithms." }, { "code": null, "e": 24744, "s": 24419, "text": "It was observed that people who buy beer also buy diapers at the same time. That is there is an association in buying beer and diapers together. Though this seems not well convincing, this association rule was mined from huge databases of supermarkets. Similarly, an association may be found between peanut butter and bread." }, { "code": null, "e": 24942, "s": 24744, "text": "Finding such associations becomes vital for supermarkets as they would stock diapers next to beers so that customers can locate both items easily resulting in an increased sale for the supermarket." }, { "code": null, "e": 25318, "s": 24942, "text": "The Apriori algorithm is one such algorithm in ML that finds out the probable associations and creates association rules. WEKA provides the implementation of the Apriori algorithm. You can define the minimum support and an acceptable confidence level while computing these rules. You will apply the Apriori algorithm to the supermarket data provided in the WEKA installation." }, { "code": null, "e": 25527, "s": 25318, "text": "In the WEKA explorer, open the Preprocess tab, click on the Open file ... button and select supermarket.arff database from the installation folder. After the data is loaded you will see the following screen −" }, { "code": null, "e": 25777, "s": 25527, "text": "The database contains 4627 instances and 217 attributes. You can easily understand how difficult it would be to detect the association between such a large number of attributes. Fortunately, this task is automated with the help of Apriori algorithm." }, { "code": null, "e": 25896, "s": 25777, "text": "Click on the Associate TAB and click on the Choose button. Select the Apriori association as shown in the screenshot −" }, { "code": null, "e": 26040, "s": 25896, "text": "To set the parameters for the Apriori algorithm, click on its name, a window will pop up as shown below that allows you to set the parameters −" }, { "code": null, "e": 26168, "s": 26040, "text": "After you set the parameters, click the Start button. After a while you will see the results as shown in the screenshot below −" }, { "code": null, "e": 26320, "s": 26168, "text": "At the bottom, you will find the detected best rules of associations. This will help the supermarket in stocking their products in appropriate shelves." }, { "code": null, "e": 26615, "s": 26320, "text": "When a database contains a large number of attributes, there will be several attributes which do not become significant in the analysis that you are currently seeking. Thus, removing the unwanted attributes from the dataset becomes an important task in developing a good machine learning model." }, { "code": null, "e": 26909, "s": 26615, "text": "You may examine the entire dataset visually and decide on the irrelevant attributes. This could be a huge task for databases containing a large number of attributes like the supermarket case that you saw in an earlier lesson. Fortunately, WEKA provides an automated tool for feature selection." }, { "code": null, "e": 27002, "s": 26909, "text": "This chapter demonstrate this feature on a database containing a large number of attributes." }, { "code": null, "e": 27162, "s": 27002, "text": "In the Preprocess tag of the WEKA explorer, select the labor.arff file for loading into the system. When you load the data, you will see the following screen −" }, { "code": null, "e": 27315, "s": 27162, "text": "Notice that there are 17 attributes. Our task is to create a reduced dataset by eliminating some of the attributes which are irrelevant to our analysis." }, { "code": null, "e": 27386, "s": 27315, "text": "Click on the Select attributesTAB.You will see the following screen − " }, { "code": null, "e": 27565, "s": 27386, "text": "Under the Attribute Evaluator and Search Method, you will find several options. We will just use the defaults here. In the Attribute Selection Mode, use full training set option." }, { "code": null, "e": 27651, "s": 27565, "text": "Click on the Start button to process the dataset. You will see the following output −" }, { "code": null, "e": 27813, "s": 27651, "text": "At the bottom of the result window, you will get the list of Selected attributes. To get the visual representation, right click on the result in the Result list." }, { "code": null, "e": 27863, "s": 27813, "text": "The output is shown in the following screenshot −" }, { "code": null, "e": 27986, "s": 27863, "text": "Clicking on any of the squares will give you the data plot for your further analysis. A typical data plot is shown below −" }, { "code": null, "e": 28125, "s": 27986, "text": "This is similar to the ones we have seen in the earlier chapters. Play around with the different options available to analyze the results." }, { "code": null, "e": 28390, "s": 28125, "text": "You have seen so far the power of WEKA in quickly developing machine learning models. What we used is a graphical tool called Explorer for developing these models. WEKA also provides a command line interface that gives you more power than provided in the explorer." }, { "code": null, "e": 28528, "s": 28390, "text": "Clicking the Simple CLI button in the GUI Chooser application starts this command line interface which is shown in the screenshot below −" }, { "code": null, "e": 28771, "s": 28528, "text": "Type your commands in the input box at the bottom. You will be able to do all that you have done so far in the explorer plus much more. Refer to WEKA documentation (https://www.cs.waikato.ac.nz/ml/weka/documentation.html) for further details." }, { "code": null, "e": 28967, "s": 28771, "text": "Lastly, WEKA is developed in Java and provides an interface to its API. So if you are a Java developer and keen to include WEKA ML implementations in your own Java projects, you can do so easily." }, { "code": null, "e": 29608, "s": 28967, "text": "WEKA is a powerful tool for developing machine learning models. It provides implementation of several most widely used ML algorithms. Before these algorithms are applied to your dataset, it also allows you to preprocess the data. The types of algorithms that are supported are classified under Classify, Cluster, Associate, and Select attributes. The result at various stages of processing can be visualized with a beautiful and powerful visual representation. This makes it easier for a Data Scientist to quickly apply the various machine learning techniques on his dataset, compare the results and create the best model for the final use." }, { "code": null, "e": 29640, "s": 29608, "text": "\n 6 Lectures \n 3 hours \n" }, { "code": null, "e": 29675, "s": 29640, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 29682, "s": 29675, "text": " Print" }, { "code": null, "e": 29693, "s": 29682, "text": " Add Notes" } ]
Downloading with chrome headless and selenium.
We can download Chrome in headless mode in Selenium. The headless execution is one of the ways saving resources by not utilizing the complete graphical interface. After the version 59, Chrome can be used in headless mode. The ChromeOptions class is used to modify the default character of the browser. The parameter headless is passed as a parameter to the addArgument method for headless execution. ChromeOptions o = new ChromeOptions(); o.addArguments("headless"); WebDriver driver = new ChromeDriver(o); Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.concurrent.TimeUnit; public class HeadlessChrome{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); //ChromeOptions object creation ChromeOptions o = new ChromeOptions(); //headless argument added o.addArguments("headless"); // add options parameter to Chrome driver WebDriver driver = new ChromeDriver(o); // wait of 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/questions/index.php"); // get page title System.out.println("Page title: " + driver.getTitle()); } }
[ { "code": null, "e": 1225, "s": 1062, "text": "We can download Chrome in headless mode in Selenium. The headless execution is one of the ways saving resources by not utilizing the complete graphical interface." }, { "code": null, "e": 1462, "s": 1225, "text": "After the version 59, Chrome can be used in headless mode. The ChromeOptions class is used to modify the default character of the browser. The parameter headless is passed as a parameter to the addArgument method for headless execution." }, { "code": null, "e": 1569, "s": 1462, "text": "ChromeOptions o = new ChromeOptions();\no.addArguments(\"headless\");\nWebDriver driver = new ChromeDriver(o);" }, { "code": null, "e": 1590, "s": 1569, "text": "Code Implementation." }, { "code": null, "e": 2519, "s": 1590, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport java.util.concurrent.TimeUnit;\npublic class HeadlessChrome{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n //ChromeOptions object creation\n ChromeOptions o = new ChromeOptions();\n //headless argument added\n o.addArguments(\"headless\");\n // add options parameter to Chrome driver\n WebDriver driver = new ChromeDriver(o);\n // wait of 5 seconds\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/questions/index.php\");\n // get page title\n System.out.println(\"Page title: \" + driver.getTitle());\n }\n}" } ]
GATE | GATE CS 2008 | Question 39 - GeeksforGeeks
28 Jun, 2021 Consider the following functions: f(n) = 2n g(n) = n! h(n) = nlogn Which of the following statements about the asymptotic behaviour of f(n), g(n), and h(n) is true? (A) f(n) = O(g(n)); g(n) = O(h(n)) (B) f(n) = (g(n)); g(n) = O(h(n)) (C) g(n) = O(f(n)); h(n) = O(f(n)) (D) h(n) = O(f(n)); g(n) = (f(n)) (A) A(B) B(C) C(D) DAnswer: (D)Explanation: According to order of growth: h(n) < f(n) < g(n) (g(n) is asymptotically greater than f(n) and f(n) is asymptotically greater than h(n) )We can easily see above order by taking logs of the given 3 functions lognlogn < n < log(n!) (logs of the given f(n), g(n) and h(n)). Note that log(n!) = (nlogn)Quiz of this Question GATE-CS-2008 GATE-GATE CS 2008 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2012 | Question 65
[ { "code": null, "e": 24075, "s": 24047, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24109, "s": 24075, "text": "Consider the following functions:" }, { "code": null, "e": 24142, "s": 24109, "text": "f(n) = 2n\ng(n) = n!\nh(n) = nlogn" }, { "code": null, "e": 24240, "s": 24142, "text": "Which of the following statements about the asymptotic behaviour of f(n), g(n), and h(n) is true?" }, { "code": null, "e": 24379, "s": 24240, "text": "(A) f(n) = O(g(n)); g(n) = O(h(n))\n(B) f(n) = (g(n)); g(n) = O(h(n))\n(C) g(n) = O(f(n)); h(n) = O(f(n))\n(D) h(n) = O(f(n)); g(n) = (f(n)) " }, { "code": null, "e": 24630, "s": 24379, "text": "(A) A(B) B(C) C(D) DAnswer: (D)Explanation: According to order of growth: h(n) < f(n) < g(n) (g(n) is asymptotically greater than f(n) and f(n) is asymptotically greater than h(n) )We can easily see above order by taking logs of the given 3 functions" }, { "code": null, "e": 24698, "s": 24630, "text": " lognlogn < n < log(n!) (logs of the given f(n), g(n) and h(n))." }, { "code": null, "e": 24747, "s": 24698, "text": "Note that log(n!) = (nlogn)Quiz of this Question" }, { "code": null, "e": 24760, "s": 24747, "text": "GATE-CS-2008" }, { "code": null, "e": 24778, "s": 24760, "text": "GATE-GATE CS 2008" }, { "code": null, "e": 24783, "s": 24778, "text": "GATE" }, { "code": null, "e": 24881, "s": 24783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24890, "s": 24881, "text": "Comments" }, { "code": null, "e": 24903, "s": 24890, "text": "Old Comments" }, { "code": null, "e": 24945, "s": 24903, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 24987, "s": 24945, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25021, "s": 24987, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25063, "s": 25021, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25117, "s": 25063, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25150, "s": 25117, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25192, "s": 25150, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 25234, "s": 25192, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25268, "s": 25234, "text": "GATE | GATE CS 2011 | Question 65" } ]
Bootstrap 4 - Sizing
You can make the size of an element wide or tall by using width and height utilities. The width and height can be set for an element, by using 25%, 50%, 75%, 100%, and auto values. For instance, use w-25 (for remaining values, replace 25 with those values) for width utility and h-25 (for remaining values, replace 25 with those values) for height utility. The following example demonstrates setting width and height utilities for an element − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Width</h2> <div class = "w-auto p-3" style = "background-color: #aaa;"> Width : auto </div> <br> <div class = "w-100 p-3" style = "background-color: #aaa;"> Width : 100% </div> <br> <div class = "w-75 p-3" style = "background-color: #aaa;"> Width : 75% </div> <br> <div class = "w-50 p-3" style = "background-color: #aaa;"> Width : 50% </div> <br> <div class = "w-25 p-3" style = "background-color: #aaa;"> Width : 25% </div> <br> <h2>Height</h2> <div class = "bg-secondary" style = "height: 100px; "> <div class = "h-100 d-inline-block bg-info" style = "width: 120px;"> Height : 100% </div> <div class = "h-75 d-inline-block bg-info" style = "width: 120px;"> Height : 75% </div> <div class = "h-50 d-inline-block bg-info" style = "width: 120px; "> Height : 50% </div> <div class = "h-25 d-inline-block bg-info" style = "width: 120px;"> Height : 25% </div> <div class = "h-auto d-inline-block bg-info" style = "width: 120px;"> Height : auto </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src =" https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity =" sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − You can also set max width and height to an element by using mw-100 and mh-100 utilities as shown in the below example − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Max Width</h2> <img class = "mw-100" src = "https://www.q1ins.com/wp-content/uploads/2016/09/black-transparent-box.png" alt = "Max-width 100%"> <br> <br> <h2>Max Height</h2> <div class = "bg-secondary" style = "height: 100px;"> <div class = "mh-100 bg-info" style = "width: 100px; height: 200px;"> Max-height : 100% </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 1902, "s": 1816, "text": "You can make the size of an element wide or tall by using width and height utilities." }, { "code": null, "e": 2174, "s": 1902, "text": "The width and height can be set for an element, by using 25%, 50%, 75%, 100%, and auto values. For instance, use w-25 (for remaining values, replace 25 with those values) for width utility and h-25 (for remaining values, replace 25 with those values) for height utility." }, { "code": null, "e": 2261, "s": 2174, "text": "The following example demonstrates setting width and height utilities for an element −" }, { "code": null, "e": 5050, "s": 2261, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n <body>\n <div class = \"container\">\n <h2>Width</h2>\n <div class = \"w-auto p-3\" style = \"background-color: #aaa;\">\n Width : auto\n </div>\n <br>\n \n <div class = \"w-100 p-3\" style = \"background-color: #aaa;\">\n Width : 100%\n </div>\n <br>\n \n <div class = \"w-75 p-3\" style = \"background-color: #aaa;\">\n Width : 75%\n </div>\n <br>\n \n <div class = \"w-50 p-3\" style = \"background-color: #aaa;\">\n Width : 50%\n </div>\n <br>\n \n <div class = \"w-25 p-3\" style = \"background-color: #aaa;\">\n Width : 25%\n </div>\n <br>\n \n <h2>Height</h2>\n <div class = \"bg-secondary\" style = \"height: 100px; \">\n <div class = \"h-100 d-inline-block bg-info\" style = \"width: 120px;\">\n Height : 100%\n </div>\n <div class = \"h-75 d-inline-block bg-info\" style = \"width: 120px;\">\n Height : 75%\n </div>\n <div class = \"h-50 d-inline-block bg-info\" style = \"width: 120px; \">\n Height : 50%\n </div>\n <div class = \"h-25 d-inline-block bg-info\" style = \"width: 120px;\">\n Height : 25%\n </div>\n <div class = \"h-auto d-inline-block bg-info\" style = \"width: 120px;\">\n Height : auto\n </div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src =\" https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity =\" sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 5089, "s": 5050, "text": "It will produce the following result −" }, { "code": null, "e": 5210, "s": 5089, "text": "You can also set max width and height to an element by using mw-100 and mh-100 utilities as shown in the below example −" }, { "code": null, "e": 7035, "s": 5210, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n <body>\n <div class = \"container\">\n <h2>Max Width</h2>\n <img class = \"mw-100\" \n src = \"https://www.q1ins.com/wp-content/uploads/2016/09/black-transparent-box.png\" \n alt = \"Max-width 100%\">\n <br>\n <br>\n \n <h2>Max Height</h2>\n <div class = \"bg-secondary\" style = \"height: 100px;\">\n <div class = \"mh-100 bg-info\" style = \"width: 100px; height: 200px;\">\n Max-height : 100%\n </div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 7074, "s": 7035, "text": "It will produce the following result −" }, { "code": null, "e": 7107, "s": 7074, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 7121, "s": 7107, "text": " Anadi Sharma" }, { "code": null, "e": 7156, "s": 7121, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7173, "s": 7156, "text": " Frahaan Hussain" }, { "code": null, "e": 7210, "s": 7173, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 7238, "s": 7210, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7271, "s": 7238, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 7283, "s": 7271, "text": " Azaz Patel" }, { "code": null, "e": 7318, "s": 7283, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7335, "s": 7318, "text": " Muhammad Ismail" }, { "code": null, "e": 7368, "s": 7335, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 7388, "s": 7368, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 7395, "s": 7388, "text": " Print" }, { "code": null, "e": 7406, "s": 7395, "text": " Add Notes" } ]
Python Pandas - Aggregations
Once the rolling, expanding and ewm objects are created, several methods are available to perform aggregations on data. Let us create a DataFrame and apply aggregations on it. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r Its output is as follows − A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 0.790670 -0.387854 -0.668132 0.267283 2000-01-03 -0.575523 -0.965025 0.060427 -2.179780 2000-01-04 1.669653 1.211759 -0.254695 1.429166 2000-01-05 0.100568 -0.236184 0.491646 -0.466081 2000-01-06 0.155172 0.992975 -1.205134 0.320958 2000-01-07 0.309468 -0.724053 -1.412446 0.627919 2000-01-08 0.099489 -1.028040 0.163206 -1.274331 2000-01-09 1.639500 -0.068443 0.714008 -0.565969 2000-01-10 0.326761 1.479841 0.664282 -1.361169 Rolling [window=3,min_periods=1,center=False,axis=0] We can aggregate by passing a function to the entire DataFrame, or select a column via the standard get item method. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r.aggregate(np.sum) Its output is as follows − A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 1.879182 -1.038796 -3.215581 -0.299575 2000-01-03 1.303660 -2.003821 -3.155154 -2.479355 2000-01-04 1.884801 -0.141119 -0.862400 -0.483331 2000-01-05 1.194699 0.010551 0.297378 -1.216695 2000-01-06 1.925393 1.968551 -0.968183 1.284044 2000-01-07 0.565208 0.032738 -2.125934 0.482797 2000-01-08 0.564129 -0.759118 -2.454374 -0.325454 2000-01-09 2.048458 -1.820537 -0.535232 -1.212381 2000-01-10 2.065750 0.383357 1.541496 -3.201469 A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 1.879182 -1.038796 -3.215581 -0.299575 2000-01-03 1.303660 -2.003821 -3.155154 -2.479355 2000-01-04 1.884801 -0.141119 -0.862400 -0.483331 2000-01-05 1.194699 0.010551 0.297378 -1.216695 2000-01-06 1.925393 1.968551 -0.968183 1.284044 2000-01-07 0.565208 0.032738 -2.125934 0.482797 2000-01-08 0.564129 -0.759118 -2.454374 -0.325454 2000-01-09 2.048458 -1.820537 -0.535232 -1.212381 2000-01-10 2.065750 0.383357 1.541496 -3.201469 import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r['A'].aggregate(np.sum) Its output is as follows − A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 1.879182 -1.038796 -3.215581 -0.299575 2000-01-03 1.303660 -2.003821 -3.155154 -2.479355 2000-01-04 1.884801 -0.141119 -0.862400 -0.483331 2000-01-05 1.194699 0.010551 0.297378 -1.216695 2000-01-06 1.925393 1.968551 -0.968183 1.284044 2000-01-07 0.565208 0.032738 -2.125934 0.482797 2000-01-08 0.564129 -0.759118 -2.454374 -0.325454 2000-01-09 2.048458 -1.820537 -0.535232 -1.212381 2000-01-10 2.065750 0.383357 1.541496 -3.201469 2000-01-01 1.088512 2000-01-02 1.879182 2000-01-03 1.303660 2000-01-04 1.884801 2000-01-05 1.194699 2000-01-06 1.925393 2000-01-07 0.565208 2000-01-08 0.564129 2000-01-09 2.048458 2000-01-10 2.065750 Freq: D, Name: A, dtype: float64 import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r[['A','B']].aggregate(np.sum) Its output is as follows − A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 1.879182 -1.038796 -3.215581 -0.299575 2000-01-03 1.303660 -2.003821 -3.155154 -2.479355 2000-01-04 1.884801 -0.141119 -0.862400 -0.483331 2000-01-05 1.194699 0.010551 0.297378 -1.216695 2000-01-06 1.925393 1.968551 -0.968183 1.284044 2000-01-07 0.565208 0.032738 -2.125934 0.482797 2000-01-08 0.564129 -0.759118 -2.454374 -0.325454 2000-01-09 2.048458 -1.820537 -0.535232 -1.212381 2000-01-10 2.065750 0.383357 1.541496 -3.201469 A B 2000-01-01 1.088512 -0.650942 2000-01-02 1.879182 -1.038796 2000-01-03 1.303660 -2.003821 2000-01-04 1.884801 -0.141119 2000-01-05 1.194699 0.010551 2000-01-06 1.925393 1.968551 2000-01-07 0.565208 0.032738 2000-01-08 0.564129 -0.759118 2000-01-09 2.048458 -1.820537 2000-01-10 2.065750 0.383357 import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r['A'].aggregate([np.sum,np.mean]) Its output is as follows − A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 1.879182 -1.038796 -3.215581 -0.299575 2000-01-03 1.303660 -2.003821 -3.155154 -2.479355 2000-01-04 1.884801 -0.141119 -0.862400 -0.483331 2000-01-05 1.194699 0.010551 0.297378 -1.216695 2000-01-06 1.925393 1.968551 -0.968183 1.284044 2000-01-07 0.565208 0.032738 -2.125934 0.482797 2000-01-08 0.564129 -0.759118 -2.454374 -0.325454 2000-01-09 2.048458 -1.820537 -0.535232 -1.212381 2000-01-10 2.065750 0.383357 1.541496 -3.201469 sum mean 2000-01-01 1.088512 1.088512 2000-01-02 1.879182 0.939591 2000-01-03 1.303660 0.434553 2000-01-04 1.884801 0.628267 2000-01-05 1.194699 0.398233 2000-01-06 1.925393 0.641798 2000-01-07 0.565208 0.188403 2000-01-08 0.564129 0.188043 2000-01-09 2.048458 0.682819 2000-01-10 2.065750 0.688583 import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r[['A','B']].aggregate([np.sum,np.mean]) Its output is as follows − A B C D 2000-01-01 1.088512 -0.650942 -2.547450 -0.566858 2000-01-02 1.879182 -1.038796 -3.215581 -0.299575 2000-01-03 1.303660 -2.003821 -3.155154 -2.479355 2000-01-04 1.884801 -0.141119 -0.862400 -0.483331 2000-01-05 1.194699 0.010551 0.297378 -1.216695 2000-01-06 1.925393 1.968551 -0.968183 1.284044 2000-01-07 0.565208 0.032738 -2.125934 0.482797 2000-01-08 0.564129 -0.759118 -2.454374 -0.325454 2000-01-09 2.048458 -1.820537 -0.535232 -1.212381 2000-01-10 2.065750 0.383357 1.541496 -3.201469 A B sum mean sum mean 2000-01-01 1.088512 1.088512 -0.650942 -0.650942 2000-01-02 1.879182 0.939591 -1.038796 -0.519398 2000-01-03 1.303660 0.434553 -2.003821 -0.667940 2000-01-04 1.884801 0.628267 -0.141119 -0.047040 2000-01-05 1.194699 0.398233 0.010551 0.003517 2000-01-06 1.925393 0.641798 1.968551 0.656184 2000-01-07 0.565208 0.188403 0.032738 0.010913 2000-01-08 0.564129 0.188043 -0.759118 -0.253039 2000-01-09 2.048458 0.682819 -1.820537 -0.606846 2000-01-10 2.065750 0.688583 0.383357 0.127786 import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(3, 4), index = pd.date_range('1/1/2000', periods=3), columns = ['A', 'B', 'C', 'D']) print df r = df.rolling(window=3,min_periods=1) print r.aggregate({'A' : np.sum,'B' : np.mean}) Its output is as follows − A B C D 2000-01-01 -1.575749 -1.018105 0.317797 0.545081 2000-01-02 -0.164917 -1.361068 0.258240 1.113091 2000-01-03 1.258111 1.037941 -0.047487 0.867371 A B 2000-01-01 -1.575749 -1.018105 2000-01-02 -1.740666 -1.189587 2000-01-03 -0.482555 -0.447078 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2563, "s": 2443, "text": "Once the rolling, expanding and ewm objects are created, several methods are available to perform aggregations on data." }, { "code": null, "e": 2619, "s": 2563, "text": "Let us create a DataFrame and apply aggregations on it." }, { "code": null, "e": 2843, "s": 2619, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10, 4),\n index = pd.date_range('1/1/2000', periods=10),\n columns = ['A', 'B', 'C', 'D'])\n\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r" }, { "code": null, "e": 2870, "s": 2843, "text": "Its output is as follows −" }, { "code": null, "e": 3579, "s": 2870, "text": " A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 0.790670 -0.387854 -0.668132 0.267283\n2000-01-03 -0.575523 -0.965025 0.060427 -2.179780\n2000-01-04 1.669653 1.211759 -0.254695 1.429166\n2000-01-05 0.100568 -0.236184 0.491646 -0.466081\n2000-01-06 0.155172 0.992975 -1.205134 0.320958\n2000-01-07 0.309468 -0.724053 -1.412446 0.627919\n2000-01-08 0.099489 -1.028040 0.163206 -1.274331\n2000-01-09 1.639500 -0.068443 0.714008 -0.565969\n2000-01-10 0.326761 1.479841 0.664282 -1.361169\n\nRolling [window=3,min_periods=1,center=False,axis=0] \n" }, { "code": null, "e": 3696, "s": 3579, "text": "We can aggregate by passing a function to the entire DataFrame, or select a column via the standard get item method." }, { "code": null, "e": 3937, "s": 3696, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10, 4),\n index = pd.date_range('1/1/2000', periods=10),\n columns = ['A', 'B', 'C', 'D'])\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r.aggregate(np.sum)" }, { "code": null, "e": 3964, "s": 3937, "text": "Its output is as follows −" }, { "code": null, "e": 5242, "s": 3964, "text": " A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 1.879182 -1.038796 -3.215581 -0.299575\n2000-01-03 1.303660 -2.003821 -3.155154 -2.479355\n2000-01-04 1.884801 -0.141119 -0.862400 -0.483331\n2000-01-05 1.194699 0.010551 0.297378 -1.216695\n2000-01-06 1.925393 1.968551 -0.968183 1.284044\n2000-01-07 0.565208 0.032738 -2.125934 0.482797\n2000-01-08 0.564129 -0.759118 -2.454374 -0.325454\n2000-01-09 2.048458 -1.820537 -0.535232 -1.212381\n2000-01-10 2.065750 0.383357 1.541496 -3.201469\n\n A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 1.879182 -1.038796 -3.215581 -0.299575\n2000-01-03 1.303660 -2.003821 -3.155154 -2.479355\n2000-01-04 1.884801 -0.141119 -0.862400 -0.483331\n2000-01-05 1.194699 0.010551 0.297378 -1.216695\n2000-01-06 1.925393 1.968551 -0.968183 1.284044\n2000-01-07 0.565208 0.032738 -2.125934 0.482797\n2000-01-08 0.564129 -0.759118 -2.454374 -0.325454\n2000-01-09 2.048458 -1.820537 -0.535232 -1.212381\n2000-01-10 2.065750 0.383357 1.541496 -3.201469\n" }, { "code": null, "e": 5488, "s": 5242, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10, 4),\n index = pd.date_range('1/1/2000', periods=10),\n columns = ['A', 'B', 'C', 'D'])\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r['A'].aggregate(np.sum)" }, { "code": null, "e": 5515, "s": 5488, "text": "Its output is as follows −" }, { "code": null, "e": 6404, "s": 5515, "text": " A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 1.879182 -1.038796 -3.215581 -0.299575\n2000-01-03 1.303660 -2.003821 -3.155154 -2.479355\n2000-01-04 1.884801 -0.141119 -0.862400 -0.483331\n2000-01-05 1.194699 0.010551 0.297378 -1.216695\n2000-01-06 1.925393 1.968551 -0.968183 1.284044\n2000-01-07 0.565208 0.032738 -2.125934 0.482797\n2000-01-08 0.564129 -0.759118 -2.454374 -0.325454\n2000-01-09 2.048458 -1.820537 -0.535232 -1.212381\n2000-01-10 2.065750 0.383357 1.541496 -3.201469\n2000-01-01 1.088512\n2000-01-02 1.879182\n2000-01-03 1.303660\n2000-01-04 1.884801\n2000-01-05 1.194699\n2000-01-06 1.925393\n2000-01-07 0.565208\n2000-01-08 0.564129\n2000-01-09 2.048458\n2000-01-10 2.065750\nFreq: D, Name: A, dtype: float64\n" }, { "code": null, "e": 6656, "s": 6404, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10, 4),\n index = pd.date_range('1/1/2000', periods=10),\n columns = ['A', 'B', 'C', 'D'])\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r[['A','B']].aggregate(np.sum)" }, { "code": null, "e": 6683, "s": 6656, "text": "Its output is as follows −" }, { "code": null, "e": 7693, "s": 6683, "text": " A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 1.879182 -1.038796 -3.215581 -0.299575\n2000-01-03 1.303660 -2.003821 -3.155154 -2.479355\n2000-01-04 1.884801 -0.141119 -0.862400 -0.483331\n2000-01-05 1.194699 0.010551 0.297378 -1.216695\n2000-01-06 1.925393 1.968551 -0.968183 1.284044\n2000-01-07 0.565208 0.032738 -2.125934 0.482797\n2000-01-08 0.564129 -0.759118 -2.454374 -0.325454\n2000-01-09 2.048458 -1.820537 -0.535232 -1.212381\n2000-01-10 2.065750 0.383357 1.541496 -3.201469\n A B\n2000-01-01 1.088512 -0.650942\n2000-01-02 1.879182 -1.038796\n2000-01-03 1.303660 -2.003821\n2000-01-04 1.884801 -0.141119\n2000-01-05 1.194699 0.010551\n2000-01-06 1.925393 1.968551\n2000-01-07 0.565208 0.032738\n2000-01-08 0.564129 -0.759118\n2000-01-09 2.048458 -1.820537\n2000-01-10 2.065750 0.383357\n" }, { "code": null, "e": 7949, "s": 7693, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10, 4),\n index = pd.date_range('1/1/2000', periods=10),\n columns = ['A', 'B', 'C', 'D'])\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r['A'].aggregate([np.sum,np.mean])" }, { "code": null, "e": 7976, "s": 7949, "text": "Its output is as follows −" }, { "code": null, "e": 8975, "s": 7976, "text": " A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 1.879182 -1.038796 -3.215581 -0.299575\n2000-01-03 1.303660 -2.003821 -3.155154 -2.479355\n2000-01-04 1.884801 -0.141119 -0.862400 -0.483331\n2000-01-05 1.194699 0.010551 0.297378 -1.216695\n2000-01-06 1.925393 1.968551 -0.968183 1.284044\n2000-01-07 0.565208 0.032738 -2.125934 0.482797\n2000-01-08 0.564129 -0.759118 -2.454374 -0.325454\n2000-01-09 2.048458 -1.820537 -0.535232 -1.212381\n2000-01-10 2.065750 0.383357 1.541496 -3.201469\n sum mean\n2000-01-01 1.088512 1.088512\n2000-01-02 1.879182 0.939591\n2000-01-03 1.303660 0.434553\n2000-01-04 1.884801 0.628267\n2000-01-05 1.194699 0.398233\n2000-01-06 1.925393 0.641798\n2000-01-07 0.565208 0.188403\n2000-01-08 0.564129 0.188043\n2000-01-09 2.048458 0.682819\n2000-01-10 2.065750 0.688583\n" }, { "code": null, "e": 9237, "s": 8975, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10, 4),\n index = pd.date_range('1/1/2000', periods=10),\n columns = ['A', 'B', 'C', 'D'])\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r[['A','B']].aggregate([np.sum,np.mean])" }, { "code": null, "e": 9264, "s": 9237, "text": "Its output is as follows −" }, { "code": null, "e": 10572, "s": 9264, "text": " A B C D\n2000-01-01 1.088512 -0.650942 -2.547450 -0.566858\n2000-01-02 1.879182 -1.038796 -3.215581 -0.299575\n2000-01-03 1.303660 -2.003821 -3.155154 -2.479355\n2000-01-04 1.884801 -0.141119 -0.862400 -0.483331\n2000-01-05 1.194699 0.010551 0.297378 -1.216695\n2000-01-06 1.925393 1.968551 -0.968183 1.284044\n2000-01-07 0.565208 0.032738 -2.125934 0.482797\n2000-01-08 0.564129 -0.759118 -2.454374 -0.325454\n2000-01-09 2.048458 -1.820537 -0.535232 -1.212381\n2000-01-10 2.065750 0.383357 1.541496 -3.201469\n A B\n sum mean sum mean\n2000-01-01 1.088512 1.088512 -0.650942 -0.650942\n2000-01-02 1.879182 0.939591 -1.038796 -0.519398\n2000-01-03 1.303660 0.434553 -2.003821 -0.667940\n2000-01-04 1.884801 0.628267 -0.141119 -0.047040\n2000-01-05 1.194699 0.398233 0.010551 0.003517\n2000-01-06 1.925393 0.641798 1.968551 0.656184\n2000-01-07 0.565208 0.188403 0.032738 0.010913\n2000-01-08 0.564129 0.188043 -0.759118 -0.253039\n2000-01-09 2.048458 0.682819 -1.820537 -0.606846\n2000-01-10 2.065750 0.688583 0.383357 0.127786\n" }, { "code": null, "e": 10834, "s": 10572, "text": "import pandas as pd\nimport numpy as np\n \ndf = pd.DataFrame(np.random.randn(3, 4),\n index = pd.date_range('1/1/2000', periods=3),\n columns = ['A', 'B', 'C', 'D'])\nprint df\nr = df.rolling(window=3,min_periods=1)\nprint r.aggregate({'A' : np.sum,'B' : np.mean})" }, { "code": null, "e": 10861, "s": 10834, "text": "Its output is as follows −" }, { "code": null, "e": 11210, "s": 10861, "text": " A B C D\n2000-01-01 -1.575749 -1.018105 0.317797 0.545081\n2000-01-02 -0.164917 -1.361068 0.258240 1.113091\n2000-01-03 1.258111 1.037941 -0.047487 0.867371\n A B\n2000-01-01 -1.575749 -1.018105\n2000-01-02 -1.740666 -1.189587\n2000-01-03 -0.482555 -0.447078\n" }, { "code": null, "e": 11247, "s": 11210, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 11263, "s": 11247, "text": " Malhar Lathkar" }, { "code": null, "e": 11296, "s": 11263, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 11315, "s": 11296, "text": " Arnab Chakraborty" }, { "code": null, "e": 11350, "s": 11315, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 11372, "s": 11350, "text": " In28Minutes Official" }, { "code": null, "e": 11406, "s": 11372, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 11434, "s": 11406, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11469, "s": 11434, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 11483, "s": 11469, "text": " Lets Kode It" }, { "code": null, "e": 11516, "s": 11483, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 11533, "s": 11516, "text": " Abhilash Nelson" }, { "code": null, "e": 11540, "s": 11533, "text": " Print" }, { "code": null, "e": 11551, "s": 11540, "text": " Add Notes" } ]
Graph Algorithms (Part 2). Main concepts, properties, and... | by Maël Fabien | Towards Data Science
Graphs are becoming central to machine learning these days, whether you’d like to understand the structure of a social network by predicting potential connections, detecting fraud, understand customer’s behavior of a car rental service or making real-time recommendations for example. In this article, we’ll cover : The main graph algorithms Illustrations and use-cases Examples in Python This article was originally published on my personal blog: https://maelfabien.github.io/ml/# I publish all my articles and the corresponding code on this repository : github.com If you haven't, make sure to check my first article of this series: towardsdatascience.com NEW: Part 3 is out! towardsdatascience.com For what comes next, open a Jupyter Notebook and import the following packages : import numpy as npimport randomimport networkx as nxfrom IPython.display import Imageimport matplotlib.pyplot as plt The following articles will be using the latest version 2.x ofnetworkx. NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. I’ll try to keep a practical approach and illustrate each concept. In the previous article, we covered the main kind of graphs, and the basic characteristics to describe a graph. We’ll now cover into more details graph analysis/algorithms and the different ways a graph can be analyzed. In order to understand the context, here are some use cases for graph algorithms : real-time fraud detection real-time recommendations streamline regulatory compliance management and monitoring of complex networks identity and access management social applications/features ... There are 3 main categories of graph algorithms that are currently supported in most frameworks (networkx in Python, or in Neo4J for example) : Pathfinding: identify the optimal path depending on availability and quality for example. We’ll also include search algorithms in this category. This can be used to identify the quickest route or traffic routing for example. Centrality: determine the importance of the nodes in the network. This can be used to identify influencers in social media for example or identify potential attack targets in a network. Community detection: evaluate how a group is clustered. This can be used to segment customers and detect fraud for example. We will also develop the basis of Machine Learning in Graphs and Graph Learning in a third article, coming out next week. All algorithms implemented in Networkx can be found here : networkx.github.io As you‘ll notice, we’ll only cover the basic and most common algorithms implemented in Networkx. Pathfinding algorithms try to find the shortest path between two nodes by minimizing the number of hops. Search Algorithms does not give the shortest path. Instead, they explore graphs considering neighbors or depths of a graph. This can be used for information retrieval. There are two main graph search algorithms : Breadth-First Search (BFS) which explores each node’s neighbor first, then neighbors of the neighbors... Depth-First Search (DFS) which tries to go down a path as much as possible, and visit new neighbors if possible. a. Shortest Path Shortest Path calculates the shortest weighted (if the graph is weighted) path between a pair of nodes. It is used to identify optimal driving directions or degree of separation between two people on a social network for example. The are many ways to compute the shortest path in a graph, including the Dijkstra’s algorithm, the default algorithm in Networkx. The pseudo-code for this algorithm according to Wikipedia is the following : Mark all nodes of the graph as unvisited. Create a set of all the unvisited nodes called the unvisited set.Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Set the initial starting node as current.For the current node, consider all of its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value.When we are done considering all of the unvisited neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again.If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished.Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new “current node”, and go back to step 3. Mark all nodes of the graph as unvisited. Create a set of all the unvisited nodes called the unvisited set. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Set the initial starting node as current. For the current node, consider all of its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value. When we are done considering all of the unvisited neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished. Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new “current node”, and go back to step 3. If you’d like to read more on the shortest path problem, check this article: https://en.wikipedia.org/wiki/Shortest_path_problem In Python, the implementation is straightforward : # Returns shortest path between each nodenx.shortest_path(G_karate) This returns a list of the minimal path between each node of the graph : {0: {0: [0], 1: [0, 1], 2: [0, 2], ... b. Single Source Shortest Path The Single Source Shortest Path (SSSP) finds the shortest path between a given node and all other nodes in the graph. It is often used for routing protocol for IP networks for example. c. All Pairs Shortest Path The “All Pairs Shortest Path” (APSP) algorithm finds the shortest path between all pairs of nodes. Although providing similar results, it is quicker than calling the Single Source Shortest Path for every pair of nodes. This algorithm can typically be used to determine traffic load expected on different segments of a transportation grid. # Returns shortest path length between each nodelist(nx.all_pairs_shortest_path_length(G_karate)) Which returns : [(0, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, ... d. Minimum Weight Spanning Tree A minimum spanning tree is a subgraph of the graph (a tree) with the minimum sum of edge weights that connects all nodes within a graph. Minimum spanning tree should be applied to undirected graphs. from networkx.algorithms import treemst = tree.minimum_spanning_edges(G_karate, algorithm='prim', data=False)edgelist = list(mst)sorted(edgelist) Which returns : [(0, 1),(0, 2),(0, 3),(0, 4),(0, 5),(0, 6),... Community detection partitions the nodes into a several groups according to a given quality criterion. It is typically used to identify social communities, customers behaviors or web pages topics. A community is a set of connected nodes. There is however no universal definition that one can give to define communities, although the nodes within a community should be densely connected. A common algorithm to find communities is the Girvan Newman algorithm. It identifies communities by progressively removing edges within the network. We’ll refer to betweenness as the “edge betweenness”. It is a score proportional to the number of shortest paths between pairs of nodes that go through this edge. The steps of this algorithm are the following : Compute the betweenness of all existing edges in the network.Remove the edge with the highest betweenness.Recompute the betweenness of all edges after the removal of this edge.Steps 2 and 3 are repeated until no edges remain. Compute the betweenness of all existing edges in the network. Remove the edge with the highest betweenness. Recompute the betweenness of all edges after the removal of this edge. Steps 2 and 3 are repeated until no edges remain. To implement this in Python, you can use the following code : from networkx.algorithms import communityk = 1comp = community.girvan_newman(G_karate)for communities in itertools.islice(comp, k): print(tuple(sorted(c) for c in communities)) This heads a list of the nodes that belong to each community (k=1 means we expect 2 communities): ([0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21], [2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]) As stated above, this method does not really scale. For this reason, methods such as the Louvain method have been developed. Such methods are however really long to run on large graphs. Before defining the Louvain method, it is important to introduce the notion of modularity. Modularity is a measure of how well groups have been partitioned into clusters : The pseudo-code of the Louvain method is the following : Assign a community to each node at first Alternate the next 2 steps until convergence : Create a new community with neighboring nodes to maximize modularity Create a new weighted graph. Communities of the previous step become nodes of the graph This might seem a bit confusing right now. In fact, the only thing we’re doing is to group the closest nodes so that we optimize the modularity criteria. Note that there is no theoretical guarantee of the Louvain method, but it works well in practice. Louvain’s method is present as a sub-project of NetworkX, right here: https://python-louvain.readthedocs.io/en/latest/ First, install the package : pip install python-louvain Then, compute the best partition (based on the Louvain method): import communitypartition = community.best_partition(G_karate)pos = nx.spring_layout(G_karate)plt.figure(figsize=(8, 8))plt.axis('off')nx.draw_networkx_nodes(G_karate, pos, node_size=600, cmap=plt.cm.RdYlBu, node_color=list(partition.values()))nx.draw_networkx_edges(G_karate, pos, alpha=0.3)plt.show(G_karate) The Strongly Connected Components (SCC) algorithm finds groups of connected nodes in a directed graph. Note that each node must be reachable in both directions from any other node in the same group. It is often used early in a graph analysis process to give us an idea of how our graph is structured, for example, to explore financial statements data when we look at who owns shared in what company (think about Panama papers for example). The Weakly Connected Components, or Union Find algorithm finds sets of connected nodes in a directed graph where each node is reachable from any other node in the same set. It only needs a path to exist between pairs of nodes in one direction, whereas SCC needs a path to exist in both directions. As with SCC, Union Find is often used early in analysis to understand a graph’s structure. Union-Find is a pre-processing step that is essential before any kind of algorithm, to understand the graph’s structure. We can test for connected directed graphs using : nx.is_weakly_connected(G)nx.is_strongly_connected(G) Or for undirected graphs using : nx.is_connected(G_karate) Which returns a boolean. Make sure to check the Networkx documentation on the Connectivity for implementations. In hierarchical clustering, we build a hierarchy of clusters. We represent the clusters under a form a dendrogram. The idea is to analyze community structures at different scales. We usually build the dendrogram bottom-up. We start with a cluster at each node and merge the two “closest” nodes. But how do we measure if clusters are close? We use similarity distances. Let d(i,j) be the length of the shortest path between i and j. For the maximum linkage, at each step, the two clusters separated by the shortest distance are combined. The similarity distances can be illustrated as follows : Back to our Karate example. Before applying hierarchical clustering, we need to define the matrix of distances between each node. pcc_longueurs=list(nx.all_pairs_shortest_path_length(G_karate))distances=np.zeros((n,n))# distances[i, j] is the length of the shortest path between i and jfor i in range(n): for j in range(n): distances[i, j] = pcc_longueurs[i][1][j] Now, we’ll use the AgglomerativeClustering function of sklearnto identify hierarchical clustering. from sklearn.cluster import AgglomerativeClusteringclustering = AgglomerativeClustering(n_clusters=2,linkage='average',affinity='precomputed').fit_predict(distances) And finally, draw the resulting graph with colors depending on the cluster : nx.draw(G_karate, node_color = clustering) The clustering coefficient measures how well two nodes tend to cluster together. The local clustering coefficient is a ratio of the number of triangles centered at node i over the number of triples centered at node i. In some sense, it measures how close a node i and its neighbors are to being a complete graph. I have tried to illustrate this computation of clustering coefficients for the following graph : A global coefficient measures the density of triangles (local clusters) in the graph : In the graph shown above, the clustering coefficient is equal to : For Erdos-Rényi random graphs, E[Clustering Coefficient]=E[Ci]=p where p the probability defined in the previous article. For Baràbasi-Albert random graphs, the global clustering coefficient follows a power law depending on the number of nodes. The average clustering coefficient of nodes with degree k is proportional to the inverse of k: Nodes with a low degree are connected to other nodes in their community. Nodes with high degrees are linked to nodes in different communities. For a given graph, in networkx, the clustering coefficient can be easily computed. First, let’s begin with the local clustering coefficients : # List of local clustering coefficientslist(nx.clustering(G_barabasi).values()) This should return something quite similar to : 0.13636363636363635,0.2,0.07602339181286549,0.04843304843304843,0.09,0.055384615384615386,0.07017543859649122,... And average the results to find the global clustering coefficient of the graph : # Global clustering coefficientnp.mean(list(nx.clustering(G_barabasi).values())) Which heads : 0.0965577637155059 Centrality measures how important a node is. This is not a clear definition, but it’s useful when we want to identify important web pages, bottlenecks in transportation networks... A walk is a path which can go through the same node several times. Centrality measures vary with the type of walk considered and the way of counting them. PageRank estimates a current node’s importance from its linked neighbors and then again from their respective neighbors. Although popularized by Google, it’s a way of detecting influential nodes in any network. It is for example used to suggest connections on social networks. PageRank is computed by either iteratively distributing one node’s rank (originally based on the degree) over its neighbors or by randomly traversing the graph and counting the frequency of hitting each node during these walks. PageRank is usually computed on directed graphs. However, it will also execute on undirected graphs by converting each edge in the directed graph to two edges. For example, the PageRank of the Karate graph can be accessed by : nx.pagerank(G_karate, alpha=0.9) Where alpha is the damping parameter (by default 0.85). It should give you a list of rankings in return : {0: 0.09923208031303203, 1: 0.0543403155825792, 2: 0.05919704684187155, 3: 0.036612460562853694,... Degree Centrality counts the number of walks of length 1 ending at node i. It measures incoming and outgoing relationship. It is given by C(Xi)=di. Degree Centrality is used to identify the most influential persons on a social network for example. c_degree = nx.degree_centrality(G_karate)c_degree = list(c_degree.values()) Eigenvector Centrality is the number of walks of infinite length ending at node i. This gives more importance to nodes with well-connected neighbors. c_eigenvector = nx.eigenvector_centrality(G_karate)c_eigenvector = list(c_eigenvector.values()) Closeness Centrality detects nodes that are can spread information efficiently through a graph. It can be used to identify fake news accounts or in terrorist cells to isolate the individuals that can spread information to the rest of the graph. Closeness Centrality is inversely proportional to the sum of lengths of the shortest paths to other nodes. c_closeness = nx.closeness_centrality(G_karate)c_closeness = list(c_closeness.values()) Betweenness Centrality detects the amount of influence a node has over the flow of information in a graph. It is often used to find nodes that serve as a bridge from one part of a graph to another, for example in the package delivery processor in a telecommunication network, or in the propagation of fake news. Where : σjk the number of shortest paths between j and k σjk(i) the number of shortest paths between j and k going through i The betweenness centrality measures the number of times a node acts as a bridge between two nodes. For example : c_betweenness = nx.betweenness_centrality(G_karate)c_betweenness = list(c_betweenness.values()) In Python, the implementation relies on the built-in functions of networkx : # Plot the centrality of the nodesplt.figure(figsize=(18, 12))# Degree Centralityf, axarr = plt.subplots(2, 2, num=1)plt.sca(axarr[0,0])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_degree, node_size=300, pos=pos, with_labels=True)axarr[0,0].set_title('Degree Centrality', size=16)# Eigenvalue Centralityplt.sca(axarr[0,1])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_eigenvector, node_size=300, pos=pos, with_labels=True)axarr[0,1].set_title('Eigenvalue Centrality', size=16)# Proximity Centralityplt.sca(axarr[1,0])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_closeness, node_size=300, pos=pos, with_labels=True)axarr[1,0].set_title('Proximity Centrality', size=16)# Betweenness Centralityplt.sca(axarr[1,1])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_betweenness, node_size=300, pos=pos, with_labels=True)axarr[1,1].set_title('Betweenness Centrality', size=16) We observe that the different nodes highlighted by the centrality measures are quite distinct. Betweenness centrality, for example, produces results far from the other methods, since they don’t measure the same thing. We have now covered the introduction to graphs, the main types of graphs, the different graph algorithms and their implementation in Python with Networkx. In the next article, we’ll cover graph learning which provides ways to predict nodes and edges in a graph to handle missing values or predict new relations. Feel free to comment if you have any question or remark. Stay tuned, the last article of this series is coming out next week :) A Comprehensive Guide to Graph Algorithms in Neo4j, Mark Needham & Amy E. Hodler Networkx documentation, https://networkx.github.io/documentation/stable/ If you’d like to read more from me, my previous articles can be found here:
[ { "code": null, "e": 457, "s": 172, "text": "Graphs are becoming central to machine learning these days, whether you’d like to understand the structure of a social network by predicting potential connections, detecting fraud, understand customer’s behavior of a car rental service or making real-time recommendations for example." }, { "code": null, "e": 488, "s": 457, "text": "In this article, we’ll cover :" }, { "code": null, "e": 514, "s": 488, "text": "The main graph algorithms" }, { "code": null, "e": 542, "s": 514, "text": "Illustrations and use-cases" }, { "code": null, "e": 561, "s": 542, "text": "Examples in Python" }, { "code": null, "e": 654, "s": 561, "text": "This article was originally published on my personal blog: https://maelfabien.github.io/ml/#" }, { "code": null, "e": 728, "s": 654, "text": "I publish all my articles and the corresponding code on this repository :" }, { "code": null, "e": 739, "s": 728, "text": "github.com" }, { "code": null, "e": 807, "s": 739, "text": "If you haven't, make sure to check my first article of this series:" }, { "code": null, "e": 830, "s": 807, "text": "towardsdatascience.com" }, { "code": null, "e": 850, "s": 830, "text": "NEW: Part 3 is out!" }, { "code": null, "e": 873, "s": 850, "text": "towardsdatascience.com" }, { "code": null, "e": 954, "s": 873, "text": "For what comes next, open a Jupyter Notebook and import the following packages :" }, { "code": null, "e": 1071, "s": 954, "text": "import numpy as npimport randomimport networkx as nxfrom IPython.display import Imageimport matplotlib.pyplot as plt" }, { "code": null, "e": 1277, "s": 1071, "text": "The following articles will be using the latest version 2.x ofnetworkx. NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks." }, { "code": null, "e": 1344, "s": 1277, "text": "I’ll try to keep a practical approach and illustrate each concept." }, { "code": null, "e": 1564, "s": 1344, "text": "In the previous article, we covered the main kind of graphs, and the basic characteristics to describe a graph. We’ll now cover into more details graph analysis/algorithms and the different ways a graph can be analyzed." }, { "code": null, "e": 1647, "s": 1564, "text": "In order to understand the context, here are some use cases for graph algorithms :" }, { "code": null, "e": 1673, "s": 1647, "text": "real-time fraud detection" }, { "code": null, "e": 1699, "s": 1673, "text": "real-time recommendations" }, { "code": null, "e": 1732, "s": 1699, "text": "streamline regulatory compliance" }, { "code": null, "e": 1778, "s": 1732, "text": "management and monitoring of complex networks" }, { "code": null, "e": 1809, "s": 1778, "text": "identity and access management" }, { "code": null, "e": 1838, "s": 1809, "text": "social applications/features" }, { "code": null, "e": 1842, "s": 1838, "text": "..." }, { "code": null, "e": 1986, "s": 1842, "text": "There are 3 main categories of graph algorithms that are currently supported in most frameworks (networkx in Python, or in Neo4J for example) :" }, { "code": null, "e": 2211, "s": 1986, "text": "Pathfinding: identify the optimal path depending on availability and quality for example. We’ll also include search algorithms in this category. This can be used to identify the quickest route or traffic routing for example." }, { "code": null, "e": 2397, "s": 2211, "text": "Centrality: determine the importance of the nodes in the network. This can be used to identify influencers in social media for example or identify potential attack targets in a network." }, { "code": null, "e": 2521, "s": 2397, "text": "Community detection: evaluate how a group is clustered. This can be used to segment customers and detect fraud for example." }, { "code": null, "e": 2702, "s": 2521, "text": "We will also develop the basis of Machine Learning in Graphs and Graph Learning in a third article, coming out next week. All algorithms implemented in Networkx can be found here :" }, { "code": null, "e": 2721, "s": 2702, "text": "networkx.github.io" }, { "code": null, "e": 2818, "s": 2721, "text": "As you‘ll notice, we’ll only cover the basic and most common algorithms implemented in Networkx." }, { "code": null, "e": 2923, "s": 2818, "text": "Pathfinding algorithms try to find the shortest path between two nodes by minimizing the number of hops." }, { "code": null, "e": 3091, "s": 2923, "text": "Search Algorithms does not give the shortest path. Instead, they explore graphs considering neighbors or depths of a graph. This can be used for information retrieval." }, { "code": null, "e": 3136, "s": 3091, "text": "There are two main graph search algorithms :" }, { "code": null, "e": 3241, "s": 3136, "text": "Breadth-First Search (BFS) which explores each node’s neighbor first, then neighbors of the neighbors..." }, { "code": null, "e": 3354, "s": 3241, "text": "Depth-First Search (DFS) which tries to go down a path as much as possible, and visit new neighbors if possible." }, { "code": null, "e": 3371, "s": 3354, "text": "a. Shortest Path" }, { "code": null, "e": 3475, "s": 3371, "text": "Shortest Path calculates the shortest weighted (if the graph is weighted) path between a pair of nodes." }, { "code": null, "e": 3601, "s": 3475, "text": "It is used to identify optimal driving directions or degree of separation between two people on a social network for example." }, { "code": null, "e": 3731, "s": 3601, "text": "The are many ways to compute the shortest path in a graph, including the Dijkstra’s algorithm, the default algorithm in Networkx." }, { "code": null, "e": 3808, "s": 3731, "text": "The pseudo-code for this algorithm according to Wikipedia is the following :" }, { "code": null, "e": 5298, "s": 3808, "text": "Mark all nodes of the graph as unvisited. Create a set of all the unvisited nodes called the unvisited set.Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Set the initial starting node as current.For the current node, consider all of its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value.When we are done considering all of the unvisited neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again.If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished.Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new “current node”, and go back to step 3." }, { "code": null, "e": 5406, "s": 5298, "text": "Mark all nodes of the graph as unvisited. Create a set of all the unvisited nodes called the unvisited set." }, { "code": null, "e": 5570, "s": 5406, "text": "Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Set the initial starting node as current." }, { "code": null, "e": 6096, "s": 5570, "text": "For the current node, consider all of its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value." }, { "code": null, "e": 6292, "s": 6096, "text": "When we are done considering all of the unvisited neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again." }, { "code": null, "e": 6646, "s": 6292, "text": "If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished." }, { "code": null, "e": 6793, "s": 6646, "text": "Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new “current node”, and go back to step 3." }, { "code": null, "e": 6922, "s": 6793, "text": "If you’d like to read more on the shortest path problem, check this article: https://en.wikipedia.org/wiki/Shortest_path_problem" }, { "code": null, "e": 6973, "s": 6922, "text": "In Python, the implementation is straightforward :" }, { "code": null, "e": 7041, "s": 6973, "text": "# Returns shortest path between each nodenx.shortest_path(G_karate)" }, { "code": null, "e": 7114, "s": 7041, "text": "This returns a list of the minimal path between each node of the graph :" }, { "code": null, "e": 7162, "s": 7114, "text": "{0: {0: [0], 1: [0, 1], 2: [0, 2], ..." }, { "code": null, "e": 7193, "s": 7162, "text": "b. Single Source Shortest Path" }, { "code": null, "e": 7311, "s": 7193, "text": "The Single Source Shortest Path (SSSP) finds the shortest path between a given node and all other nodes in the graph." }, { "code": null, "e": 7378, "s": 7311, "text": "It is often used for routing protocol for IP networks for example." }, { "code": null, "e": 7405, "s": 7378, "text": "c. All Pairs Shortest Path" }, { "code": null, "e": 7504, "s": 7405, "text": "The “All Pairs Shortest Path” (APSP) algorithm finds the shortest path between all pairs of nodes." }, { "code": null, "e": 7744, "s": 7504, "text": "Although providing similar results, it is quicker than calling the Single Source Shortest Path for every pair of nodes. This algorithm can typically be used to determine traffic load expected on different segments of a transportation grid." }, { "code": null, "e": 7842, "s": 7744, "text": "# Returns shortest path length between each nodelist(nx.all_pairs_shortest_path_length(G_karate))" }, { "code": null, "e": 7858, "s": 7842, "text": "Which returns :" }, { "code": null, "e": 7916, "s": 7858, "text": "[(0, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, ..." }, { "code": null, "e": 7948, "s": 7916, "text": "d. Minimum Weight Spanning Tree" }, { "code": null, "e": 8085, "s": 7948, "text": "A minimum spanning tree is a subgraph of the graph (a tree) with the minimum sum of edge weights that connects all nodes within a graph." }, { "code": null, "e": 8147, "s": 8085, "text": "Minimum spanning tree should be applied to undirected graphs." }, { "code": null, "e": 8293, "s": 8147, "text": "from networkx.algorithms import treemst = tree.minimum_spanning_edges(G_karate, algorithm='prim', data=False)edgelist = list(mst)sorted(edgelist)" }, { "code": null, "e": 8309, "s": 8293, "text": "Which returns :" }, { "code": null, "e": 8356, "s": 8309, "text": "[(0, 1),(0, 2),(0, 3),(0, 4),(0, 5),(0, 6),..." }, { "code": null, "e": 8459, "s": 8356, "text": "Community detection partitions the nodes into a several groups according to a given quality criterion." }, { "code": null, "e": 8553, "s": 8459, "text": "It is typically used to identify social communities, customers behaviors or web pages topics." }, { "code": null, "e": 8743, "s": 8553, "text": "A community is a set of connected nodes. There is however no universal definition that one can give to define communities, although the nodes within a community should be densely connected." }, { "code": null, "e": 9055, "s": 8743, "text": "A common algorithm to find communities is the Girvan Newman algorithm. It identifies communities by progressively removing edges within the network. We’ll refer to betweenness as the “edge betweenness”. It is a score proportional to the number of shortest paths between pairs of nodes that go through this edge." }, { "code": null, "e": 9103, "s": 9055, "text": "The steps of this algorithm are the following :" }, { "code": null, "e": 9329, "s": 9103, "text": "Compute the betweenness of all existing edges in the network.Remove the edge with the highest betweenness.Recompute the betweenness of all edges after the removal of this edge.Steps 2 and 3 are repeated until no edges remain." }, { "code": null, "e": 9391, "s": 9329, "text": "Compute the betweenness of all existing edges in the network." }, { "code": null, "e": 9437, "s": 9391, "text": "Remove the edge with the highest betweenness." }, { "code": null, "e": 9508, "s": 9437, "text": "Recompute the betweenness of all edges after the removal of this edge." }, { "code": null, "e": 9558, "s": 9508, "text": "Steps 2 and 3 are repeated until no edges remain." }, { "code": null, "e": 9620, "s": 9558, "text": "To implement this in Python, you can use the following code :" }, { "code": null, "e": 9800, "s": 9620, "text": "from networkx.algorithms import communityk = 1comp = community.girvan_newman(G_karate)for communities in itertools.islice(comp, k): print(tuple(sorted(c) for c in communities))" }, { "code": null, "e": 9898, "s": 9800, "text": "This heads a list of the nodes that belong to each community (k=1 means we expect 2 communities):" }, { "code": null, "e": 10029, "s": 9898, "text": "([0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21], [2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33])" }, { "code": null, "e": 10215, "s": 10029, "text": "As stated above, this method does not really scale. For this reason, methods such as the Louvain method have been developed. Such methods are however really long to run on large graphs." }, { "code": null, "e": 10387, "s": 10215, "text": "Before defining the Louvain method, it is important to introduce the notion of modularity. Modularity is a measure of how well groups have been partitioned into clusters :" }, { "code": null, "e": 10444, "s": 10387, "text": "The pseudo-code of the Louvain method is the following :" }, { "code": null, "e": 10485, "s": 10444, "text": "Assign a community to each node at first" }, { "code": null, "e": 10532, "s": 10485, "text": "Alternate the next 2 steps until convergence :" }, { "code": null, "e": 10601, "s": 10532, "text": "Create a new community with neighboring nodes to maximize modularity" }, { "code": null, "e": 10689, "s": 10601, "text": "Create a new weighted graph. Communities of the previous step become nodes of the graph" }, { "code": null, "e": 10843, "s": 10689, "text": "This might seem a bit confusing right now. In fact, the only thing we’re doing is to group the closest nodes so that we optimize the modularity criteria." }, { "code": null, "e": 11060, "s": 10843, "text": "Note that there is no theoretical guarantee of the Louvain method, but it works well in practice. Louvain’s method is present as a sub-project of NetworkX, right here: https://python-louvain.readthedocs.io/en/latest/" }, { "code": null, "e": 11089, "s": 11060, "text": "First, install the package :" }, { "code": null, "e": 11116, "s": 11089, "text": "pip install python-louvain" }, { "code": null, "e": 11180, "s": 11116, "text": "Then, compute the best partition (based on the Louvain method):" }, { "code": null, "e": 11491, "s": 11180, "text": "import communitypartition = community.best_partition(G_karate)pos = nx.spring_layout(G_karate)plt.figure(figsize=(8, 8))plt.axis('off')nx.draw_networkx_nodes(G_karate, pos, node_size=600, cmap=plt.cm.RdYlBu, node_color=list(partition.values()))nx.draw_networkx_edges(G_karate, pos, alpha=0.3)plt.show(G_karate)" }, { "code": null, "e": 11690, "s": 11491, "text": "The Strongly Connected Components (SCC) algorithm finds groups of connected nodes in a directed graph. Note that each node must be reachable in both directions from any other node in the same group." }, { "code": null, "e": 11931, "s": 11690, "text": "It is often used early in a graph analysis process to give us an idea of how our graph is structured, for example, to explore financial statements data when we look at who owns shared in what company (think about Panama papers for example)." }, { "code": null, "e": 12104, "s": 11931, "text": "The Weakly Connected Components, or Union Find algorithm finds sets of connected nodes in a directed graph where each node is reachable from any other node in the same set." }, { "code": null, "e": 12320, "s": 12104, "text": "It only needs a path to exist between pairs of nodes in one direction, whereas SCC needs a path to exist in both directions. As with SCC, Union Find is often used early in analysis to understand a graph’s structure." }, { "code": null, "e": 12441, "s": 12320, "text": "Union-Find is a pre-processing step that is essential before any kind of algorithm, to understand the graph’s structure." }, { "code": null, "e": 12491, "s": 12441, "text": "We can test for connected directed graphs using :" }, { "code": null, "e": 12544, "s": 12491, "text": "nx.is_weakly_connected(G)nx.is_strongly_connected(G)" }, { "code": null, "e": 12577, "s": 12544, "text": "Or for undirected graphs using :" }, { "code": null, "e": 12603, "s": 12577, "text": "nx.is_connected(G_karate)" }, { "code": null, "e": 12628, "s": 12603, "text": "Which returns a boolean." }, { "code": null, "e": 12715, "s": 12628, "text": "Make sure to check the Networkx documentation on the Connectivity for implementations." }, { "code": null, "e": 12830, "s": 12715, "text": "In hierarchical clustering, we build a hierarchy of clusters. We represent the clusters under a form a dendrogram." }, { "code": null, "e": 13010, "s": 12830, "text": "The idea is to analyze community structures at different scales. We usually build the dendrogram bottom-up. We start with a cluster at each node and merge the two “closest” nodes." }, { "code": null, "e": 13147, "s": 13010, "text": "But how do we measure if clusters are close? We use similarity distances. Let d(i,j) be the length of the shortest path between i and j." }, { "code": null, "e": 13309, "s": 13147, "text": "For the maximum linkage, at each step, the two clusters separated by the shortest distance are combined. The similarity distances can be illustrated as follows :" }, { "code": null, "e": 13439, "s": 13309, "text": "Back to our Karate example. Before applying hierarchical clustering, we need to define the matrix of distances between each node." }, { "code": null, "e": 13684, "s": 13439, "text": "pcc_longueurs=list(nx.all_pairs_shortest_path_length(G_karate))distances=np.zeros((n,n))# distances[i, j] is the length of the shortest path between i and jfor i in range(n): for j in range(n): distances[i, j] = pcc_longueurs[i][1][j]" }, { "code": null, "e": 13783, "s": 13684, "text": "Now, we’ll use the AgglomerativeClustering function of sklearnto identify hierarchical clustering." }, { "code": null, "e": 13949, "s": 13783, "text": "from sklearn.cluster import AgglomerativeClusteringclustering = AgglomerativeClustering(n_clusters=2,linkage='average',affinity='precomputed').fit_predict(distances)" }, { "code": null, "e": 14026, "s": 13949, "text": "And finally, draw the resulting graph with colors depending on the cluster :" }, { "code": null, "e": 14070, "s": 14026, "text": "nx.draw(G_karate, node_color = clustering)" }, { "code": null, "e": 14151, "s": 14070, "text": "The clustering coefficient measures how well two nodes tend to cluster together." }, { "code": null, "e": 14383, "s": 14151, "text": "The local clustering coefficient is a ratio of the number of triangles centered at node i over the number of triples centered at node i. In some sense, it measures how close a node i and its neighbors are to being a complete graph." }, { "code": null, "e": 14480, "s": 14383, "text": "I have tried to illustrate this computation of clustering coefficients for the following graph :" }, { "code": null, "e": 14567, "s": 14480, "text": "A global coefficient measures the density of triangles (local clusters) in the graph :" }, { "code": null, "e": 14634, "s": 14567, "text": "In the graph shown above, the clustering coefficient is equal to :" }, { "code": null, "e": 14757, "s": 14634, "text": "For Erdos-Rényi random graphs, E[Clustering Coefficient]=E[Ci]=p where p the probability defined in the previous article." }, { "code": null, "e": 14976, "s": 14757, "text": "For Baràbasi-Albert random graphs, the global clustering coefficient follows a power law depending on the number of nodes. The average clustering coefficient of nodes with degree k is proportional to the inverse of k:" }, { "code": null, "e": 15119, "s": 14976, "text": "Nodes with a low degree are connected to other nodes in their community. Nodes with high degrees are linked to nodes in different communities." }, { "code": null, "e": 15262, "s": 15119, "text": "For a given graph, in networkx, the clustering coefficient can be easily computed. First, let’s begin with the local clustering coefficients :" }, { "code": null, "e": 15342, "s": 15262, "text": "# List of local clustering coefficientslist(nx.clustering(G_barabasi).values())" }, { "code": null, "e": 15390, "s": 15342, "text": "This should return something quite similar to :" }, { "code": null, "e": 15504, "s": 15390, "text": "0.13636363636363635,0.2,0.07602339181286549,0.04843304843304843,0.09,0.055384615384615386,0.07017543859649122,..." }, { "code": null, "e": 15585, "s": 15504, "text": "And average the results to find the global clustering coefficient of the graph :" }, { "code": null, "e": 15666, "s": 15585, "text": "# Global clustering coefficientnp.mean(list(nx.clustering(G_barabasi).values()))" }, { "code": null, "e": 15680, "s": 15666, "text": "Which heads :" }, { "code": null, "e": 15699, "s": 15680, "text": "0.0965577637155059" }, { "code": null, "e": 15880, "s": 15699, "text": "Centrality measures how important a node is. This is not a clear definition, but it’s useful when we want to identify important web pages, bottlenecks in transportation networks..." }, { "code": null, "e": 16035, "s": 15880, "text": "A walk is a path which can go through the same node several times. Centrality measures vary with the type of walk considered and the way of counting them." }, { "code": null, "e": 16156, "s": 16035, "text": "PageRank estimates a current node’s importance from its linked neighbors and then again from their respective neighbors." }, { "code": null, "e": 16312, "s": 16156, "text": "Although popularized by Google, it’s a way of detecting influential nodes in any network. It is for example used to suggest connections on social networks." }, { "code": null, "e": 16540, "s": 16312, "text": "PageRank is computed by either iteratively distributing one node’s rank (originally based on the degree) over its neighbors or by randomly traversing the graph and counting the frequency of hitting each node during these walks." }, { "code": null, "e": 16700, "s": 16540, "text": "PageRank is usually computed on directed graphs. However, it will also execute on undirected graphs by converting each edge in the directed graph to two edges." }, { "code": null, "e": 16767, "s": 16700, "text": "For example, the PageRank of the Karate graph can be accessed by :" }, { "code": null, "e": 16800, "s": 16767, "text": "nx.pagerank(G_karate, alpha=0.9)" }, { "code": null, "e": 16906, "s": 16800, "text": "Where alpha is the damping parameter (by default 0.85). It should give you a list of rankings in return :" }, { "code": null, "e": 17006, "s": 16906, "text": "{0: 0.09923208031303203, 1: 0.0543403155825792, 2: 0.05919704684187155, 3: 0.036612460562853694,..." }, { "code": null, "e": 17081, "s": 17006, "text": "Degree Centrality counts the number of walks of length 1 ending at node i." }, { "code": null, "e": 17254, "s": 17081, "text": "It measures incoming and outgoing relationship. It is given by C(Xi)=di. Degree Centrality is used to identify the most influential persons on a social network for example." }, { "code": null, "e": 17330, "s": 17254, "text": "c_degree = nx.degree_centrality(G_karate)c_degree = list(c_degree.values())" }, { "code": null, "e": 17413, "s": 17330, "text": "Eigenvector Centrality is the number of walks of infinite length ending at node i." }, { "code": null, "e": 17480, "s": 17413, "text": "This gives more importance to nodes with well-connected neighbors." }, { "code": null, "e": 17576, "s": 17480, "text": "c_eigenvector = nx.eigenvector_centrality(G_karate)c_eigenvector = list(c_eigenvector.values())" }, { "code": null, "e": 17672, "s": 17576, "text": "Closeness Centrality detects nodes that are can spread information efficiently through a graph." }, { "code": null, "e": 17821, "s": 17672, "text": "It can be used to identify fake news accounts or in terrorist cells to isolate the individuals that can spread information to the rest of the graph." }, { "code": null, "e": 17928, "s": 17821, "text": "Closeness Centrality is inversely proportional to the sum of lengths of the shortest paths to other nodes." }, { "code": null, "e": 18016, "s": 17928, "text": "c_closeness = nx.closeness_centrality(G_karate)c_closeness = list(c_closeness.values())" }, { "code": null, "e": 18123, "s": 18016, "text": "Betweenness Centrality detects the amount of influence a node has over the flow of information in a graph." }, { "code": null, "e": 18328, "s": 18123, "text": "It is often used to find nodes that serve as a bridge from one part of a graph to another, for example in the package delivery processor in a telecommunication network, or in the propagation of fake news." }, { "code": null, "e": 18336, "s": 18328, "text": "Where :" }, { "code": null, "e": 18385, "s": 18336, "text": "σjk the number of shortest paths between j and k" }, { "code": null, "e": 18453, "s": 18385, "text": "σjk(i) the number of shortest paths between j and k going through i" }, { "code": null, "e": 18566, "s": 18453, "text": "The betweenness centrality measures the number of times a node acts as a bridge between two nodes. For example :" }, { "code": null, "e": 18662, "s": 18566, "text": "c_betweenness = nx.betweenness_centrality(G_karate)c_betweenness = list(c_betweenness.values())" }, { "code": null, "e": 18739, "s": 18662, "text": "In Python, the implementation relies on the built-in functions of networkx :" }, { "code": null, "e": 19683, "s": 18739, "text": "# Plot the centrality of the nodesplt.figure(figsize=(18, 12))# Degree Centralityf, axarr = plt.subplots(2, 2, num=1)plt.sca(axarr[0,0])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_degree, node_size=300, pos=pos, with_labels=True)axarr[0,0].set_title('Degree Centrality', size=16)# Eigenvalue Centralityplt.sca(axarr[0,1])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_eigenvector, node_size=300, pos=pos, with_labels=True)axarr[0,1].set_title('Eigenvalue Centrality', size=16)# Proximity Centralityplt.sca(axarr[1,0])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_closeness, node_size=300, pos=pos, with_labels=True)axarr[1,0].set_title('Proximity Centrality', size=16)# Betweenness Centralityplt.sca(axarr[1,1])nx.draw(G_karate, cmap = plt.get_cmap('inferno'), node_color = c_betweenness, node_size=300, pos=pos, with_labels=True)axarr[1,1].set_title('Betweenness Centrality', size=16)" }, { "code": null, "e": 19901, "s": 19683, "text": "We observe that the different nodes highlighted by the centrality measures are quite distinct. Betweenness centrality, for example, produces results far from the other methods, since they don’t measure the same thing." }, { "code": null, "e": 20056, "s": 19901, "text": "We have now covered the introduction to graphs, the main types of graphs, the different graph algorithms and their implementation in Python with Networkx." }, { "code": null, "e": 20213, "s": 20056, "text": "In the next article, we’ll cover graph learning which provides ways to predict nodes and edges in a graph to handle missing values or predict new relations." }, { "code": null, "e": 20341, "s": 20213, "text": "Feel free to comment if you have any question or remark. Stay tuned, the last article of this series is coming out next week :)" }, { "code": null, "e": 20422, "s": 20341, "text": "A Comprehensive Guide to Graph Algorithms in Neo4j, Mark Needham & Amy E. Hodler" }, { "code": null, "e": 20495, "s": 20422, "text": "Networkx documentation, https://networkx.github.io/documentation/stable/" } ]
Data Science Skills: Web scraping javascript using python | by Kerry Parker | Towards Data Science
There are different ways of scraping web pages using python. In my previous article, I gave an introduction to web scraping by using the libraries:requests and BeautifulSoup. However, many web pages are dynamic and use JavaScript to load their content. These websites often require a different approach to gather the data. towardsdatascience.com In this tutorial, I will present several different ways of gathering the content of a webpage that contains Javascript. The techniques used will be the following: Using selenium with Firefox web driverUsing a headless browser with phantomJSMaking an API call using a REST client or python requests library Using selenium with Firefox web driver Using a headless browser with phantomJS Making an API call using a REST client or python requests library Update November 7th 2019: Please note, the html structure of the webpage being scraped may be updated over time and this article initially reflected the structure at the time of publication in November 2018. The article has now been updated to run with the current webpage but in the future this may again change. To start the tutorial, I first needed to find a website to scrape. Before proceeding with your web scraper, it is important to always check the Terms & Conditions and the Privacy Policy on the website you plan to scrape to ensure that you are not breaking any of their terms of use. When trying to find a suitable website to demonstrate, many of the examples I first looked at explicitly stated that web crawlers were prohibited. It wasn’t until reading an article about sugar content in yogurt and wondering where I could find the latest nutritional information inspired another train of thought where I could find a suitable website; online supermarkets. Online retailers often have dynamic web pages that load content using javascript so the aim of this tutorial is to scrape the nutritional information of yogurts from the web page of an online supermarket. Since we will be using some new python libraries to access the content of the web pages and also to handle the data, these libraries will need to be installed using your usual python package manager pip. If you don’t already have beautifulsoup then you will need to install this here too. pip install seleniumpip install pandas To use selenium as a web driver, there are a few additional requirements: I will be using Firefox as the browser for my web driver so this means you will either need to install Firefox to follow this tutorial or alternatively you can use Chromium with Chrome. To use the web driver we need to install a web browser engine, geckodriver. You will need to download geckodriver for your OS, extract the file and set the executable path location. You can do this in several ways:(i) move geckodriver to a directory of your choice and define this the executable path in your python code (see later example), (ii) move geckodriver to a directory which is already a set as a directory where executable files are located, this is known as your environmental variable path. You can find out which directories are in your $PATH by the following: WindowsGo to: Control Panel > Environmental Variables > System Variables > Path Mac OSX / LinuxIn your terminal use the command: echo $PATH (iii) add geckodriver location to your PATH environment variables WindowsGo to: Control Panel > Environmental Variables > System Variables > Path > EditAdd the directory containing geckodriver to this list and save Mac OSX / LinuxAdd a line to your .bash_profile (Mac OSX) or .bash_rc (Linux) # add geckodriver to your PATHexport PATH="$PATH:/path/to/your/directory" Restart your terminal and use the command from (ii) to check that your new path has been added. Similar to the steps for geckodriver, we also need to download PhantomJS. Once downloaded, unzip the file and move to a directory of choice or add to your path executable, following the same instructions as above. In the final part of this blog, we will make a request to an API using a REST client. I will be using Insomnia but feel free to use whichever client you prefer! Following the standard steps outlined in my introductory tutorial into web scraping, I have inspected the webpage and want to extract the repeated HTML element: <div data-cid="XXXX" class="listing category_templates clearfix productListing ">...</div> As a first step, you might try using BeautifulSoup to extract this information using the following script. # import librariesimport urllib.requestfrom bs4 import BeautifulSoup# specify the urlurlpage = 'https://groceries.asda.com/search/yogurt' print(urlpage)# query the website and return the html to the variable 'page'page = urllib.request.urlopen(urlpage)# parse the html using beautiful soup and store in variable 'soup'soup = BeautifulSoup(page, 'html.parser')# find product items# at time of publication, Nov 2018:# results = soup.find_all('div', attrs={'class': 'listing category_templates clearfix productListing'})# updated Nov 2019:results = soup.find_all('div', attrs={'class': 'co-product'})print('Number of results', len(results)) Unexpectedly, when running the python script, the number of results returned is 0 even though I see many results on the web page! https://groceries.asda.com/search/yoghurtBeautifulSoup - Number of results 0 When further inspecting the page, there are many dynamic features on the web page which suggests that javascript is used to present these results. By right-clicking and selecting View Page Source there are many <script> elements in use and searching for the element above containing the data we are interested in returns no matches. The first approach to scrape this webpage is to use Selenium web driver to call the browser, search for the elements of interest and return the results. Since we are unable to access the content of the web page using Beautiful Soup, we first need to set up a web driver in our python script. # import librariesimport urllib.requestfrom bs4 import BeautifulSoupfrom selenium import webdriverimport timeimport pandas as pd# specify the urlurlpage = 'https://groceries.asda.com/search/yogurt' print(urlpage)# run firefox webdriver from executable path of your choicedriver = webdriver.Firefox(executable_path = 'your/directory/of/choice') As mentioned when installing geckodriver, if the executable file is not in an executable path, we are able to define the path in our python script. If it is in an executable path then the line above becomes: # run firefox webdriver from executable path of your choicedriver = webdriver.Firefox() Once set up, we can now connect to the web page and find the elements of interest. When loading the webpage in a browser, results often take a while to load and also may not even load until we scroll down the page. With this in mind, here we can add some javascript for the web driver to execute to perform such actions. Below is a simple example to get the page to scroll, there will be more efficient ways to do this, why not test your own javascript here and let me know in the comments what works best for you! We also add a sleep time as another method to wait for the page to fully load. # get web pagedriver.get(urlpage)# execute script to scroll down the pagedriver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")# sleep for 30stime.sleep(30)# driver.quit() If we run the script now (you can also uncommentdriver.quit() at the end to ensure the browser closes), as your python script runs Firefox will open the url specified and scroll down the page. Hopefully, you should many products load up before the script finishes running. Next, we want to get the elements of interest. Previously, using Beautiful Soup we have tried to find all elements based on the tag and class attributes, however, in this example we will use a slightly different approach to access the product information. Instead, we can search for the elements by xpath, based on the XML structure or the css selector. We can inspect the element of interest and within the toolbar, right-click on the highlighted element and Copy > Copy xpath (or Copy Selector). This is another interesting way to understand the structure of the html. In this case we will be using the xpath to find the elements, and we can then print the number of results that match: # find elements by xpath# at time of publication, Nov 2018:# results = driver.find_elements_by_xpath("//*[@id='componentsContainer']//*[contains(@id,'listingsContainer')]//*[@class='product active']//*[@class='title productTitle']")# updated Nov 2019:results = driver.find_elements_by_xpath("//*[@class=' co-product-list__main-cntr']//*[@class=' co-item ']//*[@class='co-product']//*[@class='co-item__title-container']//*[@class='co-product__title']")print('Number of results', len(results)) One of the main reasons for using the xpath rather than using the element as the results have a few elements where the stem of the id is listingsContainer with some additional words, so the contains function has been used to select all of the results but also to exclude any of the other div elements within the container such as for adverts. Firefox Webdriver - Number of results 38 Now that we have some results from the page, we can loop over each result and save the data of interest. In this case, we can save the product name and link. Note that there are actually more than 38 results on the web page. This number also may vary depending on how many results load when you connect to the page. All results can be gathered by either changing the javascript we execute as suggested above, alternatively other methods will be explored in the following sections. # create empty array to store datadata = []# loop over resultsfor result in results: product_name = result.text link = result.find_element_by_tag_name('a') product_link = link.get_attribute("href") # append dict to array data.append({"product" : product_name, "link" : product_link}) Outside of this loop, we can close the browser and as we imported the pandas library, we can make use of that by saving the data we have scraped to a dataframe. We can print the dataframe to view the content. # close driver driver.quit()# save to pandas dataframedf = pd.DataFrame(data)print(df) In this format, we can very simply write this data to a csv. # write to csvdf.to_csv('asdaYogurtLink.csv') Using Selenium with geckodriver is a quick way to scrape the web pages that are using javascript but there are a few drawbacks. I have found that sometimes the page does not load (I’m sure that this could be more efficient by changing the javascript we execute as mentioned above, but I am new to JS so this might require some time), but also loading the browser and waiting for the page to load takes time. Another option, we can use a headless browser. This should speed up the scraping as we don’t have to wait for the browser to load each time. When using PhantomJS as a headless browser instead of geckodriver, the only difference is how the web driver is loaded. This means that we can follow the method above but change the line that initialises the web driver which becomes: # run phantomJS webdriver from executable path of your choicedriver = webdriver.PhantomJS(executable_path = 'your/directory/of/choice') Note here that Selenium support for PhantomJS has been depreciated and provides a warning. It is also possible to use headless mode with geckodriver by using the headless option: from selenium import webdriverfrom selenium.webdriver.firefox.options import Optionsoptions = Options()options.headless = Truedriver = webdriver.Firefox(firefox_options=options, executable_path = 'your/directory/of/choice') By using the headless browser, we should see an improvement in time for the script to run since we aren’t opening a browser but not all results are scraped in a similar way to using firefox webdriver in normal mode. The final approach we will discuss in this tutorial is making a request to an API. When inspecting the Network page XHR files, as a page loads this page displays the requests that are being made. Within this list is a /search request which calls an API endpoint to get the results that are presented on the page. We are able to make the same request using either a REST client or with a few lines of python. If we inspect the search file and look at the headers, the request url containing the keyword and other parameters that are needed to make the request. Below the general details are the response and request headers which we may need later. To get the response, we can take the request url and as a test enter this into the address bar of your browser. Since the parameters are added in the string we can also try to remove all but the keyword parameter to test whether any further parameters are required. In this case, the keyword query returns the results in the browser, so we can also perform the same request using a REST client or in python. Using insomnia we can enter the request url and send the request. This returns a JSON response containing the data that we are looking for! This example is very straight forward with no headers or security tokens required. For other cases, the REST client allows you to enter any additional response parameters that you can get from the inspect tool when gathering the request details. We can also make the same request from python using the urllib.request library in the same way that we connect to a web page before scraping. The JSON response can be made more readable by adding a few parameters for indenting and sorting the keys so that we can now open the file and see the response data provided to the webpage when a search is made. # import json libraryimport json# request urlurlreq = 'https://groceries.asda.com/api/items/search?keyword=yogurt'# get responseresponse = urllib.request.urlopen(urlreq)# load as jsonjresponse = json.load(response)# write to file as pretty printwith open('asdaresp.json', 'w') as outfile: json.dump(jresponse, outfile, sort_keys=True, indent=4) For now, we will keep all the data. My next tutorial will cover data structures and output in more detail so we can manipulate the JSON and find the relevant data. This tutorial has outlined some of the methods we can use to scrape web pages that use javascript. These methods include: Using selenium web driver to connect to a web page either with Firefox web driver, PhantomJS, headless browser Use the web driver to find the elements of interest Loop over the results and saving variables of interest Saving data to a dataframe Writing to a csv file Inspect the web page to find HTTP request details Make the GET request using either a browser, REST client, python Whilst the HTTP request method is quicker to implement in this tutorial and provides all the data we need from one request, this is not always the case. Not all websites will make their requests visible, additional security may be in place with expiring authentication tokens or the output data may require significant cleaning which would be more work than using a web driver with some javascript to enable loading all results and looping over all pages. This tutorial provides a few different alternatives you can try to make it possible to scrape javascript. In my next tutorial we will explore data structures, manipulating data and writing to output files or databases. Thank you for reading! If you enjoyed my article then subscribe to my monthly newsletter where you can get my latest articles and top resources delivered right to your inbox, or find out more about what I’m up to on my website. If you are new to python or want to improve, check out my article with a list of learning resources including courses in data science:
[ { "code": null, "e": 494, "s": 171, "text": "There are different ways of scraping web pages using python. In my previous article, I gave an introduction to web scraping by using the libraries:requests and BeautifulSoup. However, many web pages are dynamic and use JavaScript to load their content. These websites often require a different approach to gather the data." }, { "code": null, "e": 517, "s": 494, "text": "towardsdatascience.com" }, { "code": null, "e": 680, "s": 517, "text": "In this tutorial, I will present several different ways of gathering the content of a webpage that contains Javascript. The techniques used will be the following:" }, { "code": null, "e": 823, "s": 680, "text": "Using selenium with Firefox web driverUsing a headless browser with phantomJSMaking an API call using a REST client or python requests library" }, { "code": null, "e": 862, "s": 823, "text": "Using selenium with Firefox web driver" }, { "code": null, "e": 902, "s": 862, "text": "Using a headless browser with phantomJS" }, { "code": null, "e": 968, "s": 902, "text": "Making an API call using a REST client or python requests library" }, { "code": null, "e": 1282, "s": 968, "text": "Update November 7th 2019: Please note, the html structure of the webpage being scraped may be updated over time and this article initially reflected the structure at the time of publication in November 2018. The article has now been updated to run with the current webpage but in the future this may again change." }, { "code": null, "e": 1565, "s": 1282, "text": "To start the tutorial, I first needed to find a website to scrape. Before proceeding with your web scraper, it is important to always check the Terms & Conditions and the Privacy Policy on the website you plan to scrape to ensure that you are not breaking any of their terms of use." }, { "code": null, "e": 1939, "s": 1565, "text": "When trying to find a suitable website to demonstrate, many of the examples I first looked at explicitly stated that web crawlers were prohibited. It wasn’t until reading an article about sugar content in yogurt and wondering where I could find the latest nutritional information inspired another train of thought where I could find a suitable website; online supermarkets." }, { "code": null, "e": 2144, "s": 1939, "text": "Online retailers often have dynamic web pages that load content using javascript so the aim of this tutorial is to scrape the nutritional information of yogurts from the web page of an online supermarket." }, { "code": null, "e": 2433, "s": 2144, "text": "Since we will be using some new python libraries to access the content of the web pages and also to handle the data, these libraries will need to be installed using your usual python package manager pip. If you don’t already have beautifulsoup then you will need to install this here too." }, { "code": null, "e": 2472, "s": 2433, "text": "pip install seleniumpip install pandas" }, { "code": null, "e": 2546, "s": 2472, "text": "To use selenium as a web driver, there are a few additional requirements:" }, { "code": null, "e": 2732, "s": 2546, "text": "I will be using Firefox as the browser for my web driver so this means you will either need to install Firefox to follow this tutorial or alternatively you can use Chromium with Chrome." }, { "code": null, "e": 2914, "s": 2732, "text": "To use the web driver we need to install a web browser engine, geckodriver. You will need to download geckodriver for your OS, extract the file and set the executable path location." }, { "code": null, "e": 3074, "s": 2914, "text": "You can do this in several ways:(i) move geckodriver to a directory of your choice and define this the executable path in your python code (see later example)," }, { "code": null, "e": 3307, "s": 3074, "text": "(ii) move geckodriver to a directory which is already a set as a directory where executable files are located, this is known as your environmental variable path. You can find out which directories are in your $PATH by the following:" }, { "code": null, "e": 3321, "s": 3307, "text": "WindowsGo to:" }, { "code": null, "e": 3387, "s": 3321, "text": "Control Panel > Environmental Variables > System Variables > Path" }, { "code": null, "e": 3436, "s": 3387, "text": "Mac OSX / LinuxIn your terminal use the command:" }, { "code": null, "e": 3447, "s": 3436, "text": "echo $PATH" }, { "code": null, "e": 3513, "s": 3447, "text": "(iii) add geckodriver location to your PATH environment variables" }, { "code": null, "e": 3527, "s": 3513, "text": "WindowsGo to:" }, { "code": null, "e": 3662, "s": 3527, "text": "Control Panel > Environmental Variables > System Variables > Path > EditAdd the directory containing geckodriver to this list and save" }, { "code": null, "e": 3740, "s": 3662, "text": "Mac OSX / LinuxAdd a line to your .bash_profile (Mac OSX) or .bash_rc (Linux)" }, { "code": null, "e": 3814, "s": 3740, "text": "# add geckodriver to your PATHexport PATH=\"$PATH:/path/to/your/directory\"" }, { "code": null, "e": 3910, "s": 3814, "text": "Restart your terminal and use the command from (ii) to check that your new path has been added." }, { "code": null, "e": 4124, "s": 3910, "text": "Similar to the steps for geckodriver, we also need to download PhantomJS. Once downloaded, unzip the file and move to a directory of choice or add to your path executable, following the same instructions as above." }, { "code": null, "e": 4285, "s": 4124, "text": "In the final part of this blog, we will make a request to an API using a REST client. I will be using Insomnia but feel free to use whichever client you prefer!" }, { "code": null, "e": 4446, "s": 4285, "text": "Following the standard steps outlined in my introductory tutorial into web scraping, I have inspected the webpage and want to extract the repeated HTML element:" }, { "code": null, "e": 4537, "s": 4446, "text": "<div data-cid=\"XXXX\" class=\"listing category_templates clearfix productListing \">...</div>" }, { "code": null, "e": 4644, "s": 4537, "text": "As a first step, you might try using BeautifulSoup to extract this information using the following script." }, { "code": null, "e": 5282, "s": 4644, "text": "# import librariesimport urllib.requestfrom bs4 import BeautifulSoup# specify the urlurlpage = 'https://groceries.asda.com/search/yogurt' print(urlpage)# query the website and return the html to the variable 'page'page = urllib.request.urlopen(urlpage)# parse the html using beautiful soup and store in variable 'soup'soup = BeautifulSoup(page, 'html.parser')# find product items# at time of publication, Nov 2018:# results = soup.find_all('div', attrs={'class': 'listing category_templates clearfix productListing'})# updated Nov 2019:results = soup.find_all('div', attrs={'class': 'co-product'})print('Number of results', len(results))" }, { "code": null, "e": 5412, "s": 5282, "text": "Unexpectedly, when running the python script, the number of results returned is 0 even though I see many results on the web page!" }, { "code": null, "e": 5489, "s": 5412, "text": "https://groceries.asda.com/search/yoghurtBeautifulSoup - Number of results 0" }, { "code": null, "e": 5822, "s": 5489, "text": "When further inspecting the page, there are many dynamic features on the web page which suggests that javascript is used to present these results. By right-clicking and selecting View Page Source there are many <script> elements in use and searching for the element above containing the data we are interested in returns no matches." }, { "code": null, "e": 5975, "s": 5822, "text": "The first approach to scrape this webpage is to use Selenium web driver to call the browser, search for the elements of interest and return the results." }, { "code": null, "e": 6114, "s": 5975, "text": "Since we are unable to access the content of the web page using Beautiful Soup, we first need to set up a web driver in our python script." }, { "code": null, "e": 6458, "s": 6114, "text": "# import librariesimport urllib.requestfrom bs4 import BeautifulSoupfrom selenium import webdriverimport timeimport pandas as pd# specify the urlurlpage = 'https://groceries.asda.com/search/yogurt' print(urlpage)# run firefox webdriver from executable path of your choicedriver = webdriver.Firefox(executable_path = 'your/directory/of/choice')" }, { "code": null, "e": 6666, "s": 6458, "text": "As mentioned when installing geckodriver, if the executable file is not in an executable path, we are able to define the path in our python script. If it is in an executable path then the line above becomes:" }, { "code": null, "e": 6754, "s": 6666, "text": "# run firefox webdriver from executable path of your choicedriver = webdriver.Firefox()" }, { "code": null, "e": 7269, "s": 6754, "text": "Once set up, we can now connect to the web page and find the elements of interest. When loading the webpage in a browser, results often take a while to load and also may not even load until we scroll down the page. With this in mind, here we can add some javascript for the web driver to execute to perform such actions. Below is a simple example to get the page to scroll, there will be more efficient ways to do this, why not test your own javascript here and let me know in the comments what works best for you!" }, { "code": null, "e": 7348, "s": 7269, "text": "We also add a sleep time as another method to wait for the page to fully load." }, { "code": null, "e": 7596, "s": 7348, "text": "# get web pagedriver.get(urlpage)# execute script to scroll down the pagedriver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;\")# sleep for 30stime.sleep(30)# driver.quit()" }, { "code": null, "e": 7869, "s": 7596, "text": "If we run the script now (you can also uncommentdriver.quit() at the end to ensure the browser closes), as your python script runs Firefox will open the url specified and scroll down the page. Hopefully, you should many products load up before the script finishes running." }, { "code": null, "e": 8223, "s": 7869, "text": "Next, we want to get the elements of interest. Previously, using Beautiful Soup we have tried to find all elements based on the tag and class attributes, however, in this example we will use a slightly different approach to access the product information. Instead, we can search for the elements by xpath, based on the XML structure or the css selector." }, { "code": null, "e": 8558, "s": 8223, "text": "We can inspect the element of interest and within the toolbar, right-click on the highlighted element and Copy > Copy xpath (or Copy Selector). This is another interesting way to understand the structure of the html. In this case we will be using the xpath to find the elements, and we can then print the number of results that match:" }, { "code": null, "e": 9050, "s": 8558, "text": "# find elements by xpath# at time of publication, Nov 2018:# results = driver.find_elements_by_xpath(\"//*[@id='componentsContainer']//*[contains(@id,'listingsContainer')]//*[@class='product active']//*[@class='title productTitle']\")# updated Nov 2019:results = driver.find_elements_by_xpath(\"//*[@class=' co-product-list__main-cntr']//*[@class=' co-item ']//*[@class='co-product']//*[@class='co-item__title-container']//*[@class='co-product__title']\")print('Number of results', len(results))" }, { "code": null, "e": 9393, "s": 9050, "text": "One of the main reasons for using the xpath rather than using the element as the results have a few elements where the stem of the id is listingsContainer with some additional words, so the contains function has been used to select all of the results but also to exclude any of the other div elements within the container such as for adverts." }, { "code": null, "e": 9434, "s": 9393, "text": "Firefox Webdriver - Number of results 38" }, { "code": null, "e": 9592, "s": 9434, "text": "Now that we have some results from the page, we can loop over each result and save the data of interest. In this case, we can save the product name and link." }, { "code": null, "e": 9915, "s": 9592, "text": "Note that there are actually more than 38 results on the web page. This number also may vary depending on how many results load when you connect to the page. All results can be gathered by either changing the javascript we execute as suggested above, alternatively other methods will be explored in the following sections." }, { "code": null, "e": 10214, "s": 9915, "text": "# create empty array to store datadata = []# loop over resultsfor result in results: product_name = result.text link = result.find_element_by_tag_name('a') product_link = link.get_attribute(\"href\") # append dict to array data.append({\"product\" : product_name, \"link\" : product_link})" }, { "code": null, "e": 10423, "s": 10214, "text": "Outside of this loop, we can close the browser and as we imported the pandas library, we can make use of that by saving the data we have scraped to a dataframe. We can print the dataframe to view the content." }, { "code": null, "e": 10510, "s": 10423, "text": "# close driver driver.quit()# save to pandas dataframedf = pd.DataFrame(data)print(df)" }, { "code": null, "e": 10571, "s": 10510, "text": "In this format, we can very simply write this data to a csv." }, { "code": null, "e": 10617, "s": 10571, "text": "# write to csvdf.to_csv('asdaYogurtLink.csv')" }, { "code": null, "e": 11025, "s": 10617, "text": "Using Selenium with geckodriver is a quick way to scrape the web pages that are using javascript but there are a few drawbacks. I have found that sometimes the page does not load (I’m sure that this could be more efficient by changing the javascript we execute as mentioned above, but I am new to JS so this might require some time), but also loading the browser and waiting for the page to load takes time." }, { "code": null, "e": 11166, "s": 11025, "text": "Another option, we can use a headless browser. This should speed up the scraping as we don’t have to wait for the browser to load each time." }, { "code": null, "e": 11400, "s": 11166, "text": "When using PhantomJS as a headless browser instead of geckodriver, the only difference is how the web driver is loaded. This means that we can follow the method above but change the line that initialises the web driver which becomes:" }, { "code": null, "e": 11536, "s": 11400, "text": "# run phantomJS webdriver from executable path of your choicedriver = webdriver.PhantomJS(executable_path = 'your/directory/of/choice')" }, { "code": null, "e": 11627, "s": 11536, "text": "Note here that Selenium support for PhantomJS has been depreciated and provides a warning." }, { "code": null, "e": 11715, "s": 11627, "text": "It is also possible to use headless mode with geckodriver by using the headless option:" }, { "code": null, "e": 11939, "s": 11715, "text": "from selenium import webdriverfrom selenium.webdriver.firefox.options import Optionsoptions = Options()options.headless = Truedriver = webdriver.Firefox(firefox_options=options, executable_path = 'your/directory/of/choice')" }, { "code": null, "e": 12155, "s": 11939, "text": "By using the headless browser, we should see an improvement in time for the script to run since we aren’t opening a browser but not all results are scraped in a similar way to using firefox webdriver in normal mode." }, { "code": null, "e": 12468, "s": 12155, "text": "The final approach we will discuss in this tutorial is making a request to an API. When inspecting the Network page XHR files, as a page loads this page displays the requests that are being made. Within this list is a /search request which calls an API endpoint to get the results that are presented on the page." }, { "code": null, "e": 12563, "s": 12468, "text": "We are able to make the same request using either a REST client or with a few lines of python." }, { "code": null, "e": 12803, "s": 12563, "text": "If we inspect the search file and look at the headers, the request url containing the keyword and other parameters that are needed to make the request. Below the general details are the response and request headers which we may need later." }, { "code": null, "e": 13211, "s": 12803, "text": "To get the response, we can take the request url and as a test enter this into the address bar of your browser. Since the parameters are added in the string we can also try to remove all but the keyword parameter to test whether any further parameters are required. In this case, the keyword query returns the results in the browser, so we can also perform the same request using a REST client or in python." }, { "code": null, "e": 13277, "s": 13211, "text": "Using insomnia we can enter the request url and send the request." }, { "code": null, "e": 13351, "s": 13277, "text": "This returns a JSON response containing the data that we are looking for!" }, { "code": null, "e": 13597, "s": 13351, "text": "This example is very straight forward with no headers or security tokens required. For other cases, the REST client allows you to enter any additional response parameters that you can get from the inspect tool when gathering the request details." }, { "code": null, "e": 13739, "s": 13597, "text": "We can also make the same request from python using the urllib.request library in the same way that we connect to a web page before scraping." }, { "code": null, "e": 13951, "s": 13739, "text": "The JSON response can be made more readable by adding a few parameters for indenting and sorting the keys so that we can now open the file and see the response data provided to the webpage when a search is made." }, { "code": null, "e": 14299, "s": 13951, "text": "# import json libraryimport json# request urlurlreq = 'https://groceries.asda.com/api/items/search?keyword=yogurt'# get responseresponse = urllib.request.urlopen(urlreq)# load as jsonjresponse = json.load(response)# write to file as pretty printwith open('asdaresp.json', 'w') as outfile: json.dump(jresponse, outfile, sort_keys=True, indent=4)" }, { "code": null, "e": 14463, "s": 14299, "text": "For now, we will keep all the data. My next tutorial will cover data structures and output in more detail so we can manipulate the JSON and find the relevant data." }, { "code": null, "e": 14585, "s": 14463, "text": "This tutorial has outlined some of the methods we can use to scrape web pages that use javascript. These methods include:" }, { "code": null, "e": 14696, "s": 14585, "text": "Using selenium web driver to connect to a web page either with Firefox web driver, PhantomJS, headless browser" }, { "code": null, "e": 14748, "s": 14696, "text": "Use the web driver to find the elements of interest" }, { "code": null, "e": 14803, "s": 14748, "text": "Loop over the results and saving variables of interest" }, { "code": null, "e": 14830, "s": 14803, "text": "Saving data to a dataframe" }, { "code": null, "e": 14852, "s": 14830, "text": "Writing to a csv file" }, { "code": null, "e": 14902, "s": 14852, "text": "Inspect the web page to find HTTP request details" }, { "code": null, "e": 14967, "s": 14902, "text": "Make the GET request using either a browser, REST client, python" }, { "code": null, "e": 15529, "s": 14967, "text": "Whilst the HTTP request method is quicker to implement in this tutorial and provides all the data we need from one request, this is not always the case. Not all websites will make their requests visible, additional security may be in place with expiring authentication tokens or the output data may require significant cleaning which would be more work than using a web driver with some javascript to enable loading all results and looping over all pages. This tutorial provides a few different alternatives you can try to make it possible to scrape javascript." }, { "code": null, "e": 15642, "s": 15529, "text": "In my next tutorial we will explore data structures, manipulating data and writing to output files or databases." }, { "code": null, "e": 15870, "s": 15642, "text": "Thank you for reading! If you enjoyed my article then subscribe to my monthly newsletter where you can get my latest articles and top resources delivered right to your inbox, or find out more about what I’m up to on my website." } ]
The Medium-Sized Dataset. Too big for RAM, too small for a... | by João Paulo Figueira | Towards Data Science
Small datasets are cool. You can load them into memory and manipulate them at will, no sweat. Massive datasets are also cool. They have lots of data and the promise of exciting models and analyses. You gladly pay the price of the required cluster just to handle all that goodness. Medium-sized datasets are a pain. They are either small enough to fit your RAM but too cumbersome to handle or just a bit larger than your memory but not worthy of the cluster cost. How do you tackle such a scenario? There are several solutions to handle medium-sized datasets, and my favorite is to use a local database. You can fit the data in local storage and just bring into memory what you need to handle. An old but proven solution. My regular setup is the Jupyter notebook supported by the Python machine learning and data analysis ecosystem. A natural local database choice for such an environment is SQLite. The Python distribution comes packaged with an implementation of this database with a straightforward and intuitive API. In this article, I illustrate such use with a dataset of vehicle fuel and electric energy consumption, which is medium-size, as described above. Before we move along, I advise you to install an SQLite database editor such as SQLiteStudio. Tools such as this one will make your life easier when creating and inspecting your dataset, and I have found their use to be invaluable. In 2019 G. S. Oh, David J. Leblanc, and Huei Peng published a paper on the Vehicle Energy Dataset (VED) containing one year’s worth of vehicle trajectory and energy consumption data. These data were collected from November 2017 to November 2018 in Ann Arbor and refer to a sample of 383 vehicles of diverse types and power sources. Please see the paper for an official description of the dataset and its contents. The dataset is distributed from the authors’ GitHub repository and consists of two subsets named dynamic and static data. The former contains all the collected signal data, while the latter consists of two Microsoft Excel files containing information about the studied vehicles. Two compressed files contain the whole dynamic dataset. All the code illustrated below is available on the article’s GitHub repository. To download the data, we can simply clone the repository to the local storage. This process is quite easy to do: git clone https://github.com/gsoh/VED.git ./ved Once cloned, the newly created local directory contains the license file, a documentation file, and a data directory with both datasets. Before proceeding, we must first decompress the dynamic data files with a specific tool: 7z x ./ved/Data/VED_DynamicData_Part1.7z -o./data7z x ./ved/Data/VED_DynamicData_Part2.7z -o./data Please note that you may have to install the appropriate file compression tool for the above command lines to work. Once completed, the local data directory will have 55 CSV files with the weekly dynamic data. We are now ready to read them and insert them into an SQLite database. You can find the download and decompression process implemented as the first Jupyter notebook in the accompanying GitHub repository. Before we can use it, we must first create the SQLite database through the provided Python API. To make the whole process more straightforward and more comfortable to manage, I created a higher level class to interface with the database. To access it, you just need to instantiate an object: from sqlapi import VedDbdb = VedDb() The object instantiation executes several tasks behind the scenes, such as opening the database file and, if it does not yet exist, create it along with a baseline structure. The code creates the database tables and indexes using externally stored SQL scripts such as the one below that creates the table containing all vehicles. CREATE TABLE vehicle ( vehicle_id INTEGER PRIMARY KEY ASC, vehicle_type TEXT, vehicle_class TEXT, engine TEXT, transmission TEXT, drive_wheels TEXT, weight FLOAT); An external JSON file encodes the execution order for these files. This setup allows for a straightforward extension of both SQL files and their execution order. Here is a sample of the JSON file’s contents at the time of this writing: { "sequence": ["tables", "indexes"], "tables": [ "tables/vehicle.sql", "tables/signal.sql", "tables/move.sql" ], "indexes": [ "indexes/idx_signal_vehicle_day_ts.sql", "indexes/idx_move_vehicle_day.sql" ]} The “sequence” tag contains a list with the names of the JSON tags to execute in order, so in this case, we start by creating the tables and then the indexes. Each entry in the “tables” list is the relative path to the SQL script to execute. The base path is a default constructor parameter. With the database ready to use, we can start importing the data from the downloaded VED data files. The VED dynamic data lives in several manageable CSV files, so we can read them one at a time into a Pandas DataFrame and batch insert the data into the database. The Pandas library makes it quite easy to read CSV files, so we can use it to ease reading the data into memory. Here’s the code to do so (please refer to the second notebook in the GitHub repository): for file in tqdm(files): df = read_data_frame(file) signals = [] for row in df.itertuples(index=False): signals.append(row) db.insert_signals(signals) The function that inserts signals also uses a SQL script that is externally stored. To manage these external references, I created a class that loads the SQL scripts from storage on-demand and stores them in memory using a dictionary. This solution has the advantage of allowing you to change the SQL script without changing the Python code, and the memory caching means that you only take a small performance hit when loading the text file the first time. The next time will have a near-zero performance impact. Here is how the function looks: def insert_vehicles(self, vehicles): conn = self.connect() cur = conn.cursor() sql = self.sql_cache.get("vehicle/insert") cur.executemany(sql, vehicles) conn.commit() cur.close() conn.close() As you might have guessed, the script’s key name is the file’s relative pathname without the extension. The same process applies to the static dataset, but this time using Panda’s functions to read Excel files into DataFrames. To illustrate how to explore the dataset using the SQLite interface, let us start by profiling the types of vehicles that generated data. We start by issuing a query and storing the result in a Pandas DataFrame: vehicles = db.query_df("select * from vehicle") With all the vehicle data loaded into DataFrame, we can use the standard query methods to reveal the data structure: vehicles.groupby(by='vehicle_type').count() This command produces the following output: We can also run quick inspections through the head and tail functions, like this: db.head("select * from signal where vehicle_id = 10", rows=20) We can now proceed to some more sophisticated and insightful analyses using the simple tools described above. The presence of high-frequency location data in the dataset allows us to perform trajectory analyses to help characterize the vehicle behaviors. Detecting individual vehicle trips, between known stop locations, is usually a complicated process. Fortunately, we are in luck with this dataset, as the data anonymization process baked that for us. The data collection process for the VED ensured driver anonymization through a relatively simple three-step approach. This process turned out to be quite relevant to this study as it produced, as a by-product, a critical piece of information: individualized vehicle trajectories. To anonymize the driver information, the study authors applied techniques of Random Fogging, Geo-fencing, and Major Intersection Bounding. The random fogging method removes observed locations near the start and the end of the trip. The geo-fencing technique clips observations outside a bounding box defined around the city’s boundaries. The authors also clipped trips around the first and last significant intersections. Besides driver anonymization, these procedures also have the benefit of producing individual trajectories that are readily usable. After some cursory inspection, it is easy to realize that we can identify trips using two features only, namely the “day number” and the vehicle identifier. Let us first count the number of different individual vehicle trips. There are over thirty-two thousand trips in the dataset. Knowing how to identify vehicle trips uniquely, we can create a table containing summary information about each one. This table will prove its usefulness as an index into the signal table when iterating over trips and also help in aggregating trips per vehicle. The database startup code created an extra table named “move” to store each trip identifier. We can fill this table using a more complex query: insert into move (vehicle_id, day_num, ts_ini, ts_end)select tt.vehicle_id, tt.day_num, ( select min(s1.time_stamp) from signal s1 where s1.day_num = tt.day_num and s1.vehicle_id = tt.vehicle_id ) as ts_ini, ( select max(s2.time_stamp) from signal s2 where s2.day_num = tt.day_num and s2.vehicle_id = tt.vehicle_id ) as ts_endfrom (select distinct vehicle_id, day_num from signal) tt; You can try running this from the notebook using the “query” function or use a ready-made shortcut in the database interface object: db.generate_moves() This function illustrates the principle of decoupling the SQL script from the Python code. It starts by loading the text through the SQL script caching object and then executes it. The result is a table with all the unique trips for each vehicle. If we need to inspect the journeys of a single car, we can do so using simple queries with joins to the signal table to pull up the necessary detailed information. Let us illustrate this using a map. To extract the geographic information of an arbitrary trip, we can use the “move” table as a selector into the “signal” table. sql = """select s.latitude, s.longitudefrom signal s inner join move m on m.vehicle_id = s.vehicle_id and m.day_num = s.day_numwhere m.move_id = 1"""locations = db.query(sql) There are two things to note about the code above. First, I selected an arbitrary trip through its unique identifier. A more realistic scenario would involve selecting a vehicle and a period for a trip inspection. Second, this version of the query function returns a list of tuples with the same order as declared in the SQL text. This arrangement is quite convenient as we can immediately feed the query’s return to the map object of choice, a Folium PolyLine. tiles = "cartodbpositron"map = folium.Map(prefer_canvas=True)folium.TileLayer(tiles).add_to(map)color='#3388ff'opacity=0.7lats = [l[0] for l in locations]lons = [l[1] for l in locations]min_lat, max_lat = min(lats), max(lats)min_lon, max_lon = min(lons), max(lons)map.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]])polyline = PolyLine(locations, color=color, opacity=opacity)polyline.add_to(map) Here is the result: In this article, I showed how to use SQLite as a partial alternative to Pandas when it comes to managing medium-sized datasets. This approach can be especially practical when you are short in RAM. By mixing the familiar Pandas API with a bit of SQL, you can perform compelling analyses on datasets that would not comfortably fit in your main memory. I will follow up on this article with more in-depth analyses of the VED, as it is such an intriguing dataset, mixing geographic information with vehicle energy performance data. Stay tuned for the forthcoming articles. [1] G. S. Oh, David J. Leblanc, Huei Peng. Vehicle Energy Dataset (VED), A Large-scale Dataset for Vehicle Energy Consumption Research. [2] GitHub repository
[ { "code": null, "e": 669, "s": 171, "text": "Small datasets are cool. You can load them into memory and manipulate them at will, no sweat. Massive datasets are also cool. They have lots of data and the promise of exciting models and analyses. You gladly pay the price of the required cluster just to handle all that goodness. Medium-sized datasets are a pain. They are either small enough to fit your RAM but too cumbersome to handle or just a bit larger than your memory but not worthy of the cluster cost. How do you tackle such a scenario?" }, { "code": null, "e": 892, "s": 669, "text": "There are several solutions to handle medium-sized datasets, and my favorite is to use a local database. You can fit the data in local storage and just bring into memory what you need to handle. An old but proven solution." }, { "code": null, "e": 1191, "s": 892, "text": "My regular setup is the Jupyter notebook supported by the Python machine learning and data analysis ecosystem. A natural local database choice for such an environment is SQLite. The Python distribution comes packaged with an implementation of this database with a straightforward and intuitive API." }, { "code": null, "e": 1336, "s": 1191, "text": "In this article, I illustrate such use with a dataset of vehicle fuel and electric energy consumption, which is medium-size, as described above." }, { "code": null, "e": 1568, "s": 1336, "text": "Before we move along, I advise you to install an SQLite database editor such as SQLiteStudio. Tools such as this one will make your life easier when creating and inspecting your dataset, and I have found their use to be invaluable." }, { "code": null, "e": 1982, "s": 1568, "text": "In 2019 G. S. Oh, David J. Leblanc, and Huei Peng published a paper on the Vehicle Energy Dataset (VED) containing one year’s worth of vehicle trajectory and energy consumption data. These data were collected from November 2017 to November 2018 in Ann Arbor and refer to a sample of 383 vehicles of diverse types and power sources. Please see the paper for an official description of the dataset and its contents." }, { "code": null, "e": 2317, "s": 1982, "text": "The dataset is distributed from the authors’ GitHub repository and consists of two subsets named dynamic and static data. The former contains all the collected signal data, while the latter consists of two Microsoft Excel files containing information about the studied vehicles. Two compressed files contain the whole dynamic dataset." }, { "code": null, "e": 2397, "s": 2317, "text": "All the code illustrated below is available on the article’s GitHub repository." }, { "code": null, "e": 2510, "s": 2397, "text": "To download the data, we can simply clone the repository to the local storage. This process is quite easy to do:" }, { "code": null, "e": 2558, "s": 2510, "text": "git clone https://github.com/gsoh/VED.git ./ved" }, { "code": null, "e": 2784, "s": 2558, "text": "Once cloned, the newly created local directory contains the license file, a documentation file, and a data directory with both datasets. Before proceeding, we must first decompress the dynamic data files with a specific tool:" }, { "code": null, "e": 2883, "s": 2784, "text": "7z x ./ved/Data/VED_DynamicData_Part1.7z -o./data7z x ./ved/Data/VED_DynamicData_Part2.7z -o./data" }, { "code": null, "e": 3164, "s": 2883, "text": "Please note that you may have to install the appropriate file compression tool for the above command lines to work. Once completed, the local data directory will have 55 CSV files with the weekly dynamic data. We are now ready to read them and insert them into an SQLite database." }, { "code": null, "e": 3297, "s": 3164, "text": "You can find the download and decompression process implemented as the first Jupyter notebook in the accompanying GitHub repository." }, { "code": null, "e": 3589, "s": 3297, "text": "Before we can use it, we must first create the SQLite database through the provided Python API. To make the whole process more straightforward and more comfortable to manage, I created a higher level class to interface with the database. To access it, you just need to instantiate an object:" }, { "code": null, "e": 3626, "s": 3589, "text": "from sqlapi import VedDbdb = VedDb()" }, { "code": null, "e": 3956, "s": 3626, "text": "The object instantiation executes several tasks behind the scenes, such as opening the database file and, if it does not yet exist, create it along with a baseline structure. The code creates the database tables and indexes using externally stored SQL scripts such as the one below that creates the table containing all vehicles." }, { "code": null, "e": 4175, "s": 3956, "text": "CREATE TABLE vehicle ( vehicle_id INTEGER PRIMARY KEY ASC, vehicle_type TEXT, vehicle_class TEXT, engine TEXT, transmission TEXT, drive_wheels TEXT, weight FLOAT);" }, { "code": null, "e": 4411, "s": 4175, "text": "An external JSON file encodes the execution order for these files. This setup allows for a straightforward extension of both SQL files and their execution order. Here is a sample of the JSON file’s contents at the time of this writing:" }, { "code": null, "e": 4636, "s": 4411, "text": "{ \"sequence\": [\"tables\", \"indexes\"], \"tables\": [ \"tables/vehicle.sql\", \"tables/signal.sql\", \"tables/move.sql\" ], \"indexes\": [ \"indexes/idx_signal_vehicle_day_ts.sql\", \"indexes/idx_move_vehicle_day.sql\" ]}" }, { "code": null, "e": 4928, "s": 4636, "text": "The “sequence” tag contains a list with the names of the JSON tags to execute in order, so in this case, we start by creating the tables and then the indexes. Each entry in the “tables” list is the relative path to the SQL script to execute. The base path is a default constructor parameter." }, { "code": null, "e": 5028, "s": 4928, "text": "With the database ready to use, we can start importing the data from the downloaded VED data files." }, { "code": null, "e": 5393, "s": 5028, "text": "The VED dynamic data lives in several manageable CSV files, so we can read them one at a time into a Pandas DataFrame and batch insert the data into the database. The Pandas library makes it quite easy to read CSV files, so we can use it to ease reading the data into memory. Here’s the code to do so (please refer to the second notebook in the GitHub repository):" }, { "code": null, "e": 5575, "s": 5393, "text": "for file in tqdm(files): df = read_data_frame(file) signals = [] for row in df.itertuples(index=False): signals.append(row) db.insert_signals(signals)" }, { "code": null, "e": 6120, "s": 5575, "text": "The function that inserts signals also uses a SQL script that is externally stored. To manage these external references, I created a class that loads the SQL scripts from storage on-demand and stores them in memory using a dictionary. This solution has the advantage of allowing you to change the SQL script without changing the Python code, and the memory caching means that you only take a small performance hit when loading the text file the first time. The next time will have a near-zero performance impact. Here is how the function looks:" }, { "code": null, "e": 6333, "s": 6120, "text": "def insert_vehicles(self, vehicles): conn = self.connect() cur = conn.cursor() sql = self.sql_cache.get(\"vehicle/insert\") cur.executemany(sql, vehicles) conn.commit() cur.close() conn.close()" }, { "code": null, "e": 6437, "s": 6333, "text": "As you might have guessed, the script’s key name is the file’s relative pathname without the extension." }, { "code": null, "e": 6560, "s": 6437, "text": "The same process applies to the static dataset, but this time using Panda’s functions to read Excel files into DataFrames." }, { "code": null, "e": 6772, "s": 6560, "text": "To illustrate how to explore the dataset using the SQLite interface, let us start by profiling the types of vehicles that generated data. We start by issuing a query and storing the result in a Pandas DataFrame:" }, { "code": null, "e": 6820, "s": 6772, "text": "vehicles = db.query_df(\"select * from vehicle\")" }, { "code": null, "e": 6937, "s": 6820, "text": "With all the vehicle data loaded into DataFrame, we can use the standard query methods to reveal the data structure:" }, { "code": null, "e": 6981, "s": 6937, "text": "vehicles.groupby(by='vehicle_type').count()" }, { "code": null, "e": 7025, "s": 6981, "text": "This command produces the following output:" }, { "code": null, "e": 7107, "s": 7025, "text": "We can also run quick inspections through the head and tail functions, like this:" }, { "code": null, "e": 7170, "s": 7107, "text": "db.head(\"select * from signal where vehicle_id = 10\", rows=20)" }, { "code": null, "e": 7625, "s": 7170, "text": "We can now proceed to some more sophisticated and insightful analyses using the simple tools described above. The presence of high-frequency location data in the dataset allows us to perform trajectory analyses to help characterize the vehicle behaviors. Detecting individual vehicle trips, between known stop locations, is usually a complicated process. Fortunately, we are in luck with this dataset, as the data anonymization process baked that for us." }, { "code": null, "e": 8458, "s": 7625, "text": "The data collection process for the VED ensured driver anonymization through a relatively simple three-step approach. This process turned out to be quite relevant to this study as it produced, as a by-product, a critical piece of information: individualized vehicle trajectories. To anonymize the driver information, the study authors applied techniques of Random Fogging, Geo-fencing, and Major Intersection Bounding. The random fogging method removes observed locations near the start and the end of the trip. The geo-fencing technique clips observations outside a bounding box defined around the city’s boundaries. The authors also clipped trips around the first and last significant intersections. Besides driver anonymization, these procedures also have the benefit of producing individual trajectories that are readily usable." }, { "code": null, "e": 8684, "s": 8458, "text": "After some cursory inspection, it is easy to realize that we can identify trips using two features only, namely the “day number” and the vehicle identifier. Let us first count the number of different individual vehicle trips." }, { "code": null, "e": 9003, "s": 8684, "text": "There are over thirty-two thousand trips in the dataset. Knowing how to identify vehicle trips uniquely, we can create a table containing summary information about each one. This table will prove its usefulness as an index into the signal table when iterating over trips and also help in aggregating trips per vehicle." }, { "code": null, "e": 9147, "s": 9003, "text": "The database startup code created an extra table named “move” to store each trip identifier. We can fill this table using a more complex query:" }, { "code": null, "e": 9659, "s": 9147, "text": "insert into move (vehicle_id, day_num, ts_ini, ts_end)select tt.vehicle_id, tt.day_num, ( select min(s1.time_stamp) from signal s1 where s1.day_num = tt.day_num and s1.vehicle_id = tt.vehicle_id ) as ts_ini, ( select max(s2.time_stamp) from signal s2 where s2.day_num = tt.day_num and s2.vehicle_id = tt.vehicle_id ) as ts_endfrom (select distinct vehicle_id, day_num from signal) tt;" }, { "code": null, "e": 9792, "s": 9659, "text": "You can try running this from the notebook using the “query” function or use a ready-made shortcut in the database interface object:" }, { "code": null, "e": 9812, "s": 9792, "text": "db.generate_moves()" }, { "code": null, "e": 10259, "s": 9812, "text": "This function illustrates the principle of decoupling the SQL script from the Python code. It starts by loading the text through the SQL script caching object and then executes it. The result is a table with all the unique trips for each vehicle. If we need to inspect the journeys of a single car, we can do so using simple queries with joins to the signal table to pull up the necessary detailed information. Let us illustrate this using a map." }, { "code": null, "e": 10386, "s": 10259, "text": "To extract the geographic information of an arbitrary trip, we can use the “move” table as a selector into the “signal” table." }, { "code": null, "e": 10612, "s": 10386, "text": "sql = \"\"\"select s.latitude, s.longitudefrom signal s inner join move m on m.vehicle_id = s.vehicle_id and m.day_num = s.day_numwhere m.move_id = 1\"\"\"locations = db.query(sql)" }, { "code": null, "e": 11074, "s": 10612, "text": "There are two things to note about the code above. First, I selected an arbitrary trip through its unique identifier. A more realistic scenario would involve selecting a vehicle and a period for a trip inspection. Second, this version of the query function returns a list of tuples with the same order as declared in the SQL text. This arrangement is quite convenient as we can immediately feed the query’s return to the map object of choice, a Folium PolyLine." }, { "code": null, "e": 11475, "s": 11074, "text": "tiles = \"cartodbpositron\"map = folium.Map(prefer_canvas=True)folium.TileLayer(tiles).add_to(map)color='#3388ff'opacity=0.7lats = [l[0] for l in locations]lons = [l[1] for l in locations]min_lat, max_lat = min(lats), max(lats)min_lon, max_lon = min(lons), max(lons)map.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]])polyline = PolyLine(locations, color=color, opacity=opacity)polyline.add_to(map)" }, { "code": null, "e": 11495, "s": 11475, "text": "Here is the result:" }, { "code": null, "e": 11845, "s": 11495, "text": "In this article, I showed how to use SQLite as a partial alternative to Pandas when it comes to managing medium-sized datasets. This approach can be especially practical when you are short in RAM. By mixing the familiar Pandas API with a bit of SQL, you can perform compelling analyses on datasets that would not comfortably fit in your main memory." }, { "code": null, "e": 12064, "s": 11845, "text": "I will follow up on this article with more in-depth analyses of the VED, as it is such an intriguing dataset, mixing geographic information with vehicle energy performance data. Stay tuned for the forthcoming articles." }, { "code": null, "e": 12200, "s": 12064, "text": "[1] G. S. Oh, David J. Leblanc, Huei Peng. Vehicle Energy Dataset (VED), A Large-scale Dataset for Vehicle Energy Consumption Research." } ]
How to print the first character of each word in a String in Java?
A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created. We can print the first character of each word in a string by using the below program public class FirstCharacterPrintTest { public static void main(String[] args) { String str = "Welcome To Tutorials Point"; char c[] = str.toCharArray(); System.out.println("The first character of each word: "); for (int i=0; i < c.length; i++) { // Logic to implement first character of each word in a string if(c[i] != ' ' && (i == 0 || c[i-1] == ' ')) { System.out.println(c[i]); } } } } The first character of each word: W T T P
[ { "code": null, "e": 1304, "s": 1062, "text": "A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created." }, { "code": null, "e": 1389, "s": 1304, "text": "We can print the first character of each word in a string by using the below program" }, { "code": null, "e": 1854, "s": 1389, "text": "public class FirstCharacterPrintTest {\n public static void main(String[] args) {\n String str = \"Welcome To Tutorials Point\";\n char c[] = str.toCharArray();\n System.out.println(\"The first character of each word: \");\n for (int i=0; i < c.length; i++) {\n // Logic to implement first character of each word in a string\n if(c[i] != ' ' && (i == 0 || c[i-1] == ' ')) {\n System.out.println(c[i]);\n }\n }\n }\n}" }, { "code": null, "e": 1896, "s": 1854, "text": "The first character of each word:\nW\nT\nT\nP" } ]
How to make a jQuery function call after “X” seconds?
To make a jQuery function call after “X” seconds, use the siteTimeout() method. On button click, set the following and fade out the element. Here, we have also set the milliseconds. This is the delay that would occur before fading an element: $("#button1").bind("click",function() { setTimeout(function() { $('#list').fadeOut();}, 4000); }); You can try to run the following code to learn how to work with setTimeout() method in jQuery: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#button1").bind("click",function() { setTimeout(function() { $('#list').fadeOut();}, 4000); }); }); </script> </head> <body> <input type="button" id="button1" value="Fade Out" /> <br/> <br/> <div id="list"> <ul> <li>India</li> <li>US</li> <li>UK</li> </ul> </div> <p>The above data will fade out after 4 seconds</p> </body> </html>
[ { "code": null, "e": 1142, "s": 1062, "text": "To make a jQuery function call after “X” seconds, use the siteTimeout() method." }, { "code": null, "e": 1305, "s": 1142, "text": "On button click, set the following and fade out the element. Here, we have also set the milliseconds. This is the delay that would occur before fading an element:" }, { "code": null, "e": 1413, "s": 1305, "text": "$(\"#button1\").bind(\"click\",function() {\n setTimeout(function() {\n $('#list').fadeOut();}, 4000);\n});" }, { "code": null, "e": 1508, "s": 1413, "text": "You can try to run the following code to learn how to work with setTimeout() method in jQuery:" }, { "code": null, "e": 1519, "s": 1508, "text": " Live Demo" }, { "code": null, "e": 2109, "s": 1519, "text": "<!DOCTYPE html>\n<html>\n<head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"#button1\").bind(\"click\",function() {\n setTimeout(function() {\n $('#list').fadeOut();}, 4000);\n });\n });\n </script>\n</head>\n<body>\n\n<input type=\"button\" id=\"button1\" value=\"Fade Out\" />\n<br/>\n<br/>\n<div id=\"list\">\n <ul>\n <li>India</li>\n <li>US</li>\n <li>UK</li>\n </ul>\n</div>\n<p>The above data will fade out after 4 seconds</p>\n</body>\n</html>" } ]
JDBC - Updating a Result Set Example
Following is the example, which makes use of the ResultSet.CONCUR_UPDATABLE and ResultSet.TYPE_SCROLL_INSENSITIVE described in the Result Set tutorial. This example would explain INSERT, UPDATE and DELETE operation on a table. It should be noted that tables you are working on should have Primary Key set properly. Drop the table and Create the table Employees again as follows − mysql> use TUTORIALSPOINT; mysql> drop table Employees; Query OK, 0 rows affected (0.08 sec) mysql> create table Employees -> ( -> id int primary key auto_increment, -> age int not null, -> first varchar (255), -> last varchar (255) -> ); Query OK, 0 rows affected (0.08 sec) mysql> Finally you create few records in Employee table as follows − mysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCExample { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT id, first, last, age FROM Employees"; public static void printResultSet(ResultSet rs) throws SQLException{ // Ensure we start with first row rs.beforeFirst(); while(rs.next()){ // Display values System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } System.out.println(); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery(QUERY); ) { System.out.println("List result set for reference...."); printResultSet(rs); // Loop through result set and add 5 in age // Move to Before first position so while-loop works properly rs.beforeFirst(); //STEP 7: Extract data from result set while(rs.next()){ // Retrieve by column name int newAge = rs.getInt("age") + 5; rs.updateDouble( "age", newAge ); rs.updateRow(); } System.out.println("List result set showing new ages..."); printResultSet(rs); // Insert a record into the table. // Move to insert row and add column data with updateXXX() System.out.println("Inserting a new record..."); rs.moveToInsertRow(); rs.updateString("first","John"); rs.updateString("last","Paul"); rs.updateInt("age",40); // Commit row rs.insertRow(); System.out.println("List result set showing new set..."); printResultSet(rs); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac JDBCExample.java C:\> When you run JDBCExample, it produces the following result − C:\>java JDBCExample List result set for reference.... ID: 1, Age: 18, First: Zara, Last: Ali ID: 2, Age: 25, First: Mahnaz, Last: Fatma ID: 3, Age: 30, First: Zaid, Last: Khan ID: 4, Age: 28, First: Sumit, Last: Mittal List result set showing new ages... ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal Inserting a new record... List result set showing new set... ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul C:\> 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": 2389, "s": 2162, "text": "Following is the example, which makes use of the ResultSet.CONCUR_UPDATABLE and ResultSet.TYPE_SCROLL_INSENSITIVE described in the Result Set tutorial. This example would explain INSERT, UPDATE and DELETE operation on a table." }, { "code": null, "e": 2477, "s": 2389, "text": "It should be noted that tables you are working on should have Primary Key set properly." }, { "code": null, "e": 2542, "s": 2477, "text": "Drop the table and Create the table Employees again as follows −" }, { "code": null, "e": 2849, "s": 2542, "text": "mysql> use TUTORIALSPOINT;\nmysql> drop table Employees;\nQuery OK, 0 rows affected (0.08 sec)\nmysql> create table Employees\n -> (\n -> id int primary key auto_increment,\n -> age int not null,\n -> first varchar (255),\n -> last varchar (255)\n -> );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>" }, { "code": null, "e": 2911, "s": 2849, "text": "Finally you create few records in Employee table as follows −" }, { "code": null, "e": 3375, "s": 2911, "text": "mysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees(AGE, FIRST, LAST) VALUES (28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql>" }, { "code": null, "e": 3462, "s": 3375, "text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −" }, { "code": null, "e": 5807, "s": 3462, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Employees\";\n\n public static void printResultSet(ResultSet rs) throws SQLException{\n // Ensure we start with first row\n rs.beforeFirst();\n while(rs.next()){\n // Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement(\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_UPDATABLE);\n ResultSet rs = stmt.executeQuery(QUERY);\n ) {\t\t\n\n System.out.println(\"List result set for reference....\");\n printResultSet(rs);\n\n // Loop through result set and add 5 in age\n // Move to Before first position so while-loop works properly\n rs.beforeFirst();\n //STEP 7: Extract data from result set\n while(rs.next()){\n // Retrieve by column name\n int newAge = rs.getInt(\"age\") + 5;\n rs.updateDouble( \"age\", newAge );\n rs.updateRow();\n }\n System.out.println(\"List result set showing new ages...\");\n printResultSet(rs);\n\n // Insert a record into the table.\n // Move to insert row and add column data with updateXXX()\n System.out.println(\"Inserting a new record...\");\n rs.moveToInsertRow();\n rs.updateString(\"first\",\"John\");\n rs.updateString(\"last\",\"Paul\");\n rs.updateInt(\"age\",40);\n // Commit row\n rs.insertRow();\n\n System.out.println(\"List result set showing new set...\");\n printResultSet(rs);\t\n\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 5857, "s": 5807, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 5889, "s": 5857, "text": "C:\\>javac JDBCExample.java\nC:\\>" }, { "code": null, "e": 5950, "s": 5889, "text": "When you run JDBCExample, it produces the following result −" }, { "code": null, "e": 6645, "s": 5950, "text": "C:\\>java JDBCExample\nList result set for reference....\nID: 1, Age: 18, First: Zara, Last: Ali\nID: 2, Age: 25, First: Mahnaz, Last: Fatma\nID: 3, Age: 30, First: Zaid, Last: Khan\nID: 4, Age: 28, First: Sumit, Last: Mittal\n\nList result set showing new ages...\nID: 1, Age: 23, First: Zara, Last: Ali\nID: 2, Age: 30, First: Mahnaz, Last: Fatma\nID: 3, Age: 35, First: Zaid, Last: Khan\nID: 4, Age: 33, First: Sumit, Last: Mittal\n\nInserting a new record...\nList result set showing new set...\nID: 1, Age: 23, First: Zara, Last: Ali\nID: 2, Age: 30, First: Mahnaz, Last: Fatma\nID: 3, Age: 35, First: Zaid, Last: Khan\nID: 4, Age: 33, First: Sumit, Last: Mittal\nID: 5, Age: 40, First: John, Last: Paul\nC:\\>\n" }, { "code": null, "e": 6678, "s": 6645, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6694, "s": 6678, "text": " Malhar Lathkar" }, { "code": null, "e": 6727, "s": 6694, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6743, "s": 6727, "text": " Malhar Lathkar" }, { "code": null, "e": 6778, "s": 6743, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6792, "s": 6778, "text": " Anadi Sharma" }, { "code": null, "e": 6826, "s": 6792, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6840, "s": 6826, "text": " Tushar Kale" }, { "code": null, "e": 6877, "s": 6840, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6892, "s": 6877, "text": " Monica Mittal" }, { "code": null, "e": 6925, "s": 6892, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6944, "s": 6925, "text": " Arnab Chakraborty" }, { "code": null, "e": 6951, "s": 6944, "text": " Print" }, { "code": null, "e": 6962, "s": 6951, "text": " Add Notes" } ]
Clustering Analysis in R using K-means | by Luiz Fonseca | Towards Data Science
The purpose of clustering analysis is to identify patterns in your data and create groups according to those patterns. Therefore, if two points have similar characteristics, that means they have the same pattern and consequently, they belong to the same group. By doing clustering analysis we should be able to check what features usually appear together and see what characterizes a group. In this post, we are going to perform a clustering analysis with multiple variables using the algorithm K-means. The intention is to find groups of mammals based on the composition of the species’ milk. The main points covered here are: A brief description of the data used in the clustering;An explanation of how the K-means algorithm works;How to decide the number of groups we want as input;Clustering validation using silhouette width.How to interpret the results and show them in a visualization. A brief description of the data used in the clustering; An explanation of how the K-means algorithm works; How to decide the number of groups we want as input; Clustering validation using silhouette width. How to interpret the results and show them in a visualization. The dataset used is part of the package cluster.datasets and contains 25 observations on the following 6 variables: name — a character vector for the name of the animals water — a numeric vector for the water content in the milk sample protein — a numeric vector for the amount of protein in the milk samplefat — a numeric vector for the fat content in the milk sample lactose — a numeric vector for the amount of lactose in the milk sample ash — a numeric vector for the amount of mineral in the milk sample Let’s take a look at a sample of the data library(cluster.datasets)data(all.mammals.milk.1956)head(all.mammals.milk.1956)## name water protein fat lactose ash## 1 Horse 90.1 2.6 1.0 6.9 0.35## 2 Orangutan 88.5 1.4 3.5 6.0 0.24## 3 Monkey 88.4 2.2 2.7 6.4 0.18## 4 Donkey 90.3 1.7 1.4 6.2 0.40## 5 Hippo 90.4 0.6 4.5 4.4 0.10## 6 Camel 87.7 3.5 3.4 4.8 0.71 The charts below show us the distribution for each variable. Each point represents a mammal species (25 in total). Each variable has different behavior and we could identify groups of mammals on each one individually, but that’s not the purpose here. All the variables will be used in the clustering on a linear scale. Sometimes, when the values (for each feature) are in a big range, for example from 0 up to 1 million, it’s interesting to use a logarithmic scale because on a log scale we would highlight bigger differences between the values and smaller differences would be considered less important. Since the values in our dataset vary between 0 and 100, we are going to use a linear scale, which considers differences between values equally important. The clustering algorithm that we are going to use is the K-means algorithm, which we can find in the package stats. The K-means algorithm accepts two parameters as input: The data; A K value, which is the number of groups that we want to create. Conceptually, the K-means behaves as follows: It chooses K centroids randomly;Matches each point in the data (in our case, each mammal) with the closest centroid in an n-dimensional space where n is the number of features used in the clustering (in our example, 5 features — water, protein, fat, lactose, ash). After this step, each point belongs to a group.Now, it recalculates the centroids as being the mean point (vector) of all other points in the group.It keeps repeating the steps 2 and 3 until either when the groups are stabilized, that is, when no points are reallocated to another centroid or when it reaches the maximum number of iterations (the stats library uses 10 as default). It chooses K centroids randomly; Matches each point in the data (in our case, each mammal) with the closest centroid in an n-dimensional space where n is the number of features used in the clustering (in our example, 5 features — water, protein, fat, lactose, ash). After this step, each point belongs to a group. Now, it recalculates the centroids as being the mean point (vector) of all other points in the group. It keeps repeating the steps 2 and 3 until either when the groups are stabilized, that is, when no points are reallocated to another centroid or when it reaches the maximum number of iterations (the stats library uses 10 as default). The bigger is the K you choose, the lower will be the variance within the groups in the clustering. If K is equal to the number of observations, then each point will be a group and the variance will be 0. It’s interesting to find a balance between the number of groups and their variance. A variance of a group means how different the members of the group are. The bigger is the variance, the bigger is the dissimilarity in a group. How do we choose the best value of K in order to find that balance? To answer that question, we are going to run K-means for an arbitrary K. Let’s pick 3. ## K-means clustering with 3 clusters of sizes 7, 2, 16## ## Cluster means:## water protein fat lactose ash## 1 69.47143 9.514286 16.28571 2.928571 1.311429## 2 45.65000 10.150000 38.45000 0.450000 0.690000## 3 86.06250 4.275000 4.17500 5.118750 0.635625## ## Clustering vector:## [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 1 1 1 2 2## ## Within cluster sum of squares by cluster:## [1] 300.1562 27.1912 377.2215## (between_SS / total_SS = 89.9 %)## ## Available components:## ## [1] "cluster" "centers" "totss" "withinss" ## [5] "tot.withinss" "betweenss" "size" "iter" ## [9] "ifault" The kmeans() function outputs the results of the clustering. We can see the centroid vectors (cluster means), the group in which each observation was allocated (clustering vector) and a percentage (89.9%) that represents the compactness of the clustering, that is, how similar are the members within the same group. If all the observations within a group were in the same exact point in the n-dimensional space, then we would achieve 100% of compactness. Since we know that, we will use that percentage to help us decide our K value, that is, a number of groups that will have satisfactory variance and compactness. The function below plots a chart showing the “within sum of squares” (withinss) by the number of groups (K value) chosen for several executions of the algorithm. The within sum of squares is a metric that shows how dissimilar are the members of a group., the greater is the sum, the greater is the dissimilarity within a group. By Analysing the chart from right to left, we can see that when the number of groups (K) reduces from 4 to 3 there is a big increase in the sum of squares, bigger than any other previous increase. That means that when it passes from 4 to 3 groups there is a reduction in the clustering compactness (by compactness, I mean the similarity within a group). Our goal, however, is not to achieve compactness of 100% — for that, we would just take each observation as a group. The main purpose is to find a fair number of groups that could explain satisfactorily a considerable part of the data. So, let’s choose K = 4 and run the K-means again. ## K-means clustering with 4 clusters of sizes 10, 2, 7, 6## ## Cluster means:## water protein fat lactose ash## 1 88.50000 2.570000 2.80000 5.680000 0.4850000## 2 45.65000 10.150000 38.45000 0.450000 0.6900000## 3 81.18571 7.428571 6.90000 4.014286 0.9314286## 4 68.33333 9.550000 17.41667 2.916667 1.3300000## ## Clustering vector:## [1] 1 1 1 1 1 1 1 3 3 3 3 1 1 3 1 3 3 4 4 4 4 4 4 2 2## ## Within cluster sum of squares by cluster:## [1] 59.41225 27.19120 63.53491 191.96100## (between_SS / total_SS = 95.1 %)## ## Available components:## ## [1] "cluster" "centers" "totss" "withinss" ## [5] "tot.withinss" "betweenss" "size" "iter" ## [9] "ifault" Using 3 groups (K = 3) we had 89.9% of well-grouped data. Using 4 groups (K = 4) that value raised to 95.1%, which is a good value for us. We may use the silhouette coefficient (silhouette width) to evaluate the goodness of our clustering. The silhouette coefficient is calculated as follows: For each observation i, it calculates the average dissimilarity between i and all the other points within the same cluster which i belongs. Let’s call this average dissimilarity “Di”.Now we do the same dissimilarity calculation between i and all the other clusters and get the lowest value among them. That is, we find the dissimilarity between i and the cluster that is closest to i right after its own cluster. Let’s call that value “Ci”The silhouette (Si) width is the difference between Ci and Di (Ci — Di) divided by the greatest of those two values (max(Di, Ci)).Si = (Ci — Di) / max(Di, Ci) For each observation i, it calculates the average dissimilarity between i and all the other points within the same cluster which i belongs. Let’s call this average dissimilarity “Di”. Now we do the same dissimilarity calculation between i and all the other clusters and get the lowest value among them. That is, we find the dissimilarity between i and the cluster that is closest to i right after its own cluster. Let’s call that value “Ci” The silhouette (Si) width is the difference between Ci and Di (Ci — Di) divided by the greatest of those two values (max(Di, Ci)).Si = (Ci — Di) / max(Di, Ci) So, the interpretation of the silhouette width is the following: Si > 0 means that the observation is well clustered. The closest it is to 1, the best it is clustered. Si < 0 means that the observation was placed in the wrong cluster. Si = 0 means that the observation is between two clusters. The silhouette plot below gives us evidence that our clustering using four groups is good because there’s no negative silhouette width and most of the values are bigger than 0.5. ## cluster size ave.sil.width## 1 1 10 0.65## 2 2 2 0.76## 3 3 7 0.58## 4 4 6 0.49 The following plot shows the final result of our clustering. The actual plot is interactive, but the image below is not. You can reproduce the plot using the code below. In the interactive plot, you may isolate the groups to better understand each one individually. The purpose of clustering analysis is to identify patterns in the data. As we can see in the plot above, observations within the same group tend to have similar characteristics. Let’s take the green group as an instance to evaluate. The two mammal species that belong to that group, namely seal and dolphin, they have the lowest percentage of water (44.9% and 46.4%); they both have around 10% of protein in their milk; they have the highest percentage of fat in the milk among all other species as well as the lowest percentage of lactose. This is the pattern found that puts seals and dolphins together in the same group. We can identify such patterns in the other groups as well. Thank you for reading. I hope it was a pleasurable and useful reading.
[ { "code": null, "e": 563, "s": 172, "text": "The purpose of clustering analysis is to identify patterns in your data and create groups according to those patterns. Therefore, if two points have similar characteristics, that means they have the same pattern and consequently, they belong to the same group. By doing clustering analysis we should be able to check what features usually appear together and see what characterizes a group." }, { "code": null, "e": 800, "s": 563, "text": "In this post, we are going to perform a clustering analysis with multiple variables using the algorithm K-means. The intention is to find groups of mammals based on the composition of the species’ milk. The main points covered here are:" }, { "code": null, "e": 1065, "s": 800, "text": "A brief description of the data used in the clustering;An explanation of how the K-means algorithm works;How to decide the number of groups we want as input;Clustering validation using silhouette width.How to interpret the results and show them in a visualization." }, { "code": null, "e": 1121, "s": 1065, "text": "A brief description of the data used in the clustering;" }, { "code": null, "e": 1172, "s": 1121, "text": "An explanation of how the K-means algorithm works;" }, { "code": null, "e": 1225, "s": 1172, "text": "How to decide the number of groups we want as input;" }, { "code": null, "e": 1271, "s": 1225, "text": "Clustering validation using silhouette width." }, { "code": null, "e": 1334, "s": 1271, "text": "How to interpret the results and show them in a visualization." }, { "code": null, "e": 1450, "s": 1334, "text": "The dataset used is part of the package cluster.datasets and contains 25 observations on the following 6 variables:" }, { "code": null, "e": 1843, "s": 1450, "text": "name — a character vector for the name of the animals water — a numeric vector for the water content in the milk sample protein — a numeric vector for the amount of protein in the milk samplefat — a numeric vector for the fat content in the milk sample lactose — a numeric vector for the amount of lactose in the milk sample ash — a numeric vector for the amount of mineral in the milk sample" }, { "code": null, "e": 1885, "s": 1843, "text": "Let’s take a look at a sample of the data" }, { "code": null, "e": 2280, "s": 1885, "text": "library(cluster.datasets)data(all.mammals.milk.1956)head(all.mammals.milk.1956)## name water protein fat lactose ash## 1 Horse 90.1 2.6 1.0 6.9 0.35## 2 Orangutan 88.5 1.4 3.5 6.0 0.24## 3 Monkey 88.4 2.2 2.7 6.4 0.18## 4 Donkey 90.3 1.7 1.4 6.2 0.40## 5 Hippo 90.4 0.6 4.5 4.4 0.10## 6 Camel 87.7 3.5 3.4 4.8 0.71" }, { "code": null, "e": 2395, "s": 2280, "text": "The charts below show us the distribution for each variable. Each point represents a mammal species (25 in total)." }, { "code": null, "e": 2531, "s": 2395, "text": "Each variable has different behavior and we could identify groups of mammals on each one individually, but that’s not the purpose here." }, { "code": null, "e": 3039, "s": 2531, "text": "All the variables will be used in the clustering on a linear scale. Sometimes, when the values (for each feature) are in a big range, for example from 0 up to 1 million, it’s interesting to use a logarithmic scale because on a log scale we would highlight bigger differences between the values and smaller differences would be considered less important. Since the values in our dataset vary between 0 and 100, we are going to use a linear scale, which considers differences between values equally important." }, { "code": null, "e": 3210, "s": 3039, "text": "The clustering algorithm that we are going to use is the K-means algorithm, which we can find in the package stats. The K-means algorithm accepts two parameters as input:" }, { "code": null, "e": 3220, "s": 3210, "text": "The data;" }, { "code": null, "e": 3285, "s": 3220, "text": "A K value, which is the number of groups that we want to create." }, { "code": null, "e": 3331, "s": 3285, "text": "Conceptually, the K-means behaves as follows:" }, { "code": null, "e": 3978, "s": 3331, "text": "It chooses K centroids randomly;Matches each point in the data (in our case, each mammal) with the closest centroid in an n-dimensional space where n is the number of features used in the clustering (in our example, 5 features — water, protein, fat, lactose, ash). After this step, each point belongs to a group.Now, it recalculates the centroids as being the mean point (vector) of all other points in the group.It keeps repeating the steps 2 and 3 until either when the groups are stabilized, that is, when no points are reallocated to another centroid or when it reaches the maximum number of iterations (the stats library uses 10 as default)." }, { "code": null, "e": 4011, "s": 3978, "text": "It chooses K centroids randomly;" }, { "code": null, "e": 4292, "s": 4011, "text": "Matches each point in the data (in our case, each mammal) with the closest centroid in an n-dimensional space where n is the number of features used in the clustering (in our example, 5 features — water, protein, fat, lactose, ash). After this step, each point belongs to a group." }, { "code": null, "e": 4394, "s": 4292, "text": "Now, it recalculates the centroids as being the mean point (vector) of all other points in the group." }, { "code": null, "e": 4628, "s": 4394, "text": "It keeps repeating the steps 2 and 3 until either when the groups are stabilized, that is, when no points are reallocated to another centroid or when it reaches the maximum number of iterations (the stats library uses 10 as default)." }, { "code": null, "e": 5061, "s": 4628, "text": "The bigger is the K you choose, the lower will be the variance within the groups in the clustering. If K is equal to the number of observations, then each point will be a group and the variance will be 0. It’s interesting to find a balance between the number of groups and their variance. A variance of a group means how different the members of the group are. The bigger is the variance, the bigger is the dissimilarity in a group." }, { "code": null, "e": 5129, "s": 5061, "text": "How do we choose the best value of K in order to find that balance?" }, { "code": null, "e": 5216, "s": 5129, "text": "To answer that question, we are going to run K-means for an arbitrary K. Let’s pick 3." }, { "code": null, "e": 5867, "s": 5216, "text": "## K-means clustering with 3 clusters of sizes 7, 2, 16## ## Cluster means:## water protein fat lactose ash## 1 69.47143 9.514286 16.28571 2.928571 1.311429## 2 45.65000 10.150000 38.45000 0.450000 0.690000## 3 86.06250 4.275000 4.17500 5.118750 0.635625## ## Clustering vector:## [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 1 1 1 2 2## ## Within cluster sum of squares by cluster:## [1] 300.1562 27.1912 377.2215## (between_SS / total_SS = 89.9 %)## ## Available components:## ## [1] \"cluster\" \"centers\" \"totss\" \"withinss\" ## [5] \"tot.withinss\" \"betweenss\" \"size\" \"iter\" ## [9] \"ifault\"" }, { "code": null, "e": 6322, "s": 5867, "text": "The kmeans() function outputs the results of the clustering. We can see the centroid vectors (cluster means), the group in which each observation was allocated (clustering vector) and a percentage (89.9%) that represents the compactness of the clustering, that is, how similar are the members within the same group. If all the observations within a group were in the same exact point in the n-dimensional space, then we would achieve 100% of compactness." }, { "code": null, "e": 6483, "s": 6322, "text": "Since we know that, we will use that percentage to help us decide our K value, that is, a number of groups that will have satisfactory variance and compactness." }, { "code": null, "e": 6811, "s": 6483, "text": "The function below plots a chart showing the “within sum of squares” (withinss) by the number of groups (K value) chosen for several executions of the algorithm. The within sum of squares is a metric that shows how dissimilar are the members of a group., the greater is the sum, the greater is the dissimilarity within a group." }, { "code": null, "e": 7401, "s": 6811, "text": "By Analysing the chart from right to left, we can see that when the number of groups (K) reduces from 4 to 3 there is a big increase in the sum of squares, bigger than any other previous increase. That means that when it passes from 4 to 3 groups there is a reduction in the clustering compactness (by compactness, I mean the similarity within a group). Our goal, however, is not to achieve compactness of 100% — for that, we would just take each observation as a group. The main purpose is to find a fair number of groups that could explain satisfactorily a considerable part of the data." }, { "code": null, "e": 7451, "s": 7401, "text": "So, let’s choose K = 4 and run the K-means again." }, { "code": null, "e": 8173, "s": 7451, "text": "## K-means clustering with 4 clusters of sizes 10, 2, 7, 6## ## Cluster means:## water protein fat lactose ash## 1 88.50000 2.570000 2.80000 5.680000 0.4850000## 2 45.65000 10.150000 38.45000 0.450000 0.6900000## 3 81.18571 7.428571 6.90000 4.014286 0.9314286## 4 68.33333 9.550000 17.41667 2.916667 1.3300000## ## Clustering vector:## [1] 1 1 1 1 1 1 1 3 3 3 3 1 1 3 1 3 3 4 4 4 4 4 4 2 2## ## Within cluster sum of squares by cluster:## [1] 59.41225 27.19120 63.53491 191.96100## (between_SS / total_SS = 95.1 %)## ## Available components:## ## [1] \"cluster\" \"centers\" \"totss\" \"withinss\" ## [5] \"tot.withinss\" \"betweenss\" \"size\" \"iter\" ## [9] \"ifault\"" }, { "code": null, "e": 8312, "s": 8173, "text": "Using 3 groups (K = 3) we had 89.9% of well-grouped data. Using 4 groups (K = 4) that value raised to 95.1%, which is a good value for us." }, { "code": null, "e": 8413, "s": 8312, "text": "We may use the silhouette coefficient (silhouette width) to evaluate the goodness of our clustering." }, { "code": null, "e": 8466, "s": 8413, "text": "The silhouette coefficient is calculated as follows:" }, { "code": null, "e": 9064, "s": 8466, "text": "For each observation i, it calculates the average dissimilarity between i and all the other points within the same cluster which i belongs. Let’s call this average dissimilarity “Di”.Now we do the same dissimilarity calculation between i and all the other clusters and get the lowest value among them. That is, we find the dissimilarity between i and the cluster that is closest to i right after its own cluster. Let’s call that value “Ci”The silhouette (Si) width is the difference between Ci and Di (Ci — Di) divided by the greatest of those two values (max(Di, Ci)).Si = (Ci — Di) / max(Di, Ci)" }, { "code": null, "e": 9248, "s": 9064, "text": "For each observation i, it calculates the average dissimilarity between i and all the other points within the same cluster which i belongs. Let’s call this average dissimilarity “Di”." }, { "code": null, "e": 9505, "s": 9248, "text": "Now we do the same dissimilarity calculation between i and all the other clusters and get the lowest value among them. That is, we find the dissimilarity between i and the cluster that is closest to i right after its own cluster. Let’s call that value “Ci”" }, { "code": null, "e": 9664, "s": 9505, "text": "The silhouette (Si) width is the difference between Ci and Di (Ci — Di) divided by the greatest of those two values (max(Di, Ci)).Si = (Ci — Di) / max(Di, Ci)" }, { "code": null, "e": 9729, "s": 9664, "text": "So, the interpretation of the silhouette width is the following:" }, { "code": null, "e": 9832, "s": 9729, "text": "Si > 0 means that the observation is well clustered. The closest it is to 1, the best it is clustered." }, { "code": null, "e": 9899, "s": 9832, "text": "Si < 0 means that the observation was placed in the wrong cluster." }, { "code": null, "e": 9958, "s": 9899, "text": "Si = 0 means that the observation is between two clusters." }, { "code": null, "e": 10137, "s": 9958, "text": "The silhouette plot below gives us evidence that our clustering using four groups is good because there’s no negative silhouette width and most of the values are bigger than 0.5." }, { "code": null, "e": 10293, "s": 10137, "text": "## cluster size ave.sil.width## 1 1 10 0.65## 2 2 2 0.76## 3 3 7 0.58## 4 4 6 0.49" }, { "code": null, "e": 10559, "s": 10293, "text": "The following plot shows the final result of our clustering. The actual plot is interactive, but the image below is not. You can reproduce the plot using the code below. In the interactive plot, you may isolate the groups to better understand each one individually." }, { "code": null, "e": 10737, "s": 10559, "text": "The purpose of clustering analysis is to identify patterns in the data. As we can see in the plot above, observations within the same group tend to have similar characteristics." }, { "code": null, "e": 11242, "s": 10737, "text": "Let’s take the green group as an instance to evaluate. The two mammal species that belong to that group, namely seal and dolphin, they have the lowest percentage of water (44.9% and 46.4%); they both have around 10% of protein in their milk; they have the highest percentage of fat in the milk among all other species as well as the lowest percentage of lactose. This is the pattern found that puts seals and dolphins together in the same group. We can identify such patterns in the other groups as well." } ]
Swift - Closures
Closures in Swift 4 are similar to that of self-contained functions organized as blocks and called anywhere like C and Objective C languages. Constants and variable references defined inside the functions are captured and stored in closures. Functions are considered as special cases of closures and it takes the following three forms − Closure expressions in Swift 4 language follow crisp, optimization, and lightweight syntax styles which includes. Inferring parameter and return value types from context. Implicit returns from single-expression closures. Shorthand argument names and Trailing closure syntax Following is a generic syntax to define closure which accepts parameters and returns a data type − { (parameters) −> return type in statements } Following is a simple example − let studname = { print("Welcome to Swift Closures") } studname() When we run the above program using playground, we get the following result − Welcome to Swift Closures The following closure accepts two parameters and returns a Bool value − { (Int, Int) −> Bool in Statement1 Statement 2 --- Statement n } Following is a simple example − let divide = { (val1: Int, val2: Int) -> Int in return val1 / val2 } let result = divide(200, 20) print (result) When we run the above program using playground, we get the following result − 10 Nested functions provide a convenient way of naming and defining blocks of code. Instead of representing the whole function declaration and name constructs are used to denote shorter functions. Representing the function in a clear brief statement with focused syntax is achieved through closure expressions. Sorting a string is achieved by the Swift 4s key reserved function "sorted" which is already available in the standard library. The function will sort the given strings in the ascending order and returns the elements in a new array with same size and data type mentioned in the old array. The old array remains the same. Two arguments are represented inside the sorted function − Values of Known type represented as arrays. Values of Known type represented as arrays. Array contents (Int, Int) and returns a Boolean value (Bool) if the array is sorted properly it will return true value otherwise it will return false. Array contents (Int, Int) and returns a Boolean value (Bool) if the array is sorted properly it will return true value otherwise it will return false. A normal function with input string is written and passed to the sorted function to get the strings sorted to new array which is shown below − func ascend(s1: String, s2: String) -> Bool { return s1 > s2 } let stringcmp = ascend(s1: "Swift 4", s2: "great") print (stringcmp) When we run above program using playground, we get following result − true The initial array to be sorted for icecream is given as "Swift 4" and "great". Function to sort the array is declared as string datatype and its return type is mentioned as Boolean. Both the strings are compared and sorted in ascending order and stored in a new array. If the sorting is performed successful the function will return a true value else it will return false. Closure expression syntax uses − constant parameters, variable parameters, and inout parameters. Closure expression did not support default values. Variadic parameters and Tuples can also be used as parameter types and return types. let sum = { (no1: Int, no2: Int) -> Int in return no1 + no2 } let digits = sum(10, 20) print(digits) When we run the above program using playground, we get the following result − 30 The parameters and return type declarations mentioned in the function statement can also be represented by the inline closure expression function with 'in' keyword. Once declaring parameter and return types 'in' keyword is used to denote that the body of the closure. Here, the function type of the sorted function's second argument makes it clear that a Bool value must be returned by the closure. Because the closure's body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted. To return a Single expression statement in expression closures 'return' keyword is omitted in its declaration part. var count:[Int] = [5, 10, -6, 75, 20] let descending = count.sorted(by: { n1, n2 in n1 > n2 }) let ascending = count.sorted(by: { n1, n2 in n1 < n2 }) print(descending) print(ascending) When we run the above program using playground, we get the following result − [75, 20, 10, 5, -6] [-6, 5, 10, 20, 75] The statement itself clearly defines that when string1 is greater than string 2 return true otherwise false hence return statement is omitted here. Consider the addition of two numbers. We know that addition will return the integer datatype. Hence known type closures are declared as − let sub = { (no1: Int, no2: Int) -> Int in return no1 - no2 } let digits = sub(10, 20) print(digits) When we run the above program using playground, we get the following result − -10 Swift 4 automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure's arguments by the names $0, $1, $2, and so on. var shorthand: (String, String) -> String shorthand = { $1 } print(shorthand("100", "200")) Here, $0 and $1 refer to the closure's first and second String arguments. When we run the above program using playground, we get the following result − 200 Swift 4 facilitates the user to represent Inline closures as shorthand argument names by representing $0, $1, $2 --- $n. Closures argument list is omitted in definition section when we represent shorthand argument names inside closure expressions. Based on the function type the shorthand argument names will be derived. Since the shorthand argument is defined in expression body the 'in' keyword is omitted. Swift 4 provides an easy way to access the members by just providing operator functions as closures. In the previous examples keyword 'Bool' is used to return either 'true' when the strings are equal otherwise it returns 'false'. The expression is made even simpler by operator function in closure as − let numb = [98, -20, -30, 42, 18, 35] var sortedNumbers = numb.sorted ({ (left: Int, right: Int) -> Bool in return left < right }) let asc = numb.sorted(<) print(asc) When we run the above program using playground, we get the following result − [-30, -20, 18, 35, 42, 98] Passing the function's final argument to a closure expression is declared with the help of 'Trailing Closures'. It is written outside the function () with {}. Its usage is needed when it is not possible to write the function inline on a single line. reversed = sorted(names) { $0 > $1} where {$0 > $1} are represented as trailing closures declared outside (names). import Foundation var letters = ["North", "East", "West", "South"] let twoletters = letters.map({ (state: String) -> String in return state.substringToIndex(advance(state.startIndex, 2)).uppercaseString }) let stletters = letters.map() { $0.substringToIndex(advance($0.startIndex, 2)).uppercaseString } print(stletters) When we run the above program using playground, we get the following result − [NO, EA, WE, SO] In Swift 4, capturing constants and variables values is done with the help of closures. It further refers and modify the values for those constants and variables inside the closure body even though the variables no longer exists. Capturing constant and variable values is achieved by using nested function by writing function with in the body of other function. A nested function captures − Outer function arguments. Capture constants and variables defined within the Outer function. In Swift 4, when a constant or a variable is declared inside a function, reference to that variables are also automatically created by the closure. It also provides the facility to refer more than two variables as the same closure as follows − let decrem = calcDecrement(forDecrement: 18) decrem() Here oneDecrement and Decrement variables will both point the same memory block as closure reference. func calcDecrement(forDecrement total: Int) -> () -> Int { var overallDecrement = 100 func decrementer() -> Int { overallDecrement -= total print(overallDecrement) return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement: 18) decrem() decrem() decrem() When we run the above program using playground, we get the following result − 82 64 46 When each and every time the outer function calcDecrement is called it invokes the decrementer() function and decrements the value by 18 and returns the result with the help of outer function calcDecrement. Here calcDecrement acts as a closure. Even though the function decrementer() does not have any arguments closure by default refers to variables 'overallDecrement' and 'total' by capturing its existing values. The copy of the values for the specified variables are stored with the new decrementer() function. Swift 4 handles memory management functions by allocating and deallocating memory spaces when the variables are not in use. 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2590, "s": 2253, "text": "Closures in Swift 4 are similar to that of self-contained functions organized as blocks and called anywhere like C and Objective C languages. Constants and variable references defined inside the functions are captured and stored in closures. Functions are considered as special cases of closures and it takes the following three forms −" }, { "code": null, "e": 2704, "s": 2590, "text": "Closure expressions in Swift 4 language follow crisp, optimization, and lightweight syntax styles which includes." }, { "code": null, "e": 2761, "s": 2704, "text": "Inferring parameter and return value types from context." }, { "code": null, "e": 2811, "s": 2761, "text": "Implicit returns from single-expression closures." }, { "code": null, "e": 2840, "s": 2811, "text": "Shorthand argument names and" }, { "code": null, "e": 2864, "s": 2840, "text": "Trailing closure syntax" }, { "code": null, "e": 2963, "s": 2864, "text": "Following is a generic syntax to define closure which accepts parameters and returns a data type −" }, { "code": null, "e": 3016, "s": 2963, "text": "{\n (parameters) −> return type in\n statements\n}\n" }, { "code": null, "e": 3048, "s": 3016, "text": "Following is a simple example −" }, { "code": null, "e": 3113, "s": 3048, "text": "let studname = { print(\"Welcome to Swift Closures\") }\nstudname()" }, { "code": null, "e": 3191, "s": 3113, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 3218, "s": 3191, "text": "Welcome to Swift Closures\n" }, { "code": null, "e": 3290, "s": 3218, "text": "The following closure accepts two parameters and returns a Bool value −" }, { "code": null, "e": 3376, "s": 3290, "text": "{ \n (Int, Int) −> Bool in\n Statement1\n Statement 2\n ---\n Statement n\n}\n" }, { "code": null, "e": 3408, "s": 3376, "text": "Following is a simple example −" }, { "code": null, "e": 3530, "s": 3408, "text": "let divide = {\n (val1: Int, val2: Int) -> Int in \n return val1 / val2 \n}\n\nlet result = divide(200, 20)\nprint (result)" }, { "code": null, "e": 3608, "s": 3530, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 3612, "s": 3608, "text": "10\n" }, { "code": null, "e": 3920, "s": 3612, "text": "Nested functions provide a convenient way of naming and defining blocks of code. Instead of representing the whole function declaration and name constructs are used to denote shorter functions. Representing the function in a clear brief statement with focused syntax is achieved through closure expressions." }, { "code": null, "e": 4241, "s": 3920, "text": "Sorting a string is achieved by the Swift 4s key reserved function \"sorted\" which is already available in the standard library. The function will sort the given strings in the ascending order and returns the elements in a new array with same size and data type mentioned in the old array. The old array remains the same." }, { "code": null, "e": 4300, "s": 4241, "text": "Two arguments are represented inside the sorted function −" }, { "code": null, "e": 4344, "s": 4300, "text": "Values of Known type represented as arrays." }, { "code": null, "e": 4388, "s": 4344, "text": "Values of Known type represented as arrays." }, { "code": null, "e": 4539, "s": 4388, "text": "Array contents (Int, Int) and returns a Boolean value (Bool) if the array is sorted properly it will return true value otherwise it will return false." }, { "code": null, "e": 4690, "s": 4539, "text": "Array contents (Int, Int) and returns a Boolean value (Bool) if the array is sorted properly it will return true value otherwise it will return false." }, { "code": null, "e": 4833, "s": 4690, "text": "A normal function with input string is written and passed to the sorted function to get the strings sorted to new array which is shown below −" }, { "code": null, "e": 4969, "s": 4833, "text": "func ascend(s1: String, s2: String) -> Bool {\n return s1 > s2\n}\n\nlet stringcmp = ascend(s1: \"Swift 4\", s2: \"great\")\nprint (stringcmp)" }, { "code": null, "e": 5039, "s": 4969, "text": "When we run above program using playground, we get following result −" }, { "code": null, "e": 5045, "s": 5039, "text": "true\n" }, { "code": null, "e": 5418, "s": 5045, "text": "The initial array to be sorted for icecream is given as \"Swift 4\" and \"great\". Function to sort the array is declared as string datatype and its return type is mentioned as Boolean. Both the strings are compared and sorted in ascending order and stored in a new array. If the sorting is performed successful the function will return a true value else it will return false." }, { "code": null, "e": 5451, "s": 5418, "text": "Closure expression syntax uses −" }, { "code": null, "e": 5472, "s": 5451, "text": "constant parameters," }, { "code": null, "e": 5497, "s": 5472, "text": "variable parameters, and" }, { "code": null, "e": 5515, "s": 5497, "text": "inout parameters." }, { "code": null, "e": 5651, "s": 5515, "text": "Closure expression did not support default values. Variadic parameters and Tuples can also be used as parameter types and return types." }, { "code": null, "e": 5761, "s": 5651, "text": "let sum = {\n (no1: Int, no2: Int) -> Int in \n return no1 + no2 \n}\n\nlet digits = sum(10, 20)\nprint(digits)" }, { "code": null, "e": 5839, "s": 5761, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 5843, "s": 5839, "text": "30\n" }, { "code": null, "e": 6111, "s": 5843, "text": "The parameters and return type declarations mentioned in the function statement can also be represented by the inline closure expression function with 'in' keyword. Once declaring parameter and return types 'in' keyword is used to denote that the body of the closure." }, { "code": null, "e": 6397, "s": 6111, "text": "Here, the function type of the sorted function's second argument makes it clear that a Bool value must be returned by the closure. Because the closure's body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted." }, { "code": null, "e": 6513, "s": 6397, "text": "To return a Single expression statement in expression closures 'return' keyword is omitted in its declaration part." }, { "code": null, "e": 6700, "s": 6513, "text": "var count:[Int] = [5, 10, -6, 75, 20]\nlet descending = count.sorted(by: { n1, n2 in n1 > n2 })\nlet ascending = count.sorted(by: { n1, n2 in n1 < n2 })\n\nprint(descending)\nprint(ascending)" }, { "code": null, "e": 6778, "s": 6700, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 6819, "s": 6778, "text": "[75, 20, 10, 5, -6]\n[-6, 5, 10, 20, 75]\n" }, { "code": null, "e": 6967, "s": 6819, "text": "The statement itself clearly defines that when string1 is greater than string 2 return true otherwise false hence return statement is omitted here." }, { "code": null, "e": 7105, "s": 6967, "text": "Consider the addition of two numbers. We know that addition will return the integer datatype. Hence known type closures are declared as −" }, { "code": null, "e": 7215, "s": 7105, "text": "let sub = {\n (no1: Int, no2: Int) -> Int in \n return no1 - no2 \n}\n\nlet digits = sub(10, 20)\nprint(digits)" }, { "code": null, "e": 7293, "s": 7215, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 7298, "s": 7293, "text": "-10\n" }, { "code": null, "e": 7478, "s": 7298, "text": "Swift 4 automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure's arguments by the names $0, $1, $2, and so on." }, { "code": null, "e": 7570, "s": 7478, "text": "var shorthand: (String, String) -> String\nshorthand = { $1 }\nprint(shorthand(\"100\", \"200\"))" }, { "code": null, "e": 7644, "s": 7570, "text": "Here, $0 and $1 refer to the closure's first and second String arguments." }, { "code": null, "e": 7722, "s": 7644, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 7727, "s": 7722, "text": "200\n" }, { "code": null, "e": 7848, "s": 7727, "text": "Swift 4 facilitates the user to represent Inline closures as shorthand argument names by representing $0, $1, $2 --- $n." }, { "code": null, "e": 8136, "s": 7848, "text": "Closures argument list is omitted in definition section when we represent shorthand argument names inside closure expressions. Based on the function type the shorthand argument names will be derived. Since the shorthand argument is defined in expression body the 'in' keyword is omitted." }, { "code": null, "e": 8366, "s": 8136, "text": "Swift 4 provides an easy way to access the members by just providing operator functions as closures. In the previous examples keyword 'Bool' is used to return either 'true' when the strings are equal otherwise it returns 'false'." }, { "code": null, "e": 8439, "s": 8366, "text": "The expression is made even simpler by operator function in closure as −" }, { "code": null, "e": 8613, "s": 8439, "text": "let numb = [98, -20, -30, 42, 18, 35]\nvar sortedNumbers = numb.sorted ({\n (left: Int, right: Int) -> Bool in\n return left < right\n})\n\nlet asc = numb.sorted(<)\nprint(asc)" }, { "code": null, "e": 8691, "s": 8613, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 8719, "s": 8691, "text": "[-30, -20, 18, 35, 42, 98]\n" }, { "code": null, "e": 8969, "s": 8719, "text": "Passing the function's final argument to a closure expression is declared with the help of 'Trailing Closures'. It is written outside the function () with {}. Its usage is needed when it is not possible to write the function inline on a single line." }, { "code": null, "e": 9006, "s": 8969, "text": "reversed = sorted(names) { $0 > $1}\n" }, { "code": null, "e": 9085, "s": 9006, "text": "where {$0 > $1} are represented as trailing closures declared outside (names)." }, { "code": null, "e": 9419, "s": 9085, "text": "import Foundation\nvar letters = [\"North\", \"East\", \"West\", \"South\"]\n\nlet twoletters = letters.map({ \n (state: String) -> String in\n return state.substringToIndex(advance(state.startIndex, 2)).uppercaseString\n})\n\nlet stletters = letters.map() { \n $0.substringToIndex(advance($0.startIndex, 2)).uppercaseString \n}\nprint(stletters)" }, { "code": null, "e": 9497, "s": 9419, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 9515, "s": 9497, "text": "[NO, EA, WE, SO]\n" }, { "code": null, "e": 9745, "s": 9515, "text": "In Swift 4, capturing constants and variables values is done with the help of closures. It further refers and modify the values for those constants and variables inside the closure body even though the variables no longer exists." }, { "code": null, "e": 9877, "s": 9745, "text": "Capturing constant and variable values is achieved by using nested function by writing function with in the body of other function." }, { "code": null, "e": 9906, "s": 9877, "text": "A nested function captures −" }, { "code": null, "e": 9932, "s": 9906, "text": "Outer function arguments." }, { "code": null, "e": 9999, "s": 9932, "text": "Capture constants and variables defined within the Outer function." }, { "code": null, "e": 10243, "s": 9999, "text": "In Swift 4, when a constant or a variable is declared inside a function, reference to that variables are also automatically created by the closure. It also provides the facility to refer more than two variables as the same closure as follows −" }, { "code": null, "e": 10298, "s": 10243, "text": "let decrem = calcDecrement(forDecrement: 18)\ndecrem()\n" }, { "code": null, "e": 10400, "s": 10298, "text": "Here oneDecrement and Decrement variables will both point the same memory block as closure reference." }, { "code": null, "e": 10714, "s": 10400, "text": "func calcDecrement(forDecrement total: Int) -> () -> Int {\n var overallDecrement = 100\n func decrementer() -> Int {\n overallDecrement -= total\n print(overallDecrement)\n return overallDecrement\n }\n return decrementer\n}\n\nlet decrem = calcDecrement(forDecrement: 18)\ndecrem()\ndecrem()\ndecrem()" }, { "code": null, "e": 10792, "s": 10714, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 10802, "s": 10792, "text": "82\n64\n46\n" }, { "code": null, "e": 11047, "s": 10802, "text": "When each and every time the outer function calcDecrement is called it invokes the decrementer() function and decrements the value by 18 and returns the result with the help of outer function calcDecrement. Here calcDecrement acts as a closure." }, { "code": null, "e": 11441, "s": 11047, "text": "Even though the function decrementer() does not have any arguments closure by default refers to variables 'overallDecrement' and 'total' by capturing its existing values. The copy of the values for the specified variables are stored with the new decrementer() function. Swift 4 handles memory management functions by allocating and deallocating memory spaces when the variables are not in use." }, { "code": null, "e": 11474, "s": 11441, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 11489, "s": 11474, "text": " Ashish Sharma" }, { "code": null, "e": 11522, "s": 11489, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 11541, "s": 11522, "text": " Three Millennials" }, { "code": null, "e": 11573, "s": 11541, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 11592, "s": 11573, "text": " Three Millennials" }, { "code": null, "e": 11625, "s": 11592, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 11642, "s": 11625, "text": " Frahaan Hussain" }, { "code": null, "e": 11674, "s": 11642, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 11694, "s": 11674, "text": " Devasena Rajendran" }, { "code": null, "e": 11729, "s": 11694, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11746, "s": 11729, "text": " Grant Klimaytys" }, { "code": null, "e": 11753, "s": 11746, "text": " Print" }, { "code": null, "e": 11764, "s": 11753, "text": " Add Notes" } ]
How to validate a URL using regular expression in C#?
To validate, you need to check for the protocols. http https With that, you need to check for .com, .in, .org, etc. For this, use the following regular expression − (http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)? The following is the code − Live Demo using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "https://example.com"; Console.WriteLine("Matching URL..."); showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?"); Console.ReadKey(); } } } Matching URL... The Expression: ^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)? https://example.com
[ { "code": null, "e": 1112, "s": 1062, "text": "To validate, you need to check for the protocols." }, { "code": null, "e": 1123, "s": 1112, "text": "http\nhttps" }, { "code": null, "e": 1178, "s": 1123, "text": "With that, you need to check for .com, .in, .org, etc." }, { "code": null, "e": 1227, "s": 1178, "text": "For this, use the following regular expression −" }, { "code": null, "e": 1292, "s": 1227, "text": "(http|http(s)?://)?([\\w-]+\\.)+[\\w-]+[.com|.in|.org]+(\\[\\?%&=]*)?" }, { "code": null, "e": 1320, "s": 1292, "text": "The following is the code −" }, { "code": null, "e": 1331, "s": 1320, "text": " Live Demo" }, { "code": null, "e": 1965, "s": 1331, "text": "using System;\nusing System.Text.RegularExpressions;\nnamespace RegExApplication {\n class Program {\n private static void showMatch(string text, string expr) {\n Console.WriteLine(\"The Expression: \" + expr);\n MatchCollection mc = Regex.Matches(text, expr);\n foreach (Match m in mc) {\n Console.WriteLine(m);\n }\n }\n static void Main(string[] args) {\n string str = \"https://example.com\";\n Console.WriteLine(\"Matching URL...\");\n showMatch(str, @\"^(http|http(s)?://)?([\\w-]+\\.)+[\\w-]+[.com|.in|.org]+(\\[\\?%&=]*)?\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2083, "s": 1965, "text": "Matching URL...\nThe Expression: ^(http|http(s)?://)?([\\w-]+\\.)+[\\w-]+[.com|.in|.org]+(\\[\\?%&=]*)?\nhttps://example.com" } ]
Parse TradingView Stock Recommendations in Seconds! | Towards Data Science
In one of my earlier articles, we went over how to parse the top analyst recommendations from Yahoo Finance for any stock. While they offered validation as to where a stock might move in the future, they were only updated once a month and did not offer any info as to the rationale behind the rating. Luckily, since then, I’ve stumbled upon the wonderful site TradingView. If you aren’t familiar with the site, one of the features they offer is real-time recommendations for as short as 1 minute ahead or for as long as 1 month ahead. These recommendations are purely based on Technical Indicators including Moving Averages, Oscillators, and Pivots and you can see the calculations directly on the page! So instead of visiting the site each time I wanted a recommendation, I created this simple parser with less than 50 lines of code that can do just that. Before I get into the coding aspect, I want to quickly touch upon what and where these recommendations are on TradingView. If you go over to this page, you will see something similar to the image I included below. The page includes key statistics such as Price to Earnings ratio, Earnings Per Share, Market Cap, Dividend information, and much more. You can even click Overview to get a comprehensive table full of ratios as well as an interactive chart, and recent news. However, this isn’t where the recommendations are located. If you continue scrolling down on the Technicals page, there will be multiple charts like the one below, outlining the recommendation and the statistics for the reasoning behind the signal. The recommendations range from strong buy to strong sell and as you can see in the second image, they are entirely dependent on the technical indicator signals. The algorithm we will be building soon parses the number of buy signals, neutral signals, sell signals, and the overall recommendation. The GitHub gist below contains all the code! In case you do not have Selenium or Pandas installed, you can visit their respective links and download them using pip in your terminal! We will also need a chromedriver (the simulated chrome browser Selenium controls) and to download it using Python you can use the webdriver-manager package also found in PyPi. Additionally, you can use any IDE or Text Editor that supports Python as long as you have the necessary dependencies installed. I personally would recommend downloading either Visual Studio Code or Spyder through Anaconda. Now that everything should be installed on your machine and you have an idea for what we will be scraping, let’s get into the code! First, we have to import the dependencies we will need for the rest of the program. In this case, we will need the built-in time module, Pandas, and Selenium. The time module will allow us to make the program sleep for a number of seconds just so the simulated browser can fully load. Pandas will allow us to create a DataFrame with the data we collect. Finally, we will need selenium so we can create/control a browser window and scrape the JavaScript-rendered information. Next, we can create two variables, one for the ticker and the other for the interval we are particularly scraping for. The interval can be any of the ones I included in the code fence below. #===================================================================# Intervals: # 1m for 1 minute# 15m for 15 minutes# 1h for 1 hour# 4h for 4 hours# 1D for 1 day# 1W for 1 week# 1M for 1 month# ================================================================== After we include the imports and parameters, we can set up the chromedriver. The Options class will allow us to add arguments such as headless to customize the simulated browser. Adding headless tells the browser to not pop up each time you run the program. We can set the executable path to the path where you downloaded the chromedriver earlier. In this case, I downloaded it directly into my directory but you do not have to. We can add our scraping script inside a try/except block to catch errors from breaking our program. First, we must open up the browser using webdriver.get(URL), refresh to load all aspects of the page properly, and then add time.sleep(1) to slow down the program by one second until the browser is completely rendered. Using the .find_by_class_name method in selenium.webdriver, we can pinpoint the exact portions we want to scrape. For example, only the recommendation has the following class “speedometerSignal-pyzN — tL.” We can retrieve these class names by inspect element in Chrome DevTools. Top open up DevTools, you can right-click on the section you’d like to parse and then press “inspect” to get a similar result to the image below! We can retrieve the “Buy” using the method .get_attribute(‘innerHTML’) which will store the text that is inside the HTML tag. Similarly, we can retrieve the number of buy, neutral, and sell signals by finding a class name that is similar between all of them and then using the method .find_elements_by_class_name. Since this time we are calling for elements, not an element, this method will return a list of HTML tags that have the class name we specify. Lastly, we can append all of the signals to a list, and using the .from_records method, we can turn a tuple of our data and a list of columns into a DataFrame. Finally, we can clean it up by adding a column for the ticker, setting that column as the index, and transposing (rotating) the DataFrame for our final product. Now within seconds, you should get a similar output to the image above. I hope this algorithm will prove useful to you in the future. Thank you so much for reading! Disclaimer: The material in this article is purely educational and should not be taken as professional investment advice. Invest at your own discretion. If you enjoyed this article, join my free investing community on Finary and check out some of my other articles below!
[ { "code": null, "e": 348, "s": 47, "text": "In one of my earlier articles, we went over how to parse the top analyst recommendations from Yahoo Finance for any stock. While they offered validation as to where a stock might move in the future, they were only updated once a month and did not offer any info as to the rationale behind the rating." }, { "code": null, "e": 751, "s": 348, "text": "Luckily, since then, I’ve stumbled upon the wonderful site TradingView. If you aren’t familiar with the site, one of the features they offer is real-time recommendations for as short as 1 minute ahead or for as long as 1 month ahead. These recommendations are purely based on Technical Indicators including Moving Averages, Oscillators, and Pivots and you can see the calculations directly on the page!" }, { "code": null, "e": 904, "s": 751, "text": "So instead of visiting the site each time I wanted a recommendation, I created this simple parser with less than 50 lines of code that can do just that." }, { "code": null, "e": 1434, "s": 904, "text": "Before I get into the coding aspect, I want to quickly touch upon what and where these recommendations are on TradingView. If you go over to this page, you will see something similar to the image I included below. The page includes key statistics such as Price to Earnings ratio, Earnings Per Share, Market Cap, Dividend information, and much more. You can even click Overview to get a comprehensive table full of ratios as well as an interactive chart, and recent news. However, this isn’t where the recommendations are located." }, { "code": null, "e": 1624, "s": 1434, "text": "If you continue scrolling down on the Technicals page, there will be multiple charts like the one below, outlining the recommendation and the statistics for the reasoning behind the signal." }, { "code": null, "e": 1966, "s": 1624, "text": "The recommendations range from strong buy to strong sell and as you can see in the second image, they are entirely dependent on the technical indicator signals. The algorithm we will be building soon parses the number of buy signals, neutral signals, sell signals, and the overall recommendation. The GitHub gist below contains all the code!" }, { "code": null, "e": 2279, "s": 1966, "text": "In case you do not have Selenium or Pandas installed, you can visit their respective links and download them using pip in your terminal! We will also need a chromedriver (the simulated chrome browser Selenium controls) and to download it using Python you can use the webdriver-manager package also found in PyPi." }, { "code": null, "e": 2502, "s": 2279, "text": "Additionally, you can use any IDE or Text Editor that supports Python as long as you have the necessary dependencies installed. I personally would recommend downloading either Visual Studio Code or Spyder through Anaconda." }, { "code": null, "e": 2634, "s": 2502, "text": "Now that everything should be installed on your machine and you have an idea for what we will be scraping, let’s get into the code!" }, { "code": null, "e": 2793, "s": 2634, "text": "First, we have to import the dependencies we will need for the rest of the program. In this case, we will need the built-in time module, Pandas, and Selenium." }, { "code": null, "e": 3109, "s": 2793, "text": "The time module will allow us to make the program sleep for a number of seconds just so the simulated browser can fully load. Pandas will allow us to create a DataFrame with the data we collect. Finally, we will need selenium so we can create/control a browser window and scrape the JavaScript-rendered information." }, { "code": null, "e": 3300, "s": 3109, "text": "Next, we can create two variables, one for the ticker and the other for the interval we are particularly scraping for. The interval can be any of the ones I included in the code fence below." }, { "code": null, "e": 3563, "s": 3300, "text": "#===================================================================# Intervals: # 1m for 1 minute# 15m for 15 minutes# 1h for 1 hour# 4h for 4 hours# 1D for 1 day# 1W for 1 week# 1M for 1 month# ==================================================================" }, { "code": null, "e": 3992, "s": 3563, "text": "After we include the imports and parameters, we can set up the chromedriver. The Options class will allow us to add arguments such as headless to customize the simulated browser. Adding headless tells the browser to not pop up each time you run the program. We can set the executable path to the path where you downloaded the chromedriver earlier. In this case, I downloaded it directly into my directory but you do not have to." }, { "code": null, "e": 4311, "s": 3992, "text": "We can add our scraping script inside a try/except block to catch errors from breaking our program. First, we must open up the browser using webdriver.get(URL), refresh to load all aspects of the page properly, and then add time.sleep(1) to slow down the program by one second until the browser is completely rendered." }, { "code": null, "e": 4736, "s": 4311, "text": "Using the .find_by_class_name method in selenium.webdriver, we can pinpoint the exact portions we want to scrape. For example, only the recommendation has the following class “speedometerSignal-pyzN — tL.” We can retrieve these class names by inspect element in Chrome DevTools. Top open up DevTools, you can right-click on the section you’d like to parse and then press “inspect” to get a similar result to the image below!" }, { "code": null, "e": 4862, "s": 4736, "text": "We can retrieve the “Buy” using the method .get_attribute(‘innerHTML’) which will store the text that is inside the HTML tag." }, { "code": null, "e": 5192, "s": 4862, "text": "Similarly, we can retrieve the number of buy, neutral, and sell signals by finding a class name that is similar between all of them and then using the method .find_elements_by_class_name. Since this time we are calling for elements, not an element, this method will return a list of HTML tags that have the class name we specify." }, { "code": null, "e": 5513, "s": 5192, "text": "Lastly, we can append all of the signals to a list, and using the .from_records method, we can turn a tuple of our data and a list of columns into a DataFrame. Finally, we can clean it up by adding a column for the ticker, setting that column as the index, and transposing (rotating) the DataFrame for our final product." }, { "code": null, "e": 5678, "s": 5513, "text": "Now within seconds, you should get a similar output to the image above. I hope this algorithm will prove useful to you in the future. Thank you so much for reading!" }, { "code": null, "e": 5831, "s": 5678, "text": "Disclaimer: The material in this article is purely educational and should not be taken as professional investment advice. Invest at your own discretion." } ]
Enum.GetName in C#
Gets the string representation of an Enum value using the Enum.GetName. It has two parameters − Type − Enumeration type Type − Enumeration type Object − Value of an enumeration Object − Value of an enumeration The following is an example − Live Demo using System; class Demo { enum Vehicle { Car, Motorbike, Truck, Bicycles }; static void Main() { // Usig GetName to get the string representation of enum type string res = Enum.GetName(typeof(Vehicle), Vehicle.Motorbike); // Displaying Console.WriteLine(res); } } Motorbike
[ { "code": null, "e": 1134, "s": 1062, "text": "Gets the string representation of an Enum value using the Enum.GetName." }, { "code": null, "e": 1158, "s": 1134, "text": "It has two parameters −" }, { "code": null, "e": 1182, "s": 1158, "text": "Type − Enumeration type" }, { "code": null, "e": 1206, "s": 1182, "text": "Type − Enumeration type" }, { "code": null, "e": 1239, "s": 1206, "text": "Object − Value of an enumeration" }, { "code": null, "e": 1272, "s": 1239, "text": "Object − Value of an enumeration" }, { "code": null, "e": 1302, "s": 1272, "text": "The following is an example −" }, { "code": null, "e": 1313, "s": 1302, "text": " Live Demo" }, { "code": null, "e": 1643, "s": 1313, "text": "using System;\n\nclass Demo {\n enum Vehicle {\n Car,\n Motorbike,\n Truck,\n Bicycles\n };\n static void Main() {\n // Usig GetName to get the string representation of enum type\n string res = Enum.GetName(typeof(Vehicle), Vehicle.Motorbike);\n \n // Displaying\n Console.WriteLine(res);\n }\n}" }, { "code": null, "e": 1653, "s": 1643, "text": "Motorbike" } ]
Training, Validating and Testing — Successfully Comparing Model Performances | Towards Data Science
If you have already used machine learning algorithms, you likely have encountered functions named like train_test_split() or similar sounding functions that are available in libraries such as scikit-learn, TensorFlow or others. Training a model is the first step in making good predictions, however identifying how well the predictive power is, is a different question. Splitting data is necessary to build a solid basis to train, compare and test your models. I will give this to you, model selection is allegedly not the most interesting or exciting task, however it is essential for everyone working with data. Throwing around models and machine learning algorithms is easy and can be done by almost anyone — the challenge lies in doing your analysis right. Let’s start with the reason why we are doing this: Every dataset contains patterns called real as well as random effects. Let’s assume we are looking at some random dataset. If we created a model that allowed us to predict values, the model is exposed to real and random effects. What we do not know is, which of the data points are random and therefore show a completely unique pattern in this particular dataset, and which data points are “typical” (real effects), hence would look similar in other, new data. Let’s put it the other way around, if we had a dataset with only perfectly “real” data our model would fit well, and also perform equally well on new data, given the real effects are present in any other dataset too. But to be real, this is just hypothetical. Data contains random patterns and our model will fit to both, random and real data — and this is exactly why we need to measure accuracy for all models. Real world datasets will contain both, random and real effects, hence it is unlikely to have a model that is 100% accurate — and even if so, it is very likely to overfit the data the model was trained on. Further, new data points will also contain (entirely new) random effects and is simply unlikely that our model is able to capture these well. The questions we want to answer are simple ones, “ is my model accurate” and “how accurate is my model?”. Basically there are two entry points to answer this question, do I have a single model or are thereseveral models single model or are there several models which have to be trained, evaluated and compared among each other. Why is it important to know whether we look at a single or different models? Because depending on this assumption, we need to split our data slightly differently. In general, cross validation is the preferred way to evaluate the performance of a model and/or tweak hyperparameters, however when dealing with a variety of models, it is often simply convenient to apply different (sub) datasets and see how the models perform. If you are more interested in cross validation (or Monte Carlo Cross Validation), follow this link: towardsdatascience.com Single model case: In order to test our model with regard to its predictive accuracy it seems quite intuitive to split data into a training portion and a test portion, so that the model can be trained on one dataset, but tested on a different, new data portion. The reason for this test is simple, imagine we used the full dataset to train the model and then use the same data to predict the model’s accuracy. Naturally, we expect the model to perform well, given that all data points are already “known”. This is exactly what the term overfit refers to. What we are interested in is, if the model is also capable of handling data that has just been introduced — the test data. Training a single model is quite straightforward. We split the data into two datasets: Training data for the model fittingTesting data for estimating the model’s accuracy Training data for the model fitting Testing data for estimating the model’s accuracy A brief look at the R documentation reveals an example code to split data into train and test — which is the way to go, if we only tested one model. If we had several models to test, the data should be split into three portions — but I will get to this later. # 0.8 is the size of the training datatrain_index <- sample(1:nrow(adult), 0.8 * nrow(adult))test_index <- setdiff(1:nrow(adult), train_index)# Build X_train, y_train, X_test, y_testX_train <- adult[train_index, -15] # income = column 15y_train <- adult[train_index, "income"] # income = column 15X_test <- adult[test_index, -15] # income = column 15y_test <- adult[test_index, "income"] # income = column 15 In order to conclude if our trained model has good predictive power, we simply use the trained model and predict the response for the test data. These predictions can then be used to compare with the true response variable. The following demo code illustrates how we measure accuracy in the simple one model case (R like pseudo code): model <- classifier( y_train ~ X_train ) # y explained by Xpredictions <- predict( model, X_test )RMSE( pred=predictions, obs=y_test ) # predictions vs. Obs Multiple model case. Now it gets a bit less intuitive. If we created several models — let’s assume we changed a specific hyperparameter a couple of times to see the impact on the models or we used different classification models like SVM and KNN — each of these examples will be considered a different model. Let’s assume more specifically that there are 10 models, each one is characterized by having different hyperparameters compared to all other models. As an example, models may differ with regard to a larger XYZ value, some a smaller value lambda, etc. — you see my point. At this point, we trained 10 models on the same training data. Each model will provide its very own accuracy, some will do better some worse than others. The question now is, how can we choose the best model and how can we estimate the “true” accuracy of the model? Step 1: Choose the right model among each model type As we currently look at 10 models that have only been introduced to training data, for this reason we need a data portion our models have not seen before — the validation data. We can use the validation data to calculate accuracy metrics for every single model (each having different hyper/parameters). This allows us to rank the models by type and their best scores and select the best k models we would like to test the overall performance later on. I usually define k=2 or 3. As an example, if we had 10 models, that have 3 different underlying types (for example 3 KNN models, 4 CART models and 3 Support Vector Machine models), we simply select the best model out of each category. This concludes training and validation. Step 2: Measure the true accuracy of your model Having three models at hand, we must not yet assume that performance on the validation data is the “real” performance of each model. At this point we introduce the last step, accompanied by the test dataset. For each of the k best (top 3) models we use the model to classify the test data and calculate the test error metrics. This sounds like we’re doing the same thing all over again, just for three models and using the test set — but why? Recall my short monologue about random and real effects. The best model (in terms of highest accuracy) after validation may be good, but there it is also likely that one model may have benefited from being more suitable for the random pattern in the validation data — the random effects — and this, only by chance. This is not what we want to measure our models on, we do not want to choose a model, assuming it is better, but in reality the model only outperformed simply due to luck. For this reason, the test set introduces another layer that minimizes chances that a model benefits from pure randomness. This concludes the third step, the final evaluation. We simply pick the best out of the three models. This model was fitted (training data), performed among the top 3 on the validation data and turned out to have the best accuracy on the test data. What do we do if the observed accuracy is now considerably lower than the accuracy on the validation set? The simple answer is, nothing. Stick with the model. We have worked through legitimate steps to evaluate and compare all our the models. If the results do eventually show a lower score, then this is what the model performance is on new and unseen data. Do not run this procedure again, e.g. using different data splits, until your final model does better — why? Re-applying this procedure to find a better model under the same setting simply means, that you probably found a model that overfits the data, but may again work less well on new data in the future. To make this process of selecting the best among several models a bit more tangible, the steps are outlined with a bit more structure and terminology: Training dataset: the training dataset is used to train the model. This dataset should be the largest portion of the dataset. Model generally perform well when tested against the training dataset, simply because the error is underestimated (“downward bias”). Validation dataset: Required if several models are compared. The validation dataset is used to validate the models and pick the best among them. Test dataset: Eventually determines the true performance of the selected models. The test error is likely to be higher than what was observed in the previous steps. This step let’s is select the one final model among all. As outlined earlier, we do not know which data points are random effects and which are not. There are various ways to split the data, but in general choosing random data points is a good idea to start with — R’s sample or Python’s random.sample functions may be very handy. This post provided a short guidance through the challenges model selection under a larger number of models. Although, this topic can certainly not be found among the most exciting machine learning lectures it is crucial to follow established procedures to pick and validate data models. {See you next time} [1] Photo by invisiblepower on Unsplash— Thanks!
[ { "code": null, "e": 632, "s": 171, "text": "If you have already used machine learning algorithms, you likely have encountered functions named like train_test_split() or similar sounding functions that are available in libraries such as scikit-learn, TensorFlow or others. Training a model is the first step in making good predictions, however identifying how well the predictive power is, is a different question. Splitting data is necessary to build a solid basis to train, compare and test your models." }, { "code": null, "e": 785, "s": 632, "text": "I will give this to you, model selection is allegedly not the most interesting or exciting task, however it is essential for everyone working with data." }, { "code": null, "e": 932, "s": 785, "text": "Throwing around models and machine learning algorithms is easy and can be done by almost anyone — the challenge lies in doing your analysis right." }, { "code": null, "e": 1444, "s": 932, "text": "Let’s start with the reason why we are doing this: Every dataset contains patterns called real as well as random effects. Let’s assume we are looking at some random dataset. If we created a model that allowed us to predict values, the model is exposed to real and random effects. What we do not know is, which of the data points are random and therefore show a completely unique pattern in this particular dataset, and which data points are “typical” (real effects), hence would look similar in other, new data." }, { "code": null, "e": 1661, "s": 1444, "text": "Let’s put it the other way around, if we had a dataset with only perfectly “real” data our model would fit well, and also perform equally well on new data, given the real effects are present in any other dataset too." }, { "code": null, "e": 1857, "s": 1661, "text": "But to be real, this is just hypothetical. Data contains random patterns and our model will fit to both, random and real data — and this is exactly why we need to measure accuracy for all models." }, { "code": null, "e": 2204, "s": 1857, "text": "Real world datasets will contain both, random and real effects, hence it is unlikely to have a model that is 100% accurate — and even if so, it is very likely to overfit the data the model was trained on. Further, new data points will also contain (entirely new) random effects and is simply unlikely that our model is able to capture these well." }, { "code": null, "e": 2384, "s": 2204, "text": "The questions we want to answer are simple ones, “ is my model accurate” and “how accurate is my model?”. Basically there are two entry points to answer this question, do I have a" }, { "code": null, "e": 2424, "s": 2384, "text": "single model or are thereseveral models" }, { "code": null, "e": 2450, "s": 2424, "text": "single model or are there" }, { "code": null, "e": 2465, "s": 2450, "text": "several models" }, { "code": null, "e": 2695, "s": 2465, "text": "which have to be trained, evaluated and compared among each other. Why is it important to know whether we look at a single or different models? Because depending on this assumption, we need to split our data slightly differently." }, { "code": null, "e": 2957, "s": 2695, "text": "In general, cross validation is the preferred way to evaluate the performance of a model and/or tweak hyperparameters, however when dealing with a variety of models, it is often simply convenient to apply different (sub) datasets and see how the models perform." }, { "code": null, "e": 3057, "s": 2957, "text": "If you are more interested in cross validation (or Monte Carlo Cross Validation), follow this link:" }, { "code": null, "e": 3080, "s": 3057, "text": "towardsdatascience.com" }, { "code": null, "e": 3342, "s": 3080, "text": "Single model case: In order to test our model with regard to its predictive accuracy it seems quite intuitive to split data into a training portion and a test portion, so that the model can be trained on one dataset, but tested on a different, new data portion." }, { "code": null, "e": 3758, "s": 3342, "text": "The reason for this test is simple, imagine we used the full dataset to train the model and then use the same data to predict the model’s accuracy. Naturally, we expect the model to perform well, given that all data points are already “known”. This is exactly what the term overfit refers to. What we are interested in is, if the model is also capable of handling data that has just been introduced — the test data." }, { "code": null, "e": 3845, "s": 3758, "text": "Training a single model is quite straightforward. We split the data into two datasets:" }, { "code": null, "e": 3929, "s": 3845, "text": "Training data for the model fittingTesting data for estimating the model’s accuracy" }, { "code": null, "e": 3965, "s": 3929, "text": "Training data for the model fitting" }, { "code": null, "e": 4014, "s": 3965, "text": "Testing data for estimating the model’s accuracy" }, { "code": null, "e": 4274, "s": 4014, "text": "A brief look at the R documentation reveals an example code to split data into train and test — which is the way to go, if we only tested one model. If we had several models to test, the data should be split into three portions — but I will get to this later." }, { "code": null, "e": 4684, "s": 4274, "text": "# 0.8 is the size of the training datatrain_index <- sample(1:nrow(adult), 0.8 * nrow(adult))test_index <- setdiff(1:nrow(adult), train_index)# Build X_train, y_train, X_test, y_testX_train <- adult[train_index, -15] # income = column 15y_train <- adult[train_index, \"income\"] # income = column 15X_test <- adult[test_index, -15] # income = column 15y_test <- adult[test_index, \"income\"] # income = column 15" }, { "code": null, "e": 5019, "s": 4684, "text": "In order to conclude if our trained model has good predictive power, we simply use the trained model and predict the response for the test data. These predictions can then be used to compare with the true response variable. The following demo code illustrates how we measure accuracy in the simple one model case (R like pseudo code):" }, { "code": null, "e": 5176, "s": 5019, "text": "model <- classifier( y_train ~ X_train ) # y explained by Xpredictions <- predict( model, X_test )RMSE( pred=predictions, obs=y_test ) # predictions vs. Obs" }, { "code": null, "e": 5485, "s": 5176, "text": "Multiple model case. Now it gets a bit less intuitive. If we created several models — let’s assume we changed a specific hyperparameter a couple of times to see the impact on the models or we used different classification models like SVM and KNN — each of these examples will be considered a different model." }, { "code": null, "e": 5756, "s": 5485, "text": "Let’s assume more specifically that there are 10 models, each one is characterized by having different hyperparameters compared to all other models. As an example, models may differ with regard to a larger XYZ value, some a smaller value lambda, etc. — you see my point." }, { "code": null, "e": 6022, "s": 5756, "text": "At this point, we trained 10 models on the same training data. Each model will provide its very own accuracy, some will do better some worse than others. The question now is, how can we choose the best model and how can we estimate the “true” accuracy of the model?" }, { "code": null, "e": 6075, "s": 6022, "text": "Step 1: Choose the right model among each model type" }, { "code": null, "e": 6252, "s": 6075, "text": "As we currently look at 10 models that have only been introduced to training data, for this reason we need a data portion our models have not seen before — the validation data." }, { "code": null, "e": 6554, "s": 6252, "text": "We can use the validation data to calculate accuracy metrics for every single model (each having different hyper/parameters). This allows us to rank the models by type and their best scores and select the best k models we would like to test the overall performance later on. I usually define k=2 or 3." }, { "code": null, "e": 6762, "s": 6554, "text": "As an example, if we had 10 models, that have 3 different underlying types (for example 3 KNN models, 4 CART models and 3 Support Vector Machine models), we simply select the best model out of each category." }, { "code": null, "e": 6802, "s": 6762, "text": "This concludes training and validation." }, { "code": null, "e": 6850, "s": 6802, "text": "Step 2: Measure the true accuracy of your model" }, { "code": null, "e": 7177, "s": 6850, "text": "Having three models at hand, we must not yet assume that performance on the validation data is the “real” performance of each model. At this point we introduce the last step, accompanied by the test dataset. For each of the k best (top 3) models we use the model to classify the test data and calculate the test error metrics." }, { "code": null, "e": 7608, "s": 7177, "text": "This sounds like we’re doing the same thing all over again, just for three models and using the test set — but why? Recall my short monologue about random and real effects. The best model (in terms of highest accuracy) after validation may be good, but there it is also likely that one model may have benefited from being more suitable for the random pattern in the validation data — the random effects — and this, only by chance." }, { "code": null, "e": 7901, "s": 7608, "text": "This is not what we want to measure our models on, we do not want to choose a model, assuming it is better, but in reality the model only outperformed simply due to luck. For this reason, the test set introduces another layer that minimizes chances that a model benefits from pure randomness." }, { "code": null, "e": 8150, "s": 7901, "text": "This concludes the third step, the final evaluation. We simply pick the best out of the three models. This model was fitted (training data), performed among the top 3 on the validation data and turned out to have the best accuracy on the test data." }, { "code": null, "e": 8256, "s": 8150, "text": "What do we do if the observed accuracy is now considerably lower than the accuracy on the validation set?" }, { "code": null, "e": 8817, "s": 8256, "text": "The simple answer is, nothing. Stick with the model. We have worked through legitimate steps to evaluate and compare all our the models. If the results do eventually show a lower score, then this is what the model performance is on new and unseen data. Do not run this procedure again, e.g. using different data splits, until your final model does better — why? Re-applying this procedure to find a better model under the same setting simply means, that you probably found a model that overfits the data, but may again work less well on new data in the future." }, { "code": null, "e": 8968, "s": 8817, "text": "To make this process of selecting the best among several models a bit more tangible, the steps are outlined with a bit more structure and terminology:" }, { "code": null, "e": 9227, "s": 8968, "text": "Training dataset: the training dataset is used to train the model. This dataset should be the largest portion of the dataset. Model generally perform well when tested against the training dataset, simply because the error is underestimated (“downward bias”)." }, { "code": null, "e": 9372, "s": 9227, "text": "Validation dataset: Required if several models are compared. The validation dataset is used to validate the models and pick the best among them." }, { "code": null, "e": 9594, "s": 9372, "text": "Test dataset: Eventually determines the true performance of the selected models. The test error is likely to be higher than what was observed in the previous steps. This step let’s is select the one final model among all." }, { "code": null, "e": 9868, "s": 9594, "text": "As outlined earlier, we do not know which data points are random effects and which are not. There are various ways to split the data, but in general choosing random data points is a good idea to start with — R’s sample or Python’s random.sample functions may be very handy." }, { "code": null, "e": 10155, "s": 9868, "text": "This post provided a short guidance through the challenges model selection under a larger number of models. Although, this topic can certainly not be found among the most exciting machine learning lectures it is crucial to follow established procedures to pick and validate data models." }, { "code": null, "e": 10175, "s": 10155, "text": "{See you next time}" } ]
Python Program to Implement a Stack using Linked List
When it is required to implement a stack data structure using a linked list, a method to add (push values) elements to the linked list, and a method to delete (pop values) the elements of the linked list are defined. Below is a demonstration for the same − Live Demo class Node: def __init__(self, data): self.data = data self.next = None class Stack_structure: def __init__(self): self.head = None def push_val(self, data): if self.head is None: self.head = Node(data) else: newNode = Node(data) newNode.next = self.head self.head = newNode def pop_val(self): if self.head is None: return None else: del_Val = self.head.data self.head = self.head.next return del_Val my_instance = Stack_structure() while True: print('push <value>') print('pop') print('quit') my_input = input('What action would you like to perform ? ').split() operation = my_input[0].strip().lower() if operation == 'push': my_instance.push_val(int(my_input[1])) elif operation == 'pop': del_Val = my_instance.pop_val() if del_Val is None: print('The stack is empty.') else: print('The deleted value is : ', int(del_Val)) elif operation == 'quit': break push <value> pop quit What action would you like to perform ? push 56 push <value> pop quit What action would you like to perform ? push 78 push <value> pop quit What action would you like to perform ? push 90 push <value> pop quit What action would you like to perform ? pop The deleted value is : 90 push <value> pop quit What action would you like to perform ? quit The ‘Node’ class is created. The ‘Node’ class is created. Another ‘Stack_structure’ class with required attributes is created. Another ‘Stack_structure’ class with required attributes is created. It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’. It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’. A method named ‘push_val’ is defined, that helps add a value to the stack. A method named ‘push_val’ is defined, that helps add a value to the stack. Another method named ‘pop_val’ is defined, that helps delete a value from the top of the stack, and returns the deleted value. Another method named ‘pop_val’ is defined, that helps delete a value from the top of the stack, and returns the deleted value. An instance of the ‘Stack_structure’ is created. An instance of the ‘Stack_structure’ is created. Three options are given, such as ‘push’, ‘pop’, and ‘quit’. Three options are given, such as ‘push’, ‘pop’, and ‘quit’. The ‘push’ option adds a specific value to the stack. The ‘push’ option adds a specific value to the stack. The ‘pop’ option deletes the topmost element from the stack. The ‘pop’ option deletes the topmost element from the stack. The ‘quit’ option comes out of the loop. The ‘quit’ option comes out of the loop. Based on the input/choice by user, the respective operations are performed. Based on the input/choice by user, the respective operations are performed. This output is displayed on the console. This output is displayed on the console.
[ { "code": null, "e": 1404, "s": 1187, "text": "When it is required to implement a stack data structure using a linked list, a method to add (push values) elements to the linked list, and a method to delete (pop values) the elements of the linked list are defined." }, { "code": null, "e": 1444, "s": 1404, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1455, "s": 1444, "text": " Live Demo" }, { "code": null, "e": 2515, "s": 1455, "text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass Stack_structure:\n def __init__(self):\n self.head = None\n\n def push_val(self, data):\n if self.head is None:\n self.head = Node(data)\n else:\n newNode = Node(data)\n newNode.next = self.head\n self.head = newNode\n\n def pop_val(self):\n if self.head is None:\n return None\n else:\n del_Val = self.head.data\n self.head = self.head.next\n return del_Val\n\nmy_instance = Stack_structure()\nwhile True:\n print('push <value>')\n print('pop')\n print('quit')\n my_input = input('What action would you like to perform ? ').split()\n\n operation = my_input[0].strip().lower()\n if operation == 'push':\n my_instance.push_val(int(my_input[1]))\n elif operation == 'pop':\n del_Val = my_instance.pop_val()\n if del_Val is None:\n print('The stack is empty.')\n else:\n print('The deleted value is : ', int(del_Val))\n elif operation == 'quit':\n break" }, { "code": null, "e": 2884, "s": 2515, "text": "push <value>\npop\nquit\nWhat action would you like to perform ? push 56\npush <value>\npop\nquit\nWhat action would you like to perform ? push 78\npush <value>\npop\nquit\nWhat action would you like to perform ? push 90\npush <value>\npop\nquit\nWhat action would you like to perform ? pop\nThe deleted value is : 90\npush <value>\npop\nquit\nWhat action would you like to perform ? quit" }, { "code": null, "e": 2913, "s": 2884, "text": "The ‘Node’ class is created." }, { "code": null, "e": 2942, "s": 2913, "text": "The ‘Node’ class is created." }, { "code": null, "e": 3011, "s": 2942, "text": "Another ‘Stack_structure’ class with required attributes is created." }, { "code": null, "e": 3080, "s": 3011, "text": "Another ‘Stack_structure’ class with required attributes is created." }, { "code": null, "e": 3178, "s": 3080, "text": "It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’." }, { "code": null, "e": 3276, "s": 3178, "text": "It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’." }, { "code": null, "e": 3351, "s": 3276, "text": "A method named ‘push_val’ is defined, that helps add a value to the stack." }, { "code": null, "e": 3426, "s": 3351, "text": "A method named ‘push_val’ is defined, that helps add a value to the stack." }, { "code": null, "e": 3553, "s": 3426, "text": "Another method named ‘pop_val’ is defined, that helps delete a value from the top of the stack, and returns the deleted value." }, { "code": null, "e": 3680, "s": 3553, "text": "Another method named ‘pop_val’ is defined, that helps delete a value from the top of the stack, and returns the deleted value." }, { "code": null, "e": 3729, "s": 3680, "text": "An instance of the ‘Stack_structure’ is created." }, { "code": null, "e": 3778, "s": 3729, "text": "An instance of the ‘Stack_structure’ is created." }, { "code": null, "e": 3838, "s": 3778, "text": "Three options are given, such as ‘push’, ‘pop’, and ‘quit’." }, { "code": null, "e": 3898, "s": 3838, "text": "Three options are given, such as ‘push’, ‘pop’, and ‘quit’." }, { "code": null, "e": 3952, "s": 3898, "text": "The ‘push’ option adds a specific value to the stack." }, { "code": null, "e": 4006, "s": 3952, "text": "The ‘push’ option adds a specific value to the stack." }, { "code": null, "e": 4067, "s": 4006, "text": "The ‘pop’ option deletes the topmost element from the stack." }, { "code": null, "e": 4128, "s": 4067, "text": "The ‘pop’ option deletes the topmost element from the stack." }, { "code": null, "e": 4169, "s": 4128, "text": "The ‘quit’ option comes out of the loop." }, { "code": null, "e": 4210, "s": 4169, "text": "The ‘quit’ option comes out of the loop." }, { "code": null, "e": 4286, "s": 4210, "text": "Based on the input/choice by user, the respective operations are performed." }, { "code": null, "e": 4362, "s": 4286, "text": "Based on the input/choice by user, the respective operations are performed." }, { "code": null, "e": 4403, "s": 4362, "text": "This output is displayed on the console." }, { "code": null, "e": 4444, "s": 4403, "text": "This output is displayed on the console." } ]
Digital Low Pass Butterworth Filter in Python
08 Dec, 2020 In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse Response of the Digital Butterworth Filter. The specifications are as follows: Sampling rate of 40 kHz Pass band edge frequency of 4 kHz Stop band edge frequency of 8kHz Pass band ripple of 0.5 dB Minimum stop band attenuation of40 dB We will plot the magnitude, phase, and impulse response of the filter. Step 1: Importing all the necessary libraries. Python3 # import required modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy import signalimport math Step 2: Define variables with the given specifications of the filter. Python3 # Specifications of Filter # sampling frequencyf_sample = 40000 # pass band frequencyf_pass = 4000 # stop band frequencyf_stop = 8000 # pass band ripplefs = 0.5 # pass band freq in radianwp = f_pass/(f_sample/2) # stop band freq in radianws = f_stop/(f_sample/2) # Sampling TimeTd = 1 # pass band rippleg_pass = 0.5 # stop band attenuationg_stop = 40 Step3: Building the filter using signal.buttord function. Python3 # Conversion to prewrapped analog frequencyomega_p = (2/Td)*np.tan(wp/2)omega_s = (2/Td)*np.tan(ws/2) # Design of Filter using signal.buttord functionN, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency!print("Order of the Filter=", N) # N is the order# Wn is the cut-off freq of the filterprint("Cut-off frequency= {:.3f} rad/s ".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is the denominatorb, a = signal.butter(N, Wn, 'low', True)z, p = signal.bilinear(b, a, fs)# w is the freq in z-domain & h is the magnitude in z-domainw, h = signal.freqz(z, p, 512) Output: Step 4: Plotting the Magnitude Response. Python3 # Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show() Output: Step 5: Plotting the Impulse Response. Python3 # Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp) plt.stem(np.arange(0, 40), imp, use_line_collection=True)plt.stem(np.arange(0, 40), response, use_line_collection=True)plt.margins(0, 0.1) plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show() Output: Step 6: Plotting the Phase Response. Python3 # Phase Responsefig, ax1 = plt.subplots() ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]') angles = np.unwrap(np.angle(h)) ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show() Output: Below is the complete program based on the above approach: Python # import required modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy import signalimport math # Specifications of Filter # sampling frequencyf_sample = 40000 # pass band frequencyf_pass = 4000 # stop band frequencyf_stop = 8000 # pass band ripplefs = 0.5 # pass band freq in radianwp = f_pass/(f_sample/2) # stop band freq in radianws = f_stop/(f_sample/2) # Sampling TimeTd = 1 # pass band rippleg_pass = 0.5 # stop band attenuationg_stop = 40 # Conversion to prewrapped analog frequencyomega_p = (2/Td)*np.tan(wp/2)omega_s = (2/Td)*np.tan(ws/2) # Design of Filter using signal.buttord functionN, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency!print("Order of the Filter=", N) # N is the order# Wn is the cut-off freq of the filterprint("Cut-off frequency= {:.3f} rad/s ".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is the denominatorb, a = signal.butter(N, Wn, 'low', True)z, p = signal.bilinear(b, a, fs)# w is the freq in z-domain & h is the magnitude in z-domainw, h = signal.freqz(z, p, 512) # Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show() # Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp)plt.stem(np.arange(0, 40), imp, use_line_collection=True)plt.stem(np.arange(0, 40), response, use_line_collection=True)plt.margins(0, 0.1)plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show() # Phase Responsefig, ax1 = plt.subplots()ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]')angles = np.unwrap(np.angle(h))ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show() Output: Python-matplotlib Python-numpy Advanced Computer Subject Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Reinforcement learning Docker - COPY Instruction Supervised and Unsupervised learning Read JSON file using Python Python map() function Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Dec, 2020" }, { "code": null, "e": 443, "s": 54, "text": "In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse Response of the Digital Butterworth Filter." }, { "code": null, "e": 479, "s": 443, "text": "The specifications are as follows: " }, { "code": null, "e": 503, "s": 479, "text": "Sampling rate of 40 kHz" }, { "code": null, "e": 537, "s": 503, "text": "Pass band edge frequency of 4 kHz" }, { "code": null, "e": 570, "s": 537, "text": "Stop band edge frequency of 8kHz" }, { "code": null, "e": 597, "s": 570, "text": "Pass band ripple of 0.5 dB" }, { "code": null, "e": 635, "s": 597, "text": "Minimum stop band attenuation of40 dB" }, { "code": null, "e": 706, "s": 635, "text": "We will plot the magnitude, phase, and impulse response of the filter." }, { "code": null, "e": 753, "s": 706, "text": "Step 1: Importing all the necessary libraries." }, { "code": null, "e": 761, "s": 753, "text": "Python3" }, { "code": "# import required modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy import signalimport math", "e": 871, "s": 761, "text": null }, { "code": null, "e": 941, "s": 871, "text": "Step 2: Define variables with the given specifications of the filter." }, { "code": null, "e": 949, "s": 941, "text": "Python3" }, { "code": "# Specifications of Filter # sampling frequencyf_sample = 40000 # pass band frequencyf_pass = 4000 # stop band frequencyf_stop = 8000 # pass band ripplefs = 0.5 # pass band freq in radianwp = f_pass/(f_sample/2) # stop band freq in radianws = f_stop/(f_sample/2) # Sampling TimeTd = 1 # pass band rippleg_pass = 0.5 # stop band attenuationg_stop = 40 ", "e": 1324, "s": 949, "text": null }, { "code": null, "e": 1382, "s": 1324, "text": "Step3: Building the filter using signal.buttord function." }, { "code": null, "e": 1390, "s": 1382, "text": "Python3" }, { "code": "# Conversion to prewrapped analog frequencyomega_p = (2/Td)*np.tan(wp/2)omega_s = (2/Td)*np.tan(ws/2) # Design of Filter using signal.buttord functionN, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency!print(\"Order of the Filter=\", N) # N is the order# Wn is the cut-off freq of the filterprint(\"Cut-off frequency= {:.3f} rad/s \".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is the denominatorb, a = signal.butter(N, Wn, 'low', True)z, p = signal.bilinear(b, a, fs)# w is the freq in z-domain & h is the magnitude in z-domainw, h = signal.freqz(z, p, 512)", "e": 2057, "s": 1390, "text": null }, { "code": null, "e": 2065, "s": 2057, "text": "Output:" }, { "code": null, "e": 2106, "s": 2065, "text": "Step 4: Plotting the Magnitude Response." }, { "code": null, "e": 2114, "s": 2106, "text": "Python3" }, { "code": "# Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show()", "e": 2389, "s": 2114, "text": null }, { "code": null, "e": 2397, "s": 2389, "text": "Output:" }, { "code": null, "e": 2436, "s": 2397, "text": "Step 5: Plotting the Impulse Response." }, { "code": null, "e": 2444, "s": 2436, "text": "Python3" }, { "code": "# Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp) plt.stem(np.arange(0, 40), imp, use_line_collection=True)plt.stem(np.arange(0, 40), response, use_line_collection=True)plt.margins(0, 0.1) plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show()", "e": 2773, "s": 2444, "text": null }, { "code": null, "e": 2781, "s": 2773, "text": "Output:" }, { "code": null, "e": 2818, "s": 2781, "text": "Step 6: Plotting the Phase Response." }, { "code": null, "e": 2826, "s": 2818, "text": "Python3" }, { "code": "# Phase Responsefig, ax1 = plt.subplots() ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]') angles = np.unwrap(np.angle(h)) ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show()", "e": 3099, "s": 2826, "text": null }, { "code": null, "e": 3107, "s": 3099, "text": "Output:" }, { "code": null, "e": 3166, "s": 3107, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 3173, "s": 3166, "text": "Python" }, { "code": "# import required modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy import signalimport math # Specifications of Filter # sampling frequencyf_sample = 40000 # pass band frequencyf_pass = 4000 # stop band frequencyf_stop = 8000 # pass band ripplefs = 0.5 # pass band freq in radianwp = f_pass/(f_sample/2) # stop band freq in radianws = f_stop/(f_sample/2) # Sampling TimeTd = 1 # pass band rippleg_pass = 0.5 # stop band attenuationg_stop = 40 # Conversion to prewrapped analog frequencyomega_p = (2/Td)*np.tan(wp/2)omega_s = (2/Td)*np.tan(ws/2) # Design of Filter using signal.buttord functionN, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency!print(\"Order of the Filter=\", N) # N is the order# Wn is the cut-off freq of the filterprint(\"Cut-off frequency= {:.3f} rad/s \".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is the denominatorb, a = signal.butter(N, Wn, 'low', True)z, p = signal.bilinear(b, a, fs)# w is the freq in z-domain & h is the magnitude in z-domainw, h = signal.freqz(z, p, 512) # Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show() # Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp)plt.stem(np.arange(0, 40), imp, use_line_collection=True)plt.stem(np.arange(0, 40), response, use_line_collection=True)plt.margins(0, 0.1)plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show() # Phase Responsefig, ax1 = plt.subplots()ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]')angles = np.unwrap(np.angle(h))ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show()", "e": 5207, "s": 3173, "text": null }, { "code": null, "e": 5215, "s": 5207, "text": "Output:" }, { "code": null, "e": 5233, "s": 5215, "text": "Python-matplotlib" }, { "code": null, "e": 5246, "s": 5233, "text": "Python-numpy" }, { "code": null, "e": 5272, "s": 5246, "text": "Advanced Computer Subject" }, { "code": null, "e": 5279, "s": 5272, "text": "Python" }, { "code": null, "e": 5377, "s": 5279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5400, "s": 5377, "text": "System Design Tutorial" }, { "code": null, "e": 5423, "s": 5400, "text": "ML | Linear Regression" }, { "code": null, "e": 5446, "s": 5423, "text": "Reinforcement learning" }, { "code": null, "e": 5472, "s": 5446, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5509, "s": 5472, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 5537, "s": 5509, "text": "Read JSON file using Python" }, { "code": null, "e": 5559, "s": 5537, "text": "Python map() function" }, { "code": null, "e": 5577, "s": 5559, "text": "Python Dictionary" }, { "code": null, "e": 5621, "s": 5577, "text": "How to get column names in Pandas dataframe" } ]
Sending SMS using NEXMO API in Node.js
14 Feb, 2020 Introduction: SMS is a common method of sending short messages between cell phones, but these SMS can be sent using API in Node.js. Now there are lots of API in the market for sending SMS like Twilio, Exotel, etc to the user but the popular among them is Nexmo. Features of NEXMO: Integrating this module in your code is very simple and efficient. Using Nexmo module users can send SMS and also use Nexmo voice APIs for sending voice calls. Introduction: It’s easy to get started and easy to use.It is widely used and popular module for sending SMS.User can send SMS to desired mobile number fastly and efficiently. It’s easy to get started and easy to use. It is widely used and popular module for sending SMS. User can send SMS to desired mobile number fastly and efficiently. Installation of Nexmo module: You can visit the link to Install nexmo module. You can install this package by using the following command.npm install nexmoAfter installing nexmo you can check your nexmo version in command prompt using the command.npm version nexmoAfter 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.jsRequiring module: You need to include nexmo module in your file by using these lines.const Nexmo = require('nexmo');Filename: index.js// Include nexmo moduleconst Nexmo = require('nexmo'); const nexmo = new Nexmo({ apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET_KEY',}); // Initialize with sender and reciever// mobile number with text messageconst from = 'sender_name';const to = 'reciever_number';const text = 'Greetings from Geeksforgeeks'; nexmo.message.sendSms(from, to, text, function(error, result) { // If some error occured if(error) { console.log("ERROR", error) } // If message is sent successfully else { console.log("RESULT", result) }});Steps to run the program:The project structure will look like this:Make sure you have installed nexmo using following commands:npm install nexmoRun index.js file using below command:node index.jsIf error occurs, then following message will be displayed:My Personal Notes arrow_drop_upSave You can visit the link to Install nexmo module. You can install this package by using the following command.npm install nexmo npm install nexmo After installing nexmo you can check your nexmo version in command prompt using the command.npm version nexmo npm version nexmo 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 Requiring module: You need to include nexmo module in your file by using these lines.const Nexmo = require('nexmo'); const Nexmo = require('nexmo'); Filename: index.js // Include nexmo moduleconst Nexmo = require('nexmo'); const nexmo = new Nexmo({ apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET_KEY',}); // Initialize with sender and reciever// mobile number with text messageconst from = 'sender_name';const to = 'reciever_number';const text = 'Greetings from Geeksforgeeks'; nexmo.message.sendSms(from, to, text, function(error, result) { // If some error occured if(error) { console.log("ERROR", error) } // If message is sent successfully else { console.log("RESULT", result) }}); Steps to run the program: The project structure will look like this:Make sure you have installed nexmo using following commands:npm install nexmoRun index.js file using below command:node index.jsIf error occurs, then following message will be displayed: The project structure will look like this: Make sure you have installed nexmo using following commands:npm install nexmo npm install nexmo Run index.js file using below command:node index.js node index.js If error occurs, then following message will be displayed: Node.js-Misc Technical Scripter 2019 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function 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": 54, "s": 26, "text": "\n14 Feb, 2020" }, { "code": null, "e": 316, "s": 54, "text": "Introduction: SMS is a common method of sending short messages between cell phones, but these SMS can be sent using API in Node.js. Now there are lots of API in the market for sending SMS like Twilio, Exotel, etc to the user but the popular among them is Nexmo." }, { "code": null, "e": 495, "s": 316, "text": "Features of NEXMO: Integrating this module in your code is very simple and efficient. Using Nexmo module users can send SMS and also use Nexmo voice APIs for sending voice calls." }, { "code": null, "e": 509, "s": 495, "text": "Introduction:" }, { "code": null, "e": 670, "s": 509, "text": "It’s easy to get started and easy to use.It is widely used and popular module for sending SMS.User can send SMS to desired mobile number fastly and efficiently." }, { "code": null, "e": 712, "s": 670, "text": "It’s easy to get started and easy to use." }, { "code": null, "e": 766, "s": 712, "text": "It is widely used and popular module for sending SMS." }, { "code": null, "e": 833, "s": 766, "text": "User can send SMS to desired mobile number fastly and efficiently." }, { "code": null, "e": 863, "s": 833, "text": "Installation of Nexmo module:" }, { "code": null, "e": 2256, "s": 863, "text": "You can visit the link to Install nexmo module. You can install this package by using the following command.npm install nexmoAfter installing nexmo you can check your nexmo version in command prompt using the command.npm version nexmoAfter 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.jsRequiring module: You need to include nexmo module in your file by using these lines.const Nexmo = require('nexmo');Filename: index.js// Include nexmo moduleconst Nexmo = require('nexmo'); const nexmo = new Nexmo({ apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET_KEY',}); // Initialize with sender and reciever// mobile number with text messageconst from = 'sender_name';const to = 'reciever_number';const text = 'Greetings from Geeksforgeeks'; nexmo.message.sendSms(from, to, text, function(error, result) { // If some error occured if(error) { console.log(\"ERROR\", error) } // If message is sent successfully else { console.log(\"RESULT\", result) }});Steps to run the program:The project structure will look like this:Make sure you have installed nexmo using following commands:npm install nexmoRun index.js file using below command:node index.jsIf error occurs, then following message will be displayed:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 2382, "s": 2256, "text": "You can visit the link to Install nexmo module. You can install this package by using the following command.npm install nexmo" }, { "code": null, "e": 2400, "s": 2382, "text": "npm install nexmo" }, { "code": null, "e": 2510, "s": 2400, "text": "After installing nexmo you can check your nexmo version in command prompt using the command.npm version nexmo" }, { "code": null, "e": 2528, "s": 2510, "text": "npm version nexmo" }, { "code": null, "e": 2671, "s": 2528, "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": 2685, "s": 2671, "text": "node index.js" }, { "code": null, "e": 2802, "s": 2685, "text": "Requiring module: You need to include nexmo module in your file by using these lines.const Nexmo = require('nexmo');" }, { "code": null, "e": 2834, "s": 2802, "text": "const Nexmo = require('nexmo');" }, { "code": null, "e": 2853, "s": 2834, "text": "Filename: index.js" }, { "code": "// Include nexmo moduleconst Nexmo = require('nexmo'); const nexmo = new Nexmo({ apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET_KEY',}); // Initialize with sender and reciever// mobile number with text messageconst from = 'sender_name';const to = 'reciever_number';const text = 'Greetings from Geeksforgeeks'; nexmo.message.sendSms(from, to, text, function(error, result) { // If some error occured if(error) { console.log(\"ERROR\", error) } // If message is sent successfully else { console.log(\"RESULT\", result) }});", "e": 3448, "s": 2853, "text": null }, { "code": null, "e": 3474, "s": 3448, "text": "Steps to run the program:" }, { "code": null, "e": 3703, "s": 3474, "text": "The project structure will look like this:Make sure you have installed nexmo using following commands:npm install nexmoRun index.js file using below command:node index.jsIf error occurs, then following message will be displayed:" }, { "code": null, "e": 3746, "s": 3703, "text": "The project structure will look like this:" }, { "code": null, "e": 3824, "s": 3746, "text": "Make sure you have installed nexmo using following commands:npm install nexmo" }, { "code": null, "e": 3842, "s": 3824, "text": "npm install nexmo" }, { "code": null, "e": 3894, "s": 3842, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 3908, "s": 3894, "text": "node index.js" }, { "code": null, "e": 3967, "s": 3908, "text": "If error occurs, then following message will be displayed:" }, { "code": null, "e": 3980, "s": 3967, "text": "Node.js-Misc" }, { "code": null, "e": 4004, "s": 3980, "text": "Technical Scripter 2019" }, { "code": null, "e": 4012, "s": 4004, "text": "Node.js" }, { "code": null, "e": 4031, "s": 4012, "text": "Technical Scripter" }, { "code": null, "e": 4048, "s": 4031, "text": "Web Technologies" }, { "code": null, "e": 4146, "s": 4048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4178, "s": 4146, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 4213, "s": 4178, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 4283, "s": 4213, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 4310, "s": 4283, "text": "Mongoose Populate() Method" }, { "code": null, "e": 4335, "s": 4310, "text": "Mongoose find() Function" }, { "code": null, "e": 4397, "s": 4335, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4458, "s": 4397, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4508, "s": 4458, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4551, "s": 4508, "text": "How to fetch data from an API in ReactJS ?" } ]
Smallest subset with sum greater than all other elements
09 Apr, 2021 Given an array of non-negative integers. Our task is to find minimum number of elements such that their sum should be greater than the sum of rest of the elements of the array.Examples : Input : arr[] = {3, 1, 7, 1} Output : 1 Smallest subset is {7}. Sum of this subset is greater than all other elements {3, 1, 1} Input : arr[] = {2, 1, 2} Output : 2 In this example one element is not enough. We can pick elements with values 1, 2 or 2, 2. In any case, the minimum count is 2. The Brute force approach is to find the sum of all the possible subsets and then compare sum with the sum of remaining elements.The Efficient Approach is to take the largest elements. We sort values in descending order, then take elements from the largest, until we get strictly more than half of total sum of the given array. C++ Java Python3 C# PHP Javascript // CPP program to find minimum number of// elements such that their sum is greater// than sum of remaining elements of the array.#include <bits/stdc++.h>#include <string.h>using namespace std; // function to find minimum elements needed.int minElements(int arr[], int n){ // calculating HALF of array sum int halfSum = 0; for (int i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = halfSum / 2; // sort the array in descending order. sort(arr, arr + n, greater<int>()); int res = 0, curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; res++; // current sum greater than sum if (curr_sum > halfSum) return res; } return res;} // Driver functionint main(){ int arr[] = {3, 1, 7, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << minElements(arr, n) << endl; return 0;} // Java code to find minimum number of elements// such that their sum is greater than sum of// remaining elements of the array.import java.io.*;import java.util.*; class GFG { // Function to find minimum elements needed static int minElements(int arr[], int n) { // Calculating HALF of array sum int halfSum = 0; for (int i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = halfSum / 2; // Sort the array in ascending order and // start traversing array from the ascending // sort in descending order. Arrays.sort(arr); int res = 0, curr_sum = 0; for (int i = n-1; i >= 0; i--) { curr_sum += arr[i]; res++; // Current sum greater than sum if (curr_sum > halfSum) return res; } return res; } // Driver Code public static void main (String[] args) { int arr[] = {3, 1, 7, 1}; int n = arr.length; System.out.println(minElements(arr, n)); } } // This code is contributed by Gitanjali # Python3 code to find minimum number of# elements such that their sum is greater# than sum of remaining elements of the array. # function to find minimum elements needed.def minElements(arr , n): # calculating HALF of array sum halfSum = 0 for i in range(n): halfSum = halfSum + arr[i] halfSum = int(halfSum / 2) # sort the array in descending order. arr.sort(reverse = True) res = 0 curr_sum = 0 for i in range(n): curr_sum += arr[i] res += 1 # current sum greater than sum if curr_sum > halfSum: return res return res # driver codearr = [3, 1, 7, 1]n = len(arr)print(minElements(arr, n) ) # This code is contributed by "Sharad_Bhardwaj". // C# code to find minimum number of elements// such that their sum is greater than sum of// remaining elements of the array.using System; class GFG { // Function to find minimum elements needed static int minElements(int []arr, int n) { // Calculating HALF of array sum int halfSum = 0; for (int i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = halfSum / 2; // Sort the array in ascending order and // start traversing array from the ascending // sort in descending order. Array.Sort(arr); int res = 0, curr_sum = 0; for (int i = n-1; i >= 0; i--) { curr_sum += arr[i]; res++; // Current sum greater than sum if (curr_sum > halfSum) return res; } return res; } // Driver Code public static void Main () { int []arr = {3, 1, 7, 1}; int n = arr.Length; Console.WriteLine(minElements(arr, n)); }} // This code is contributed by vt_m. <?php// PHP program to find minimum number// of elements such that their sum is// greater than sum of remaining// elements of the array. // function to find minimum elements needed.function minElements($arr, $n){ // calculating HALF of array sum $halfSum = 0; for ($i = 0; $i < $n; $i++) $halfSum = $halfSum + $arr[$i]; $halfSum = $halfSum / 2; // sort the array in descending order. rsort($arr); $res = 0; $curr_sum = 0; for ($i = 0; $i < $n; $i++) { $curr_sum += $arr[$i]; $res++; // current sum greater than sum if ($curr_sum > $halfSum) return $res; } return $res;} // Driver Code$arr = array(3, 1, 7, 1);$n = sizeof($arr);echo minElements($arr, $n); // This code is contributed by ihritik?> <script> // Javascript program to find minimum number of // elements such that their sum is greater // than sum of remaining elements of the array. // function to find minimum elements needed. function minElements(arr, n) { // calculating HALF of array sum let halfSum = 0; for (let i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = parseInt(halfSum / 2, 10); // sort the array in descending order. arr.sort(function(a, b){return a - b}); arr.reverse(); let res = 0, curr_sum = 0; for (let i = 0; i < n; i++) { curr_sum += arr[i]; res++; // current sum greater than sum if (curr_sum > halfSum) return res; } return res; } let arr = [3, 1, 7, 1]; let n = arr.length; document.write(minElements(arr, n)); // This code is contributed by divyeshrabadiya07.</script> Output: 1 Time Complexity : O(n Log n) ihritik nidhi_biet divyeshrabadiya07 Arrays Greedy Sorting Arrays Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Program for array rotation Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Minimum Number of Platforms Required for a Railway/Bus Station
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Apr, 2021" }, { "code": null, "e": 241, "s": 52, "text": "Given an array of non-negative integers. Our task is to find minimum number of elements such that their sum should be greater than the sum of rest of the elements of the array.Examples : " }, { "code": null, "e": 537, "s": 241, "text": "Input : arr[] = {3, 1, 7, 1}\nOutput : 1\nSmallest subset is {7}. Sum of\nthis subset is greater than all\nother elements {3, 1, 1}\n\nInput : arr[] = {2, 1, 2}\nOutput : 2\nIn this example one element is not \nenough. We can pick elements with \nvalues 1, 2 or 2, 2. In any case, \nthe minimum count is 2." }, { "code": null, "e": 868, "s": 539, "text": "The Brute force approach is to find the sum of all the possible subsets and then compare sum with the sum of remaining elements.The Efficient Approach is to take the largest elements. We sort values in descending order, then take elements from the largest, until we get strictly more than half of total sum of the given array. " }, { "code": null, "e": 872, "s": 868, "text": "C++" }, { "code": null, "e": 877, "s": 872, "text": "Java" }, { "code": null, "e": 885, "s": 877, "text": "Python3" }, { "code": null, "e": 888, "s": 885, "text": "C#" }, { "code": null, "e": 892, "s": 888, "text": "PHP" }, { "code": null, "e": 903, "s": 892, "text": "Javascript" }, { "code": "// CPP program to find minimum number of// elements such that their sum is greater// than sum of remaining elements of the array.#include <bits/stdc++.h>#include <string.h>using namespace std; // function to find minimum elements needed.int minElements(int arr[], int n){ // calculating HALF of array sum int halfSum = 0; for (int i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = halfSum / 2; // sort the array in descending order. sort(arr, arr + n, greater<int>()); int res = 0, curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; res++; // current sum greater than sum if (curr_sum > halfSum) return res; } return res;} // Driver functionint main(){ int arr[] = {3, 1, 7, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << minElements(arr, n) << endl; return 0;}", "e": 1791, "s": 903, "text": null }, { "code": "// Java code to find minimum number of elements// such that their sum is greater than sum of// remaining elements of the array.import java.io.*;import java.util.*; class GFG { // Function to find minimum elements needed static int minElements(int arr[], int n) { // Calculating HALF of array sum int halfSum = 0; for (int i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = halfSum / 2; // Sort the array in ascending order and // start traversing array from the ascending // sort in descending order. Arrays.sort(arr); int res = 0, curr_sum = 0; for (int i = n-1; i >= 0; i--) { curr_sum += arr[i]; res++; // Current sum greater than sum if (curr_sum > halfSum) return res; } return res; } // Driver Code public static void main (String[] args) { int arr[] = {3, 1, 7, 1}; int n = arr.length; System.out.println(minElements(arr, n)); } } // This code is contributed by Gitanjali", "e": 2926, "s": 1791, "text": null }, { "code": "# Python3 code to find minimum number of# elements such that their sum is greater# than sum of remaining elements of the array. # function to find minimum elements needed.def minElements(arr , n): # calculating HALF of array sum halfSum = 0 for i in range(n): halfSum = halfSum + arr[i] halfSum = int(halfSum / 2) # sort the array in descending order. arr.sort(reverse = True) res = 0 curr_sum = 0 for i in range(n): curr_sum += arr[i] res += 1 # current sum greater than sum if curr_sum > halfSum: return res return res # driver codearr = [3, 1, 7, 1]n = len(arr)print(minElements(arr, n) ) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 3678, "s": 2926, "text": null }, { "code": "// C# code to find minimum number of elements// such that their sum is greater than sum of// remaining elements of the array.using System; class GFG { // Function to find minimum elements needed static int minElements(int []arr, int n) { // Calculating HALF of array sum int halfSum = 0; for (int i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = halfSum / 2; // Sort the array in ascending order and // start traversing array from the ascending // sort in descending order. Array.Sort(arr); int res = 0, curr_sum = 0; for (int i = n-1; i >= 0; i--) { curr_sum += arr[i]; res++; // Current sum greater than sum if (curr_sum > halfSum) return res; } return res; } // Driver Code public static void Main () { int []arr = {3, 1, 7, 1}; int n = arr.Length; Console.WriteLine(minElements(arr, n)); }} // This code is contributed by vt_m.", "e": 4808, "s": 3678, "text": null }, { "code": "<?php// PHP program to find minimum number// of elements such that their sum is// greater than sum of remaining// elements of the array. // function to find minimum elements needed.function minElements($arr, $n){ // calculating HALF of array sum $halfSum = 0; for ($i = 0; $i < $n; $i++) $halfSum = $halfSum + $arr[$i]; $halfSum = $halfSum / 2; // sort the array in descending order. rsort($arr); $res = 0; $curr_sum = 0; for ($i = 0; $i < $n; $i++) { $curr_sum += $arr[$i]; $res++; // current sum greater than sum if ($curr_sum > $halfSum) return $res; } return $res;} // Driver Code$arr = array(3, 1, 7, 1);$n = sizeof($arr);echo minElements($arr, $n); // This code is contributed by ihritik?>", "e": 5606, "s": 4808, "text": null }, { "code": "<script> // Javascript program to find minimum number of // elements such that their sum is greater // than sum of remaining elements of the array. // function to find minimum elements needed. function minElements(arr, n) { // calculating HALF of array sum let halfSum = 0; for (let i = 0; i < n; i++) halfSum = halfSum + arr[i]; halfSum = parseInt(halfSum / 2, 10); // sort the array in descending order. arr.sort(function(a, b){return a - b}); arr.reverse(); let res = 0, curr_sum = 0; for (let i = 0; i < n; i++) { curr_sum += arr[i]; res++; // current sum greater than sum if (curr_sum > halfSum) return res; } return res; } let arr = [3, 1, 7, 1]; let n = arr.length; document.write(minElements(arr, n)); // This code is contributed by divyeshrabadiya07.</script>", "e": 6585, "s": 5606, "text": null }, { "code": null, "e": 6595, "s": 6585, "text": "Output: " }, { "code": null, "e": 6597, "s": 6595, "text": "1" }, { "code": null, "e": 6627, "s": 6597, "text": "Time Complexity : O(n Log n) " }, { "code": null, "e": 6635, "s": 6627, "text": "ihritik" }, { "code": null, "e": 6646, "s": 6635, "text": "nidhi_biet" }, { "code": null, "e": 6664, "s": 6646, "text": "divyeshrabadiya07" }, { "code": null, "e": 6671, "s": 6664, "text": "Arrays" }, { "code": null, "e": 6678, "s": 6671, "text": "Greedy" }, { "code": null, "e": 6686, "s": 6678, "text": "Sorting" }, { "code": null, "e": 6693, "s": 6686, "text": "Arrays" }, { "code": null, "e": 6700, "s": 6693, "text": "Greedy" }, { "code": null, "e": 6708, "s": 6700, "text": "Sorting" }, { "code": null, "e": 6806, "s": 6708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6821, "s": 6806, "text": "Arrays in Java" }, { "code": null, "e": 6867, "s": 6821, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6935, "s": 6867, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6979, "s": 6935, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7011, "s": 6979, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 7038, "s": 7011, "text": "Program for array rotation" }, { "code": null, "e": 7098, "s": 7038, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7117, "s": 7098, "text": "Coin Change | DP-7" }, { "code": null, "e": 7198, "s": 7117, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" } ]
RUN vs CMD vs Entrypoint in Docker
The commands RUN, CMD and Entrypoint usually cause a lot of confusion among docker developers. Understanding all the three commands conceptually will help to have a clearer understanding of the same. When we try to build an image using dockerfile, the instructions are executed step by step. The first instruction is usually pulling a base image such as an OS distribution like ubuntu, centos etc. After that, we modify the base image either by including more images using FROM and AS commands or by modifying the images. Every such instruction creates a new intermediate image build and for each of them, caches are created. The final docker image can be considered as a layered structure where there is a core or a base image and on top of that, there are several layered intermediate images. To understand all these three commands in depth, we first need to understand what are shell and exec forms. This form is generally used for Entrypoint and CMD commands. It is of the form - <instruction> [“executable”, “parameter”, “parameter”, ....] When we execute an instruction in such a form, shell processing does not happen and the executable is called directly. Consider the commands below. RUN [“apt-get”, “install”, “vim”] ENTRYPOINT [“/bin/echo”, “TutorialsPoint”] CMD [“/bin/echo”, “TutorialsPoint”] If we write a dockerfile with the following instructions, ENV variable TutorialsPoint ENTRYPOINT [“/bin/echo”, “$variable”] When we try to run the image, the following output is generated. $variable When we try to execute an instruction using the shell form, normal shell processing takes place. It calls the command /bin/sh -c {command} behind the scenes. It is of the form - <Your instruction> <the command> Consider the commands below. RUN apt-get -y update CMD echo “TutorialsPoint” ENTRYPOINT echo “TutorialsPoint” The following dockerfile - ENV variable TutorialsPoint ENTRYPOINT echo “$variable” will output - TutorialsPoint Now that we have understood the two forms in-depth, let us continue with the three commands. The RUN command always gets executed in a new layer. It allows you to install packages and applications on top of an existing image layer and creates a new layer on top of it. It can be written in both shell and exec forms. Examples include - RUN apt-get -y update (shell form) RUN [“apt-get”, “install”, “vim”] (exec form) Using a CMD command, you will be able to set a default command. This will be executed if you run a particular container without specifying some command. In case you specify a command while running a docker container, the default one will be ignored. Note that if you specify more than one CMD instruction in your dockerfile, only the last one will be executed. Following are the different ways, through which you can execute a CMD command. CMD <command> parameter1, parameter2 .... (Shell form) CMD <command> parameter1, parameter2 .... (Shell form) CMD [“executable command”, “parameter1”, “parameter2”, ....] (executable form) CMD [“executable command”, “parameter1”, “parameter2”, ....] (executable form) CMD [“parameter1”, “parameter2”] CMD [“parameter1”, “parameter2”] The third way is used to set some additional default parameters that will be inserted after the default parameters when you are using an ENTRYPOINT in executable form and if you run the container without specifying any arguments in the command line. Consider the command below inside a dockerfile. CMD echo “TutorialsPoint” The output if you run it without specifying arguments (docker run -it image_name) will be - TutorialsPoint If you run it by specifying CLI arguments (docker run -it image_name /bin/bash), it will simply open a bash. It looks similar to a CMD command. However, the difference is that it does not ignore the parameters when you run a container with CLI parameters. The two forms of ENTRYPOINT command are - ENTRYPOINT <command> parameter1, parameter2, ... (It is shell form) ENTRYPOINT <command> parameter1, parameter2, ... (It is shell form) ENTRYPOINT [“executable command”, “parameter1”, “parameter2”, ....] (Executable form) ENTRYPOINT [“executable command”, “parameter1”, “parameter2”, ....] (Executable form) When you use an executable form of ENTRYPOINT command, it will allow you to set additional parameters using CMD command. If you use it in shell form, it will ignore CMD parameters or any CLI arguments. Consider the example below. ENTRYPOINT [“/bin/echo”, “TutorialsPoint”] CMD [“Docker”] If you try to run the container without specifying any CLI arguments (docker run -it image_name), output will be - TutorialsPoint Docker If you try to run the container without specifying any CLI arguments (docker run -it image_name), output will be - TutorialsPoint Docker If you specify CLI arguments (docker run -it image_name DockerTutorials), output will be - TutorialsPoint DockerTutorials. If you specify CLI arguments (docker run -it image_name DockerTutorials), output will be - TutorialsPoint DockerTutorials. To conclude, if you want to specify default arguments and want it to be overwritten on specifying CLI arguments, use CMD commands. And if you want to run a container with the condition that a particular command is always executed, use ENTRYPOINT. RUN is simply used to build additional image layers over the base image.
[ { "code": null, "e": 1387, "s": 1187, "text": "The commands RUN, CMD and Entrypoint usually cause a lot of confusion among docker developers. Understanding all the three commands conceptually will help to have a clearer understanding of the same." }, { "code": null, "e": 1982, "s": 1387, "text": "When we try to build an image using dockerfile, the instructions are executed step by step. The first instruction is usually pulling a base image such as an OS distribution like ubuntu, centos etc. After that, we modify the base image either by including more images using FROM and AS commands or by modifying the images. Every such instruction creates a new intermediate image build and for each of them, caches are created. The final docker image can be considered as a layered structure where there is a core or a base image and on top of that, there are several layered intermediate images." }, { "code": null, "e": 2090, "s": 1982, "text": "To understand all these three commands in depth, we first need to understand what are shell and exec forms." }, { "code": null, "e": 2171, "s": 2090, "text": "This form is generally used for Entrypoint and CMD commands. It is of the form -" }, { "code": null, "e": 2232, "s": 2171, "text": "<instruction> [“executable”, “parameter”, “parameter”, ....]" }, { "code": null, "e": 2351, "s": 2232, "text": "When we execute an instruction in such a form, shell processing does not happen and the executable is called directly." }, { "code": null, "e": 2380, "s": 2351, "text": "Consider the commands below." }, { "code": null, "e": 2493, "s": 2380, "text": "RUN [“apt-get”, “install”, “vim”]\nENTRYPOINT [“/bin/echo”, “TutorialsPoint”]\nCMD [“/bin/echo”, “TutorialsPoint”]" }, { "code": null, "e": 2551, "s": 2493, "text": "If we write a dockerfile with the following instructions," }, { "code": null, "e": 2617, "s": 2551, "text": "ENV variable TutorialsPoint\nENTRYPOINT [“/bin/echo”, “$variable”]" }, { "code": null, "e": 2682, "s": 2617, "text": "When we try to run the image, the following output is generated." }, { "code": null, "e": 2692, "s": 2682, "text": "$variable" }, { "code": null, "e": 2850, "s": 2692, "text": "When we try to execute an instruction using the shell form, normal shell processing takes place. It calls the command /bin/sh -c {command} behind the scenes." }, { "code": null, "e": 2903, "s": 2850, "text": "It is of the form - <Your instruction> <the command>" }, { "code": null, "e": 2932, "s": 2903, "text": "Consider the commands below." }, { "code": null, "e": 3013, "s": 2932, "text": "RUN apt-get -y update\nCMD echo “TutorialsPoint”\nENTRYPOINT echo “TutorialsPoint”" }, { "code": null, "e": 3040, "s": 3013, "text": "The following dockerfile -" }, { "code": null, "e": 3096, "s": 3040, "text": "ENV variable TutorialsPoint\nENTRYPOINT echo “$variable”" }, { "code": null, "e": 3110, "s": 3096, "text": "will output -" }, { "code": null, "e": 3125, "s": 3110, "text": "TutorialsPoint" }, { "code": null, "e": 3218, "s": 3125, "text": "Now that we have understood the two forms in-depth, let us continue with the three commands." }, { "code": null, "e": 3394, "s": 3218, "text": "The RUN command always gets executed in a new layer. It allows you to install packages and applications on top of an existing image layer and creates a new layer on top of it." }, { "code": null, "e": 3461, "s": 3394, "text": "It can be written in both shell and exec forms. Examples include -" }, { "code": null, "e": 3542, "s": 3461, "text": "RUN apt-get -y update (shell form)\nRUN [“apt-get”, “install”, “vim”] (exec form)" }, { "code": null, "e": 3903, "s": 3542, "text": "Using a CMD command, you will be able to set a default command. This will be executed if you run a particular container without specifying some command. In case you specify a command while running a docker container, the default one will be ignored. Note that if you specify more than one CMD instruction in your dockerfile, only the last one will be executed." }, { "code": null, "e": 3982, "s": 3903, "text": "Following are the different ways, through which you can execute a CMD command." }, { "code": null, "e": 4037, "s": 3982, "text": "CMD <command> parameter1, parameter2 .... (Shell form)" }, { "code": null, "e": 4092, "s": 4037, "text": "CMD <command> parameter1, parameter2 .... (Shell form)" }, { "code": null, "e": 4171, "s": 4092, "text": "CMD [“executable command”, “parameter1”, “parameter2”, ....] (executable form)" }, { "code": null, "e": 4250, "s": 4171, "text": "CMD [“executable command”, “parameter1”, “parameter2”, ....] (executable form)" }, { "code": null, "e": 4283, "s": 4250, "text": "CMD [“parameter1”, “parameter2”]" }, { "code": null, "e": 4316, "s": 4283, "text": "CMD [“parameter1”, “parameter2”]" }, { "code": null, "e": 4566, "s": 4316, "text": "The third way is used to set some additional default parameters that will be inserted after the default parameters when you are using an ENTRYPOINT in executable form and if you run the container without specifying any arguments in the command line." }, { "code": null, "e": 4614, "s": 4566, "text": "Consider the command below inside a dockerfile." }, { "code": null, "e": 4640, "s": 4614, "text": "CMD echo “TutorialsPoint”" }, { "code": null, "e": 4732, "s": 4640, "text": "The output if you run it without specifying arguments (docker run -it image_name) will be -" }, { "code": null, "e": 4747, "s": 4732, "text": "TutorialsPoint" }, { "code": null, "e": 4856, "s": 4747, "text": "If you run it by specifying CLI arguments (docker run -it image_name /bin/bash), it will simply open a bash." }, { "code": null, "e": 5045, "s": 4856, "text": "It looks similar to a CMD command. However, the difference is that it does not ignore the parameters when you run a container with CLI parameters. The two forms of ENTRYPOINT command are -" }, { "code": null, "e": 5113, "s": 5045, "text": "ENTRYPOINT <command> parameter1, parameter2, ... (It is shell form)" }, { "code": null, "e": 5181, "s": 5113, "text": "ENTRYPOINT <command> parameter1, parameter2, ... (It is shell form)" }, { "code": null, "e": 5267, "s": 5181, "text": "ENTRYPOINT [“executable command”, “parameter1”, “parameter2”, ....] (Executable form)" }, { "code": null, "e": 5353, "s": 5267, "text": "ENTRYPOINT [“executable command”, “parameter1”, “parameter2”, ....] (Executable form)" }, { "code": null, "e": 5555, "s": 5353, "text": "When you use an executable form of ENTRYPOINT command, it will allow you to set additional parameters using CMD command. If you use it in shell form, it will ignore CMD parameters or any CLI arguments." }, { "code": null, "e": 5583, "s": 5555, "text": "Consider the example below." }, { "code": null, "e": 5641, "s": 5583, "text": "ENTRYPOINT [“/bin/echo”, “TutorialsPoint”]\nCMD [“Docker”]" }, { "code": null, "e": 5778, "s": 5641, "text": "If you try to run the container without specifying any CLI arguments (docker run -it image_name), output will be - TutorialsPoint Docker" }, { "code": null, "e": 5915, "s": 5778, "text": "If you try to run the container without specifying any CLI arguments (docker run -it image_name), output will be - TutorialsPoint Docker" }, { "code": null, "e": 6038, "s": 5915, "text": "If you specify CLI arguments (docker run -it image_name DockerTutorials), output will be - TutorialsPoint DockerTutorials." }, { "code": null, "e": 6161, "s": 6038, "text": "If you specify CLI arguments (docker run -it image_name DockerTutorials), output will be - TutorialsPoint DockerTutorials." }, { "code": null, "e": 6481, "s": 6161, "text": "To conclude, if you want to specify default arguments and want it to be overwritten on specifying CLI arguments, use CMD commands. And if you want to run a container with the condition that a particular command is always executed, use ENTRYPOINT. RUN is simply used to build additional image layers over the base image." } ]
Program to print number with star pattern
04 Jun, 2022 We have to print the pattern as given in the below example.Examples : Input : 5 Output : 1 1*2 1*2*3 1*2 1 Input : 9 Output : 1 1*2 1*2*3 1*2*3*4 1*2*3*4*5 1*2*3*4 1*2*3 1*2 1 C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // C++ program to print above patternvoid display(int n){ // 'sp' used for space and 'st' used for star int sp = n / 2, st = 1; // Outer for loop prints number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= sp; j++) { cout << " "; } int count = 1; for (int k = 1; k <= st; k++) { if (k % 2 == 0) cout << "*"; else cout << count++; } cout << "\n"; if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } }} // Driver Codeint main(){ int n = 5; display(n); return 0;} // This code is contributed by vt_m // Java program to print above patternimport java.util.Scanner;class Pattern{ void display(int n) { // 'sp' used for space and 'st' used for star int sp = n / 2, st = 1; // Outer for loop prints number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= sp; j++) { System.out.print(" "); } int count = 1; for (int k = 1; k <= st; k++) { if (k % 2 == 0) System.out.print("*"); else System.out.print(count++); } System.out.println(); if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } } } // Driver Code public static void main(String[] args) { int n = 5; Pattern p = new Pattern(); p.display(n); }} # Python3 program to print above pattern def display(n): # 'sp' used for space and # 'st' used for star sp = n // 2 st = 1 # Outer for loop prints number # of lines for i in range(1, n + 1): for j in range(1, sp + 1): print(end = " ") count = 1 for k in range(1, st + 1): if (k % 2 == 0): print("*", end = "") else: print(count, end = "") count += 1 print() if (i <= n // 2): # Before reaching to half after # every line space is decreased # by 1 and star is increased by 2 sp = sp - 1 st = st + 2 else: # After reaching to half # space is increased by 1 # and star is decreased by 2 sp = sp + 1 st = st - 2 # Driver Coden = 5display(n) # This code is contributed by# Mohit kumar 29 // C# program to print above patternusing System;class Pattern{ void display(int n) { // 'sp' used for space and 'st' used for star int sp = n / 2, st = 1; // Outer for loop prints number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= sp; j++) { Console.Write(" "); } int count = 1; for (int k = 1; k <= st; k++) { if (k % 2 == 0) Console.Write("*"); else Console.Write(count++); } Console.WriteLine(); if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } } } // Driver Code public static void Main() { int n = 5; Pattern p = new Pattern(); p.display(n); }}//This code is contributed by vt_m. <?php// php program to print// above pattern function display($n){ // 'sp' used for space and // 'st' used for star $sp = $n / 2; $st = 1; // Outer for loop prints // number of lines for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $sp; $j++) { echo " "; } $count = 1; for ($k = 1; $k <= $st; $k++) { if ($k % 2 == 0) echo "*"; else echo $count++; } echo "\n"; if ($i <= $n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 $sp = $sp - 1; $st = $st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 $sp = $sp + 1; $st = $st - 2; } }} // Driver Code$n = 5;display($n); // This code is contributed by mits?> <script> // JavaScript program to print above pattern function display(n) { // 'sp' used for space and 'st' used for star var sp = n / 2, st = 1; // Outer for loop prints number of lines for (var i = 1; i <= n; i++) { for (var j = 1; j <= sp; j++) { document.write(" "); } var count = 1; for (var k = 1; k <= st; k++) { if (k % 2 == 0) document.write("*"); else document.write(count++); } document.write("<br>"); if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } } } // Driver Code var n = 5; display(n); </script> Output: 1 1*2 1*2*3 1*2 1 Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant. Mithun Kumar mohit kumar 29 srinam rdtank samim2000 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction To PYTHON Interfaces in Java C++ Classes and Objects C++ Data Types Operator Overloading in C++ Polymorphism in C++ Types of Operating Systems Constructors in C++ Constructors in Java Exceptions in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jun, 2022" }, { "code": null, "e": 123, "s": 52, "text": "We have to print the pattern as given in the below example.Examples : " }, { "code": null, "e": 256, "s": 123, "text": "Input : 5\nOutput :\n 1\n 1*2\n1*2*3\n 1*2\n 1\n\nInput : 9\nOutput :\n 1\n 1*2\n 1*2*3\n 1*2*3*4\n1*2*3*4*5\n 1*2*3*4\n 1*2*3\n 1*2\n 1" }, { "code": null, "e": 264, "s": 260, "text": "C++" }, { "code": null, "e": 269, "s": 264, "text": "Java" }, { "code": null, "e": 277, "s": 269, "text": "Python3" }, { "code": null, "e": 280, "s": 277, "text": "C#" }, { "code": null, "e": 284, "s": 280, "text": "PHP" }, { "code": null, "e": 295, "s": 284, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // C++ program to print above patternvoid display(int n){ // 'sp' used for space and 'st' used for star int sp = n / 2, st = 1; // Outer for loop prints number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= sp; j++) { cout << \" \"; } int count = 1; for (int k = 1; k <= st; k++) { if (k % 2 == 0) cout << \"*\"; else cout << count++; } cout << \"\\n\"; if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } }} // Driver Codeint main(){ int n = 5; display(n); return 0;} // This code is contributed by vt_m", "e": 1366, "s": 295, "text": null }, { "code": "// Java program to print above patternimport java.util.Scanner;class Pattern{ void display(int n) { // 'sp' used for space and 'st' used for star int sp = n / 2, st = 1; // Outer for loop prints number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= sp; j++) { System.out.print(\" \"); } int count = 1; for (int k = 1; k <= st; k++) { if (k % 2 == 0) System.out.print(\"*\"); else System.out.print(count++); } System.out.println(); if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } } } // Driver Code public static void main(String[] args) { int n = 5; Pattern p = new Pattern(); p.display(n); }}", "e": 2699, "s": 1366, "text": null }, { "code": "# Python3 program to print above pattern def display(n): # 'sp' used for space and # 'st' used for star sp = n // 2 st = 1 # Outer for loop prints number # of lines for i in range(1, n + 1): for j in range(1, sp + 1): print(end = \" \") count = 1 for k in range(1, st + 1): if (k % 2 == 0): print(\"*\", end = \"\") else: print(count, end = \"\") count += 1 print() if (i <= n // 2): # Before reaching to half after # every line space is decreased # by 1 and star is increased by 2 sp = sp - 1 st = st + 2 else: # After reaching to half # space is increased by 1 # and star is decreased by 2 sp = sp + 1 st = st - 2 # Driver Coden = 5display(n) # This code is contributed by# Mohit kumar 29", "e": 3689, "s": 2699, "text": null }, { "code": "// C# program to print above patternusing System;class Pattern{ void display(int n) { // 'sp' used for space and 'st' used for star int sp = n / 2, st = 1; // Outer for loop prints number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= sp; j++) { Console.Write(\" \"); } int count = 1; for (int k = 1; k <= st; k++) { if (k % 2 == 0) Console.Write(\"*\"); else Console.Write(count++); } Console.WriteLine(); if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } } } // Driver Code public static void Main() { int n = 5; Pattern p = new Pattern(); p.display(n); }}//This code is contributed by vt_m.", "e": 5028, "s": 3689, "text": null }, { "code": "<?php// php program to print// above pattern function display($n){ // 'sp' used for space and // 'st' used for star $sp = $n / 2; $st = 1; // Outer for loop prints // number of lines for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $sp; $j++) { echo \" \"; } $count = 1; for ($k = 1; $k <= $st; $k++) { if ($k % 2 == 0) echo \"*\"; else echo $count++; } echo \"\\n\"; if ($i <= $n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 $sp = $sp - 1; $st = $st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 $sp = $sp + 1; $st = $st - 2; } }} // Driver Code$n = 5;display($n); // This code is contributed by mits?>", "e": 6077, "s": 5028, "text": null }, { "code": "<script> // JavaScript program to print above pattern function display(n) { // 'sp' used for space and 'st' used for star var sp = n / 2, st = 1; // Outer for loop prints number of lines for (var i = 1; i <= n; i++) { for (var j = 1; j <= sp; j++) { document.write(\" \"); } var count = 1; for (var k = 1; k <= st; k++) { if (k % 2 == 0) document.write(\"*\"); else document.write(count++); } document.write(\"<br>\"); if (i <= n / 2) { // Before reaching to half after // every line space is decreased // by 1 and star is increased by 2 sp = sp - 1; st = st + 2; } else { // After reaching to half // space is increased by 1 // and star is decreased by 2 sp = sp + 1; st = st - 2; } } } // Driver Code var n = 5; display(n); </script>", "e": 7174, "s": 6077, "text": null }, { "code": null, "e": 7183, "s": 7174, "text": "Output: " }, { "code": null, "e": 7207, "s": 7183, "text": " 1\n 1*2\n1*2*3\n 1*2\n 1" }, { "code": null, "e": 7338, "s": 7207, "text": "Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 7351, "s": 7338, "text": "Mithun Kumar" }, { "code": null, "e": 7366, "s": 7351, "text": "mohit kumar 29" }, { "code": null, "e": 7373, "s": 7366, "text": "srinam" }, { "code": null, "e": 7380, "s": 7373, "text": "rdtank" }, { "code": null, "e": 7390, "s": 7380, "text": "samim2000" }, { "code": null, "e": 7407, "s": 7390, "text": "pattern-printing" }, { "code": null, "e": 7426, "s": 7407, "text": "School Programming" }, { "code": null, "e": 7443, "s": 7426, "text": "pattern-printing" }, { "code": null, "e": 7541, "s": 7443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7564, "s": 7541, "text": "Introduction To PYTHON" }, { "code": null, "e": 7583, "s": 7564, "text": "Interfaces in Java" }, { "code": null, "e": 7607, "s": 7583, "text": "C++ Classes and Objects" }, { "code": null, "e": 7622, "s": 7607, "text": "C++ Data Types" }, { "code": null, "e": 7650, "s": 7622, "text": "Operator Overloading in C++" }, { "code": null, "e": 7670, "s": 7650, "text": "Polymorphism in C++" }, { "code": null, "e": 7697, "s": 7670, "text": "Types of Operating Systems" }, { "code": null, "e": 7717, "s": 7697, "text": "Constructors in C++" }, { "code": null, "e": 7738, "s": 7717, "text": "Constructors in Java" } ]
Difference between Steganography and Cryptography
08 Jun, 2020 1. Steganography:Steganography is a method in which secret message is hidden in a cover media. Steganography means covered writing. Steganography is the idea to prevent secret information by creating the suspicion. Steganography is less popular than Cryptography. In steganography, structure of data is not usually altered.The forms of steganography are: 1. Text 2. Audio 3. Video 4. Images 5. Network or Protocol 2. Cryptography:Cryptography means secret writing. In cryptography, sender does not send message directly to the receiver, before sending information to the receiver information or plain text is converted into cipher text by using some encryption algorithm then send to the receiver and receiver decrypt the cipher text into plain text to read the original information.It is of two types: 1. Symmetric key cryptography 2. Asymmetric key cryptography The difference between Steganography and Cryptography: swetha_vazhakkat Computer Networks Difference Between GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 383, "s": 28, "text": "1. Steganography:Steganography is a method in which secret message is hidden in a cover media. Steganography means covered writing. Steganography is the idea to prevent secret information by creating the suspicion. Steganography is less popular than Cryptography. In steganography, structure of data is not usually altered.The forms of steganography are:" }, { "code": null, "e": 444, "s": 383, "text": "1. Text\n2. Audio\n3. Video\n4. Images\n5. Network or Protocol\n " }, { "code": null, "e": 833, "s": 444, "text": "2. Cryptography:Cryptography means secret writing. In cryptography, sender does not send message directly to the receiver, before sending information to the receiver information or plain text is converted into cipher text by using some encryption algorithm then send to the receiver and receiver decrypt the cipher text into plain text to read the original information.It is of two types:" }, { "code": null, "e": 895, "s": 833, "text": "1. Symmetric key cryptography\n2. Asymmetric key cryptography " }, { "code": null, "e": 950, "s": 895, "text": "The difference between Steganography and Cryptography:" }, { "code": null, "e": 967, "s": 950, "text": "swetha_vazhakkat" }, { "code": null, "e": 985, "s": 967, "text": "Computer Networks" }, { "code": null, "e": 1004, "s": 985, "text": "Difference Between" }, { "code": null, "e": 1012, "s": 1004, "text": "GATE CS" }, { "code": null, "e": 1030, "s": 1012, "text": "Computer Networks" } ]
Change the x or y ticks of a Matplotlib figure
29 Oct, 2021 Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module. There are many ways to change the interval of ticks of axes of a plot of Matplotlib. Some of the easiest of them are discussed here. The xticks() and yticks() function takes a list object as an argument. The elements in the list denote the positions of the corresponding action where ticks will be displayed. We can also set labels of the ticks of the axes using these functions, but, here we will focus only on changing the interval of ticks of axes. To know more about these functions click on xticks() and yticks(). Syntax : For x-axis : matplotlib.pyplot.xticks() For y-axis : matplotlib.pyplot.yticks() To create a list of ticks, we will use numpy.arange(start, stop, step) with start as the starting value for the ticks, stop as the non-inclusive ending value and step as the integer space between ticks. Below example illustrate the matplotlib.pyplot.xticks() and matplotlib.pyplot.yticks() methods: Example : Python3 # Code to change the interval of ticks of axes using xticks() and yticks() # Importing librariesimport matplotlib.pyplot as pltimport numpy as np #Creating x-value and y-value of datax = [5, 10, 15, 20]y = [10, 20, 30, 40] # Plotting the dataplt.plot(x, y) # Setting the interval of ticks of x-axis to 5.listOf_Xticks = np.arange(0, 25, 5)plt.xticks(listOf_Xticks) # Setting the interval of ticks of y-axis to 10.listOf_Yticks = np.arange(0, 50, 10)plt.yticks(listOf_Yticks) # Giving title to the plotplt.title('matplotlib.pyplot.xticks() and matplotlib.pyplot.yticks() Example') plt.show() Output : Here we can see that the range of ticks on x-axis is [0, 25) with an interval of 5 and on the y-axis is [0, 50) with an interval of 10. This is what we have set as the argument of np.arange(). Note: The above function (i.e. xticks() and yticks()) will not work for AxesSubplot object. For this, the below methods will work. Similar to the above method, set_ticks() also takes a list object as an argument whose elements denote the position of ticks on the axis. Syntax : For x-axis : AxesSubplot.xaxis.set_ticks() For y-axis : AxesSubplot.yaxis.set_ticks() Note: This method will not work for matplotlib.pyplot object. Below example illustrate the AxesSubplot.xaxis.set_ticks() and AxesSubplot.yaxis.set_ticks() methods: Example : Python3 # Code to change the interval of ticks of axes# using set_ticks() method # Importing librariesimport matplotlib.pyplot as pltimport numpy as np # Creating x-value and y-value of datax = [1, 2, 3, 4]y = [0.1, 0.2, 0.3, 0.4] # Creating a subplot with 2 row and 1 columnfig, (axes1, axes2) = plt.subplots(2, 1) # Plotting first axes object i.e. axes1 and labeling# its x and y axesaxes1.plot(x, y)axes1.set_ylabel('y-axis')axes1.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 1 and of y-axis# to 0.1 of first axes i.e. axes1.axes1.xaxis.set_ticks(np.arange(0, 5, 1))axes1.yaxis.set_ticks(np.arange(0, 0.5, 0.1)) # Plotting first axes object i.e. axes1 and labeling its# x and y axesaxes2.plot(x, y)axes2.set_ylabel('y-axis')axes2.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 0.5 and# of y-axis to 0.05 of second axes i.e. axes2.axes2.xaxis.set_ticks(np.arange(0, 4.5, 0.5))axes2.yaxis.set_ticks(np.arange(0, 0.45, 0.05)) # Giving title to the figure object i.e. figfig.suptitle('set_ticks() Example')fig.tight_layout(pad=3.0) plt.show() Output : The set_xticks() and set_yticks() functions takes a list object as an argument. The elements in the list denote the positions of the corresponding action where ticks will be displayed. Syntax : For x-axis : AxesSubplot.set_xticks() For y-axis : AxesSubplot.set_yticks() Note: This method will not work for matplotlib.pyplot object. Below example illustrate the AxesSubplot.set_xticks() and AxesSubplot.set_yticks() methods: Example : Python3 # Code to change the interval of ticks of axes# using set_xticks() and set_yticks() methods # Importing librariesimport matplotlib.pyplot as pltimport numpy as np #Creating x-value and y-value of datax = [1, 2, 3, 4]y = [0.1, 0.2, 0.3, 0.4] # Creating a subplot with 2 row and 1 columnfig, (axes1, axes2) = plt.subplots(2, 1) # Plotting first axes object i.e. axes1 and# labeling its x and y axesaxes1.plot(x, y)axes1.set_ylabel('y-axis')axes1.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 1 and of# y-axis to 0.1 of first axes i.e. axes1.axes1.set_xticks(np.arange(0, 5, 1))axes1.set_yticks(np.arange(0, 0.5, 0.1)) # Plotting first axes object i.e. axes1 and labeling# its x and y axesaxes2.plot(x, y)axes2.set_ylabel('y-axis')axes2.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 0.5 and# of y-axis to 0.05 of second axes i.e. axes2.axes2.set_xticks(np.arange(0, 4.5, 0.5))axes2.set_yticks(np.arange(0, 0.45, 0.05)) #Giving title to the figure object i.e. figfig.suptitle('set_xticks() and set_yticks() Example')fig.tight_layout(pad=3.0) plt.show() Output : sweetyty rajeev0719singh Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Oct, 2021" }, { "code": null, "e": 329, "s": 53, "text": "Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module." }, { "code": null, "e": 462, "s": 329, "text": "There are many ways to change the interval of ticks of axes of a plot of Matplotlib. Some of the easiest of them are discussed here." }, { "code": null, "e": 848, "s": 462, "text": "The xticks() and yticks() function takes a list object as an argument. The elements in the list denote the positions of the corresponding action where ticks will be displayed. We can also set labels of the ticks of the axes using these functions, but, here we will focus only on changing the interval of ticks of axes. To know more about these functions click on xticks() and yticks()." }, { "code": null, "e": 857, "s": 848, "text": "Syntax :" }, { "code": null, "e": 897, "s": 857, "text": "For x-axis : matplotlib.pyplot.xticks()" }, { "code": null, "e": 937, "s": 897, "text": "For y-axis : matplotlib.pyplot.yticks()" }, { "code": null, "e": 1140, "s": 937, "text": "To create a list of ticks, we will use numpy.arange(start, stop, step) with start as the starting value for the ticks, stop as the non-inclusive ending value and step as the integer space between ticks." }, { "code": null, "e": 1236, "s": 1140, "text": "Below example illustrate the matplotlib.pyplot.xticks() and matplotlib.pyplot.yticks() methods:" }, { "code": null, "e": 1246, "s": 1236, "text": "Example :" }, { "code": null, "e": 1254, "s": 1246, "text": "Python3" }, { "code": "# Code to change the interval of ticks of axes using xticks() and yticks() # Importing librariesimport matplotlib.pyplot as pltimport numpy as np #Creating x-value and y-value of datax = [5, 10, 15, 20]y = [10, 20, 30, 40] # Plotting the dataplt.plot(x, y) # Setting the interval of ticks of x-axis to 5.listOf_Xticks = np.arange(0, 25, 5)plt.xticks(listOf_Xticks) # Setting the interval of ticks of y-axis to 10.listOf_Yticks = np.arange(0, 50, 10)plt.yticks(listOf_Yticks) # Giving title to the plotplt.title('matplotlib.pyplot.xticks() and matplotlib.pyplot.yticks() Example') plt.show()", "e": 1846, "s": 1254, "text": null }, { "code": null, "e": 1855, "s": 1846, "text": "Output :" }, { "code": null, "e": 2048, "s": 1855, "text": "Here we can see that the range of ticks on x-axis is [0, 25) with an interval of 5 and on the y-axis is [0, 50) with an interval of 10. This is what we have set as the argument of np.arange()." }, { "code": null, "e": 2179, "s": 2048, "text": "Note: The above function (i.e. xticks() and yticks()) will not work for AxesSubplot object. For this, the below methods will work." }, { "code": null, "e": 2317, "s": 2179, "text": "Similar to the above method, set_ticks() also takes a list object as an argument whose elements denote the position of ticks on the axis." }, { "code": null, "e": 2327, "s": 2317, "text": "Syntax : " }, { "code": null, "e": 2340, "s": 2327, "text": "For x-axis :" }, { "code": null, "e": 2370, "s": 2340, "text": "AxesSubplot.xaxis.set_ticks()" }, { "code": null, "e": 2383, "s": 2370, "text": "For y-axis :" }, { "code": null, "e": 2413, "s": 2383, "text": "AxesSubplot.yaxis.set_ticks()" }, { "code": null, "e": 2475, "s": 2413, "text": "Note: This method will not work for matplotlib.pyplot object." }, { "code": null, "e": 2577, "s": 2475, "text": "Below example illustrate the AxesSubplot.xaxis.set_ticks() and AxesSubplot.yaxis.set_ticks() methods:" }, { "code": null, "e": 2587, "s": 2577, "text": "Example :" }, { "code": null, "e": 2595, "s": 2587, "text": "Python3" }, { "code": "# Code to change the interval of ticks of axes# using set_ticks() method # Importing librariesimport matplotlib.pyplot as pltimport numpy as np # Creating x-value and y-value of datax = [1, 2, 3, 4]y = [0.1, 0.2, 0.3, 0.4] # Creating a subplot with 2 row and 1 columnfig, (axes1, axes2) = plt.subplots(2, 1) # Plotting first axes object i.e. axes1 and labeling# its x and y axesaxes1.plot(x, y)axes1.set_ylabel('y-axis')axes1.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 1 and of y-axis# to 0.1 of first axes i.e. axes1.axes1.xaxis.set_ticks(np.arange(0, 5, 1))axes1.yaxis.set_ticks(np.arange(0, 0.5, 0.1)) # Plotting first axes object i.e. axes1 and labeling its# x and y axesaxes2.plot(x, y)axes2.set_ylabel('y-axis')axes2.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 0.5 and# of y-axis to 0.05 of second axes i.e. axes2.axes2.xaxis.set_ticks(np.arange(0, 4.5, 0.5))axes2.yaxis.set_ticks(np.arange(0, 0.45, 0.05)) # Giving title to the figure object i.e. figfig.suptitle('set_ticks() Example')fig.tight_layout(pad=3.0) plt.show()", "e": 3679, "s": 2595, "text": null }, { "code": null, "e": 3688, "s": 3679, "text": "Output :" }, { "code": null, "e": 3873, "s": 3688, "text": "The set_xticks() and set_yticks() functions takes a list object as an argument. The elements in the list denote the positions of the corresponding action where ticks will be displayed." }, { "code": null, "e": 3882, "s": 3873, "text": "Syntax :" }, { "code": null, "e": 3895, "s": 3882, "text": "For x-axis :" }, { "code": null, "e": 3920, "s": 3895, "text": "AxesSubplot.set_xticks()" }, { "code": null, "e": 3933, "s": 3920, "text": "For y-axis :" }, { "code": null, "e": 3958, "s": 3933, "text": "AxesSubplot.set_yticks()" }, { "code": null, "e": 4020, "s": 3958, "text": "Note: This method will not work for matplotlib.pyplot object." }, { "code": null, "e": 4112, "s": 4020, "text": "Below example illustrate the AxesSubplot.set_xticks() and AxesSubplot.set_yticks() methods:" }, { "code": null, "e": 4122, "s": 4112, "text": "Example :" }, { "code": null, "e": 4130, "s": 4122, "text": "Python3" }, { "code": "# Code to change the interval of ticks of axes# using set_xticks() and set_yticks() methods # Importing librariesimport matplotlib.pyplot as pltimport numpy as np #Creating x-value and y-value of datax = [1, 2, 3, 4]y = [0.1, 0.2, 0.3, 0.4] # Creating a subplot with 2 row and 1 columnfig, (axes1, axes2) = plt.subplots(2, 1) # Plotting first axes object i.e. axes1 and# labeling its x and y axesaxes1.plot(x, y)axes1.set_ylabel('y-axis')axes1.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 1 and of# y-axis to 0.1 of first axes i.e. axes1.axes1.set_xticks(np.arange(0, 5, 1))axes1.set_yticks(np.arange(0, 0.5, 0.1)) # Plotting first axes object i.e. axes1 and labeling# its x and y axesaxes2.plot(x, y)axes2.set_ylabel('y-axis')axes2.set_xlabel('x-axis') # Setting the interval of ticks of x-axis to 0.5 and# of y-axis to 0.05 of second axes i.e. axes2.axes2.set_xticks(np.arange(0, 4.5, 0.5))axes2.set_yticks(np.arange(0, 0.45, 0.05)) #Giving title to the figure object i.e. figfig.suptitle('set_xticks() and set_yticks() Example')fig.tight_layout(pad=3.0) plt.show()", "e": 5229, "s": 4130, "text": null }, { "code": null, "e": 5238, "s": 5229, "text": "Output :" }, { "code": null, "e": 5247, "s": 5238, "text": "sweetyty" }, { "code": null, "e": 5263, "s": 5247, "text": "rajeev0719singh" }, { "code": null, "e": 5281, "s": 5263, "text": "Python-matplotlib" }, { "code": null, "e": 5288, "s": 5281, "text": "Python" }, { "code": null, "e": 5386, "s": 5288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5404, "s": 5386, "text": "Python Dictionary" }, { "code": null, "e": 5446, "s": 5404, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5468, "s": 5446, "text": "Enumerate() in Python" }, { "code": null, "e": 5503, "s": 5468, "text": "Read a file line by line in Python" }, { "code": null, "e": 5529, "s": 5503, "text": "Python String | replace()" }, { "code": null, "e": 5561, "s": 5529, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5590, "s": 5561, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5617, "s": 5590, "text": "Python Classes and Objects" }, { "code": null, "e": 5647, "s": 5617, "text": "Iterate over a list in Python" } ]
How to Build a TODO Android Application with AWS DynamoDB as Database?
04 Feb, 2021 This is a TODO application made on android studio IDE, code is written in JAVA, and data store in AWS DynamoDB and fetch to the home screen. The connection established between the application and AWS through Amplify CLI and the data is successful gets stored by creating a TODO Table in DynamoDB, a Schema is also created which shows the structure of data. The data fetched successfully and displayed on the home page of the application. The aim of this project is to show how to connect your android applications with AWS and use the AWS resources(DynamoDB). A sample video is given below to get an idea about what we are going to do in this article. Before jumping to the implementation have a look at the following terms. Amplify CLI: Amplify Command Line Interface (CLI) is a combined toolchain to create, integrate, and manage the AWS cloud services/resources for your application. DynamoDB: It is a fast and flexible NoSQL database. It is a fully managed database that helps you with both document and key-value data models. Prerequisite: Install Node.js (version 10.x) install NPM (version 6.x), create an AWS account if you don’t have one, install android studio (version 4.0 or higher), android SDK API level 29(android 10), install amplify CLI (write following on the command prompt). npm install -g @aws-amplify/cli Step 1: Write the following on the command prompt amplify configure Install Amplify Step 2: If you have already created an IAM user then write “Do you want to use an AWS profile? Yes” and then write below its accessKeyId and secretAccessKey otherwise write “Do you want to use an AWS profile? No” create an IAM user and use its accessKeyId and secretAccessKey. Configure Amplify Give permissions User created Step 3: Write the following in order to initialize the new Amplify project amplify init Initialize Amplify Step 4: Create backend API by using GraphQL query language then use “amplify publish” to deploy it amplify add api amplify push amplify publish Add API to your backend Step 1: Add the following in the dependencies of build.gradle (Project: Todo) in Gradle Scripts buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.1.1' // Add this line into `dependencies` in `buildscript` classpath 'com.amplifyframework:amplify-tools-gradle-plugin:1.0.2' } } allprojects { repositories { google() jcenter() } } // Add this line at the end of the file apply plugin: 'com.amplifyframework.amplifytools' Step 2: Add the following in the dependencies of build.gradle (Module: app) in Gradle Scripts. Run Gradle Sync dependencies { implementation 'com.amplifyframework:aws-api:1.6.9' implementation 'com.amplifyframework:aws-datastore:1.6.9' } Step 3: In android studio go to Project -> amplify -> app -> backend -> api -> schema.graphql type Todo @model { id: ID! name: String! description: String } Step 4: Add the following code in MainActivity & MainActivity2 in the onCreate() method to initialize Amplify try { Amplify.addPlugin(new AWSDataStorePlugin()); Amplify.configure(getApplicationContext()); Log.i("Tutorial", "Initialized Amplify"); } catch (AmplifyException e) { Log.e("Tutorial", "Could not initialize Amplify", e); } Step 5: Add the following code in MainActivity2 in the onCreate() method to creates a Todo item with two properties: a name and a description Todo todo = Todo.builder() .name(name1) .description(name2) .build(); Step 6: Add the following code in MainActivity2 in the onCreate() method to save items using mutate Amplify.API.mutate( ModelMutation.create(todo), response -> Log.i("MyAmplifyApp", "Added Todo with id: " + response.getData().getId()), error -> Log.e("MyAmplifyApp", "Create failed", error) ); Go to your AWS management console -> AppSync -> Select your API -> Data Sources -> select todo table -> items Data successfully stored Step 7: Add the following code in MainActivity in the onCreate() method to fetch data/run queries to retrieve the stored data Amplify.API.query( ModelQuery.list(Todo.class), response -> { for (Todo todo : response.getData()) { ls.add(todo.getName()); Log.i("MyAmplifyApp", todo.getName()); } }, error -> Log.e("MyAmplifyApp", "Query failure", error) ); MainActivity file(Home page of App) XML Java <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/lt" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> </ListView> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="221dp" android:layout_height="53dp" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:layout_marginEnd="25dp" android:layout_marginRight="25dp" android:layout_marginBottom="70dp" android:clickable="true" app:srcCompat="@android:drawable/ic_input_add" /> </RelativeLayout> package com.example.shreyaawsapp; import android.content.Intent;import android.os.AsyncTask;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.amplifyframework.AmplifyException;import com.amplifyframework.api.aws.AWSApiPlugin;import com.amplifyframework.api.graphql.model.ModelQuery;import com.amplifyframework.core.Amplify;import com.amplifyframework.datastore.generated.model.Todo;import com.google.android.material.floatingactionbutton.FloatingActionButton;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // declaration public FloatingActionButton btn; public ListView lv; public String[] st; int i = 0; Handler handler; // the array adapter converts an ArrayList of objects // into View items filled into the ListView container ArrayAdapter<String> arrayAdapter; // list to store data public static List<String> ls; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // provide id to the layout items btn = findViewById(R.id.fab); st = new String[100]; lv = findViewById(R.id.lt); // set listener to the floating button which takes // you to the next activity where you add and sore // your data btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MainActivity2.class); startActivity(intent); } }); ls = new ArrayList<String>(); // add the code below to initialize Amplpify try { // Add these lines to add the AWSApiPlugin plugins Amplify.addPlugin(new AWSApiPlugin()); Amplify.configure(getApplicationContext()); Log.i("MyAmplifyApp", "Initialized Amplify"); } catch (AmplifyException error) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error); } // add the code below to fetch // data/run queries to // retrieve the stored data Amplify.API.query(ModelQuery.list(Todo.class), response -> { for (Todo todo : response.getData()) { ls.add(todo.getName()); Log.i("MyAmplifyApp", todo.getName()); } }, error -> Log.e("MyAmplifyApp", "Query failure", error)); handler = new Handler(); final Runnable r = new Runnable() { public void run() { handler.postDelayed(this, 2000); arrayAdapter = new ArrayAdapter<String>( getApplicationContext(), android.R.layout.simple_list_item_1, ls); lv.setAdapter(arrayAdapter); arrayAdapter.notifyDataSetChanged(); } }; handler.postDelayed(r, 1000); }} MainActivity2 file(Write notes page) XML Java <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity2"> <EditText android:id="@+id/edname" android:layout_width="347dp" android:layout_height="54dp" android:layout_marginTop="110dp" android:ems="10" android:hint="Title" android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/eddes" android:layout_width="347dp" android:layout_height="54dp" android:layout_marginTop="216dp" android:ems="10" android:inputType="textPersonName" android:hint="Description" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button2" android:layout_width="134dp" android:layout_height="53dp" android:layout_marginStart="138dp" android:layout_marginTop="69dp" android:layout_marginEnd="138dp" android:text="Store in data" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/eddes" /> </androidx.constraintlayout.widget.ConstraintLayout> package com.example.shreyaawsapp; import android.content.Intent;import android.net.wifi.p2p.WifiP2pManager;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.amplifyframework.AmplifyException;import com.amplifyframework.api.aws.AWSApiPlugin;import com.amplifyframework.api.graphql.model.ModelMutation;import com.amplifyframework.api.graphql.model.ModelQuery;import com.amplifyframework.core.Amplify;import com.amplifyframework.datastore.generated.model.Todo;import java.util.ArrayList;import java.util.List; public class MainActivity2 extends AppCompatActivity { // declaration public EditText name, desc; public Button btn; @Override protected void onCreate(Bundle savedInstanceState) { // give id to the items super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); name = findViewById(R.id.edname); desc = findViewById(R.id.eddes); btn = findViewById(R.id.button2); // add the code below to initialize Amplify try { // Add these lines to add the AWSApiPlugin plugins Amplify.addPlugin(new AWSApiPlugin()); Amplify.configure(getApplicationContext()); Log.i("MyAmplifyApp", "Initialized Amplify"); } catch (AmplifyException error) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error); } // set listener on the store data button to store // data in dynamoDB btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name1 = name.getText().toString(); String name2 = desc.getText().toString(); // add the code below to create a toto item // with two properties a name and a // description Todo todo = Todo.builder() .name(name1) .description(name2) .build(); // add the code below to save item using mutate Amplify.API.mutate(ModelMutation.create(todo), response -> Log.i( "MyAmplifyApp", "Added Todo with id: " + response.getData().getId()), error -> Log.e("MyAmplifyApp", "Create failed", error)); } }); } // move to the next activity @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(MainActivity2.this, MainActivity.class)); }} Source Code: https://github.com/shreya593/Shreyaawsapp.git 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": 52, "s": 24, "text": "\n04 Feb, 2021" }, { "code": null, "e": 704, "s": 52, "text": "This is a TODO application made on android studio IDE, code is written in JAVA, and data store in AWS DynamoDB and fetch to the home screen. The connection established between the application and AWS through Amplify CLI and the data is successful gets stored by creating a TODO Table in DynamoDB, a Schema is also created which shows the structure of data. The data fetched successfully and displayed on the home page of the application. The aim of this project is to show how to connect your android applications with AWS and use the AWS resources(DynamoDB). A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 777, "s": 704, "text": "Before jumping to the implementation have a look at the following terms." }, { "code": null, "e": 941, "s": 777, "text": "Amplify CLI: Amplify Command Line Interface (CLI) is a combined toolchain to create, integrate, and manage the AWS cloud services/resources for your application. " }, { "code": null, "e": 1085, "s": 941, "text": "DynamoDB: It is a fast and flexible NoSQL database. It is a fully managed database that helps you with both document and key-value data models." }, { "code": null, "e": 1349, "s": 1085, "text": "Prerequisite: Install Node.js (version 10.x) install NPM (version 6.x), create an AWS account if you don’t have one, install android studio (version 4.0 or higher), android SDK API level 29(android 10), install amplify CLI (write following on the command prompt)." }, { "code": null, "e": 1381, "s": 1349, "text": "npm install -g @aws-amplify/cli" }, { "code": null, "e": 1431, "s": 1381, "text": "Step 1: Write the following on the command prompt" }, { "code": null, "e": 1449, "s": 1431, "text": "amplify configure" }, { "code": null, "e": 1465, "s": 1449, "text": "Install Amplify" }, { "code": null, "e": 1742, "s": 1465, "text": "Step 2: If you have already created an IAM user then write “Do you want to use an AWS profile? Yes” and then write below its accessKeyId and secretAccessKey otherwise write “Do you want to use an AWS profile? No” create an IAM user and use its accessKeyId and secretAccessKey." }, { "code": null, "e": 1760, "s": 1742, "text": "Configure Amplify" }, { "code": null, "e": 1777, "s": 1760, "text": "Give permissions" }, { "code": null, "e": 1790, "s": 1777, "text": "User created" }, { "code": null, "e": 1865, "s": 1790, "text": "Step 3: Write the following in order to initialize the new Amplify project" }, { "code": null, "e": 1878, "s": 1865, "text": "amplify init" }, { "code": null, "e": 1897, "s": 1878, "text": "Initialize Amplify" }, { "code": null, "e": 1996, "s": 1897, "text": "Step 4: Create backend API by using GraphQL query language then use “amplify publish” to deploy it" }, { "code": null, "e": 2012, "s": 1996, "text": "amplify add api" }, { "code": null, "e": 2025, "s": 2012, "text": "amplify push" }, { "code": null, "e": 2041, "s": 2025, "text": "amplify publish" }, { "code": null, "e": 2065, "s": 2041, "text": "Add API to your backend" }, { "code": null, "e": 2161, "s": 2065, "text": "Step 1: Add the following in the dependencies of build.gradle (Project: Todo) in Gradle Scripts" }, { "code": null, "e": 2613, "s": 2161, "text": "buildscript {\n repositories {\n google()\n jcenter()\n }\n\n dependencies {\n classpath 'com.android.tools.build:gradle:4.1.1'\n\n // Add this line into `dependencies` in `buildscript`\n classpath 'com.amplifyframework:amplify-tools-gradle-plugin:1.0.2'\n }\n}\n\nallprojects {\n repositories {\n google()\n jcenter()\n }\n}\n\n// Add this line at the end of the file\napply plugin: 'com.amplifyframework.amplifytools'" }, { "code": null, "e": 2724, "s": 2613, "text": "Step 2: Add the following in the dependencies of build.gradle (Module: app) in Gradle Scripts. Run Gradle Sync" }, { "code": null, "e": 2859, "s": 2724, "text": "dependencies {\n implementation 'com.amplifyframework:aws-api:1.6.9'\n implementation 'com.amplifyframework:aws-datastore:1.6.9'\n}" }, { "code": null, "e": 2953, "s": 2859, "text": "Step 3: In android studio go to Project -> amplify -> app -> backend -> api -> schema.graphql" }, { "code": null, "e": 3022, "s": 2953, "text": "type Todo @model {\n id: ID!\n name: String!\n description: String\n}" }, { "code": null, "e": 3132, "s": 3022, "text": "Step 4: Add the following code in MainActivity & MainActivity2 in the onCreate() method to initialize Amplify" }, { "code": null, "e": 3380, "s": 3132, "text": " try {\n Amplify.addPlugin(new AWSDataStorePlugin());\n Amplify.configure(getApplicationContext());\n\n Log.i(\"Tutorial\", \"Initialized Amplify\");\n } catch (AmplifyException e) {\n Log.e(\"Tutorial\", \"Could not initialize Amplify\", e);\n }" }, { "code": null, "e": 3523, "s": 3380, "text": "Step 5: Add the following code in MainActivity2 in the onCreate() method to creates a Todo item with two properties: a name and a description" }, { "code": null, "e": 3666, "s": 3523, "text": " Todo todo = Todo.builder()\n .name(name1)\n .description(name2)\n .build();" }, { "code": null, "e": 3766, "s": 3666, "text": "Step 6: Add the following code in MainActivity2 in the onCreate() method to save items using mutate" }, { "code": null, "e": 4040, "s": 3766, "text": " Amplify.API.mutate(\n ModelMutation.create(todo),\n response -> Log.i(\"MyAmplifyApp\", \"Added Todo with id: \" + response.getData().getId()),\n error -> Log.e(\"MyAmplifyApp\", \"Create failed\", error)\n );" }, { "code": null, "e": 4150, "s": 4040, "text": "Go to your AWS management console -> AppSync -> Select your API -> Data Sources -> select todo table -> items" }, { "code": null, "e": 4175, "s": 4150, "text": "Data successfully stored" }, { "code": null, "e": 4302, "s": 4175, "text": "Step 7: Add the following code in MainActivity in the onCreate() method to fetch data/run queries to retrieve the stored data" }, { "code": null, "e": 4690, "s": 4302, "text": " Amplify.API.query(\n ModelQuery.list(Todo.class),\n response -> {\n for (Todo todo : response.getData()) {\n ls.add(todo.getName());\n Log.i(\"MyAmplifyApp\", todo.getName());\n }\n },\n error -> Log.e(\"MyAmplifyApp\", \"Query failure\", error)\n );" }, { "code": null, "e": 4726, "s": 4690, "text": "MainActivity file(Home page of App)" }, { "code": null, "e": 4730, "s": 4726, "text": "XML" }, { "code": null, "e": 4735, "s": 4730, "text": "Java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ListView android:id=\"@+id/lt\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> </ListView> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id=\"@+id/fab\" android:layout_width=\"221dp\" android:layout_height=\"53dp\" android:layout_alignParentRight=\"true\" android:layout_alignParentBottom=\"true\" android:layout_marginEnd=\"25dp\" android:layout_marginRight=\"25dp\" android:layout_marginBottom=\"70dp\" android:clickable=\"true\" app:srcCompat=\"@android:drawable/ic_input_add\" /> </RelativeLayout>", "e": 5871, "s": 4735, "text": null }, { "code": "package com.example.shreyaawsapp; import android.content.Intent;import android.os.AsyncTask;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.amplifyframework.AmplifyException;import com.amplifyframework.api.aws.AWSApiPlugin;import com.amplifyframework.api.graphql.model.ModelQuery;import com.amplifyframework.core.Amplify;import com.amplifyframework.datastore.generated.model.Todo;import com.google.android.material.floatingactionbutton.FloatingActionButton;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // declaration public FloatingActionButton btn; public ListView lv; public String[] st; int i = 0; Handler handler; // the array adapter converts an ArrayList of objects // into View items filled into the ListView container ArrayAdapter<String> arrayAdapter; // list to store data public static List<String> ls; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // provide id to the layout items btn = findViewById(R.id.fab); st = new String[100]; lv = findViewById(R.id.lt); // set listener to the floating button which takes // you to the next activity where you add and sore // your data btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MainActivity2.class); startActivity(intent); } }); ls = new ArrayList<String>(); // add the code below to initialize Amplpify try { // Add these lines to add the AWSApiPlugin plugins Amplify.addPlugin(new AWSApiPlugin()); Amplify.configure(getApplicationContext()); Log.i(\"MyAmplifyApp\", \"Initialized Amplify\"); } catch (AmplifyException error) { Log.e(\"MyAmplifyApp\", \"Could not initialize Amplify\", error); } // add the code below to fetch // data/run queries to // retrieve the stored data Amplify.API.query(ModelQuery.list(Todo.class), response -> { for (Todo todo : response.getData()) { ls.add(todo.getName()); Log.i(\"MyAmplifyApp\", todo.getName()); } }, error -> Log.e(\"MyAmplifyApp\", \"Query failure\", error)); handler = new Handler(); final Runnable r = new Runnable() { public void run() { handler.postDelayed(this, 2000); arrayAdapter = new ArrayAdapter<String>( getApplicationContext(), android.R.layout.simple_list_item_1, ls); lv.setAdapter(arrayAdapter); arrayAdapter.notifyDataSetChanged(); } }; handler.postDelayed(r, 1000); }}", "e": 9189, "s": 5871, "text": null }, { "code": null, "e": 9226, "s": 9189, "text": "MainActivity2 file(Write notes page)" }, { "code": null, "e": 9230, "s": 9226, "text": "XML" }, { "code": null, "e": 9235, "s": 9230, "text": "Java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity2\"> <EditText android:id=\"@+id/edname\" android:layout_width=\"347dp\" android:layout_height=\"54dp\" android:layout_marginTop=\"110dp\" android:ems=\"10\" android:hint=\"Title\" android:inputType=\"textPersonName\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <EditText android:id=\"@+id/eddes\" android:layout_width=\"347dp\" android:layout_height=\"54dp\" android:layout_marginTop=\"216dp\" android:ems=\"10\" android:inputType=\"textPersonName\" android:hint=\"Description\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/button2\" android:layout_width=\"134dp\" android:layout_height=\"53dp\" android:layout_marginStart=\"138dp\" android:layout_marginTop=\"69dp\" android:layout_marginEnd=\"138dp\" android:text=\"Store in data\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/eddes\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 10915, "s": 9235, "text": null }, { "code": "package com.example.shreyaawsapp; import android.content.Intent;import android.net.wifi.p2p.WifiP2pManager;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.amplifyframework.AmplifyException;import com.amplifyframework.api.aws.AWSApiPlugin;import com.amplifyframework.api.graphql.model.ModelMutation;import com.amplifyframework.api.graphql.model.ModelQuery;import com.amplifyframework.core.Amplify;import com.amplifyframework.datastore.generated.model.Todo;import java.util.ArrayList;import java.util.List; public class MainActivity2 extends AppCompatActivity { // declaration public EditText name, desc; public Button btn; @Override protected void onCreate(Bundle savedInstanceState) { // give id to the items super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); name = findViewById(R.id.edname); desc = findViewById(R.id.eddes); btn = findViewById(R.id.button2); // add the code below to initialize Amplify try { // Add these lines to add the AWSApiPlugin plugins Amplify.addPlugin(new AWSApiPlugin()); Amplify.configure(getApplicationContext()); Log.i(\"MyAmplifyApp\", \"Initialized Amplify\"); } catch (AmplifyException error) { Log.e(\"MyAmplifyApp\", \"Could not initialize Amplify\", error); } // set listener on the store data button to store // data in dynamoDB btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name1 = name.getText().toString(); String name2 = desc.getText().toString(); // add the code below to create a toto item // with two properties a name and a // description Todo todo = Todo.builder() .name(name1) .description(name2) .build(); // add the code below to save item using mutate Amplify.API.mutate(ModelMutation.create(todo), response -> Log.i( \"MyAmplifyApp\", \"Added Todo with id: \" + response.getData().getId()), error -> Log.e(\"MyAmplifyApp\", \"Create failed\", error)); } }); } // move to the next activity @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(MainActivity2.this, MainActivity.class)); }}", "e": 13723, "s": 10915, "text": null }, { "code": null, "e": 13782, "s": 13723, "text": "Source Code: https://github.com/shreya593/Shreyaawsapp.git" }, { "code": null, "e": 13790, "s": 13782, "text": "android" }, { "code": null, "e": 13814, "s": 13790, "text": "Technical Scripter 2020" }, { "code": null, "e": 13822, "s": 13814, "text": "Android" }, { "code": null, "e": 13827, "s": 13822, "text": "Java" }, { "code": null, "e": 13846, "s": 13827, "text": "Technical Scripter" }, { "code": null, "e": 13851, "s": 13846, "text": "Java" }, { "code": null, "e": 13859, "s": 13851, "text": "Android" } ]
Python | Using variable outside and inside the class and method
18 May, 2020 In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let’s see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable name. # Program to demonstrate 'Variable # defined outside the class' # Variable defined outside the class.outVar = 'outside_class' print("Outside_class1", outVar) ''' Class one '''class Geek: print("Outside_class2", outVar) def access_method(self): print("Outside_class3", outVar) # Calling method by creating objectuac = Geek()uac.access_method() ''' Class two '''class Another_Geek_class: print("Outside_class4", outVar) def another_access_method(self): print("Outside_class5", outVar) # Calling method by creating objectuaac = Another_Geek_class()uaac.another_access_method() Outside_class1 outside_class Outside_class2 outside_class Outside_class3 outside_class Outside_class4 outside_class Outside_class5 outside_class Variable defined inside the class: The variables that are defined inside the class but outside the method can be accessed within the class(all methods included) using the instance of a class. For Example – self.var_name.If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. # Program to demonstrate 'Variable # defined inside the class' # print("Inside_class1", inVar) # Error ''' Class one'''class Geek: # Variable defined inside the class. inVar = 'inside_class' print("Inside_class2", inVar) def access_method(self): print("Inside_class3", self.inVar) uac = Geek()uac.access_method() ''' Class two '''class another_Geek_class: print()# print("Inside_class4", inVar) # Error def another_access_method(self): print()# print("Inside_class5", inVar) # Error uaac = another_Geek_class()uaac.another_access_method() Inside_class2 inside_class Inside_class3 inside_class The statements which are marked as error will produce an error upon execution as the variable is not accessible there. Variable defined inside the method: The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name.If you want to use that variable outside the method or class, you have to declared that variable as a global. # Program to demonstrate 'Variable # defined inside the method' # print("Inside_method1", inVar) # Error '''class one'''class Geek: print()# print("Inside_method2", inVar) # Error def access_method(self): # Variable defined inside the method. inVar = 'inside_method' print("Inside_method3", inVar) uac = Geek()uac.access_method() '''class two'''class AnotherGeek: print()# print("Inside_method4", inVar) # Error def access_method(self): print()# print("Inside_method5", inVar) # Error uaac = AnotherGeek()uaac.access_method() Inside_method3 inside_method The statements which are marked as error will produce error upon execution as the variable is not accessible there. Summary: albertvoneinstein python-basics python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2020" }, { "code": null, "e": 205, "s": 28, "text": "In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let’s see, how to use and access these variables throughout the program." }, { "code": null, "e": 241, "s": 205, "text": "Variable defined outside the class:" }, { "code": null, "e": 382, "s": 241, "text": "The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable name." }, { "code": "# Program to demonstrate 'Variable # defined outside the class' # Variable defined outside the class.outVar = 'outside_class' print(\"Outside_class1\", outVar) ''' Class one '''class Geek: print(\"Outside_class2\", outVar) def access_method(self): print(\"Outside_class3\", outVar) # Calling method by creating objectuac = Geek()uac.access_method() ''' Class two '''class Another_Geek_class: print(\"Outside_class4\", outVar) def another_access_method(self): print(\"Outside_class5\", outVar) # Calling method by creating objectuaac = Another_Geek_class()uaac.another_access_method()", "e": 995, "s": 382, "text": null }, { "code": null, "e": 1141, "s": 995, "text": "Outside_class1 outside_class\nOutside_class2 outside_class\nOutside_class3 outside_class\nOutside_class4 outside_class\nOutside_class5 outside_class\n" }, { "code": null, "e": 1177, "s": 1141, "text": " Variable defined inside the class:" }, { "code": null, "e": 1583, "s": 1177, "text": "The variables that are defined inside the class but outside the method can be accessed within the class(all methods included) using the instance of a class. For Example – self.var_name.If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class." }, { "code": "# Program to demonstrate 'Variable # defined inside the class' # print(\"Inside_class1\", inVar) # Error ''' Class one'''class Geek: # Variable defined inside the class. inVar = 'inside_class' print(\"Inside_class2\", inVar) def access_method(self): print(\"Inside_class3\", self.inVar) uac = Geek()uac.access_method() ''' Class two '''class another_Geek_class: print()# print(\"Inside_class4\", inVar) # Error def another_access_method(self): print()# print(\"Inside_class5\", inVar) # Error uaac = another_Geek_class()uaac.another_access_method()", "e": 2165, "s": 1583, "text": null }, { "code": null, "e": 2220, "s": 2165, "text": "Inside_class2 inside_class\nInside_class3 inside_class\n" }, { "code": null, "e": 2339, "s": 2220, "text": "The statements which are marked as error will produce an error upon execution as the variable is not accessible there." }, { "code": null, "e": 2376, "s": 2339, "text": " Variable defined inside the method:" }, { "code": null, "e": 2630, "s": 2376, "text": "The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name.If you want to use that variable outside the method or class, you have to declared that variable as a global." }, { "code": "# Program to demonstrate 'Variable # defined inside the method' # print(\"Inside_method1\", inVar) # Error '''class one'''class Geek: print()# print(\"Inside_method2\", inVar) # Error def access_method(self): # Variable defined inside the method. inVar = 'inside_method' print(\"Inside_method3\", inVar) uac = Geek()uac.access_method() '''class two'''class AnotherGeek: print()# print(\"Inside_method4\", inVar) # Error def access_method(self): print()# print(\"Inside_method5\", inVar) # Error uaac = AnotherGeek()uaac.access_method()", "e": 3207, "s": 2630, "text": null }, { "code": null, "e": 3237, "s": 3207, "text": "Inside_method3 inside_method\n" }, { "code": null, "e": 3353, "s": 3237, "text": "The statements which are marked as error will produce error upon execution as the variable is not accessible there." }, { "code": null, "e": 3362, "s": 3353, "text": "Summary:" }, { "code": null, "e": 3380, "s": 3362, "text": "albertvoneinstein" }, { "code": null, "e": 3394, "s": 3380, "text": "python-basics" }, { "code": null, "e": 3414, "s": 3394, "text": "python-oop-concepts" }, { "code": null, "e": 3421, "s": 3414, "text": "Python" }, { "code": null, "e": 3519, "s": 3421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3537, "s": 3519, "text": "Python Dictionary" }, { "code": null, "e": 3579, "s": 3537, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3601, "s": 3579, "text": "Enumerate() in Python" }, { "code": null, "e": 3636, "s": 3601, "text": "Read a file line by line in Python" }, { "code": null, "e": 3662, "s": 3636, "text": "Python String | replace()" }, { "code": null, "e": 3694, "s": 3662, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3723, "s": 3694, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3750, "s": 3723, "text": "Python Classes and Objects" }, { "code": null, "e": 3771, "s": 3750, "text": "Python OOPs Concepts" } ]
NumPy in Python | Set 1 (Introduction)
06 May, 2022 This article will help you get acquainted with the widely used array-processing library in Python, NumPy. What is NumPy? NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is open-source software. It contains various features including these important ones: A powerful N-dimensional array object Sophisticated (broadcasting) functions Tools for integrating C/C++ and Fortran code Useful linear algebra, Fourier transform, and random number capabilities Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined using Numpy which allows NumPy to seamlessly and speedily integrate with a wide variety of databases. Installation: Mac and Linux users can install NumPy via pip command: pip install numpy Windows does not have any package manager analogous to that in linux or mac. Please download the pre-built windows installer for NumPy from here (according to your system configuration and Python version). And then install the packages manually. Note: All the examples discussed below will not run on an online IDE. 1. Arrays in NumPy: NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called axes. The number of axes is rank. NumPy’s array class is called ndarray. It is also known by the alias array. Example : [[ 1, 2, 3], [ 4, 2, 5]] Here, rank = 2 (as it is 2-dimensional or it has 2 axes) first dimension(axis) length = 2, second dimension has length = 3 overall shape can be expressed as: (2, 3) Python3 # Python program to demonstrate# basic array characteristicsimport numpy as np # Creating array objectarr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] ) # Printing type of arr objectprint("Array is of type: ", type(arr)) # Printing array dimensions (axes)print("No. of dimensions: ", arr.ndim) # Printing shape of arrayprint("Shape of array: ", arr.shape) # Printing size (total number of elements) of arrayprint("Size of array: ", arr.size) # Printing type of elements in arrayprint("Array stores elements of type: ", arr.dtype) Output : Array is of type: No. of dimensions: 2 Shape of array: (2, 3) Size of array: 6 Array stores elements of type: int64 2. Array creation: There are various ways to create arrays in NumPy. For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences. Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. For example: np.zeros, np.ones, np.full, np.empty, etc. To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists. arange: returns evenly spaced values within a given interval. step size is specified. linspace: returns evenly spaced values within a given interval. num no. of elements are returned. Reshaping array: We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, ..., aN). We can reshape and convert it into another array with shape (b1, b2, b3, ..., bM). The only required condition is: a1 x a2 x a3 ... x aN = b1 x b2 x b3 ... x bM . (i.e original size of array remains unchanged.) Flatten array: We can use flatten method to get a copy of array collapsed into one dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for column major order. Note: Type of array can be explicitly defined while creating array. Python3 # Python program to demonstrate# array creation techniquesimport numpy as np # Creating array from list with type floata = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')print ("Array created using passed list:\n", a) # Creating array from tupleb = np.array((1 , 3, 2))print ("\nArray created using passed tuple:\n", b) # Creating a 3X4 array with all zerosc = np.zeros((3, 4))print ("\nAn array initialized with all zeros:\n", c) # Create a constant value array of complex typed = np.full((3, 3), 6, dtype = 'complex')print ("\nAn array initialized with all 6s." "Array type is complex:\n", d) # Create an array with random valuese = np.random.random((2, 2))print ("\nA random array:\n", e) # Create a sequence of integers# from 0 to 30 with steps of 5f = np.arange(0, 30, 5)print ("\nA sequential array with steps of 5:\n", f) # Create a sequence of 10 values in range 0 to 5g = np.linspace(0, 5, 10)print ("\nA sequential array with 10 values between" "0 and 5:\n", g) # Reshaping 3X4 array to 2X2X3 arrayarr = np.array([[1, 2, 3, 4], [5, 2, 4, 2], [1, 2, 0, 1]]) newarr = arr.reshape(2, 2, 3) print ("\nOriginal array:\n", arr)print ("Reshaped array:\n", newarr) # Flatten arrayarr = np.array([[1, 2, 3], [4, 5, 6]])flarr = arr.flatten() print ("\nOriginal array:\n", arr)print ("Fattened array:\n", flarr) Output : Array created using passed list: [[ 1. 2. 4.] [ 5. 8. 7.]] Array created using passed tuple: [1 3 2] An array initialized with all zeros: [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] An array initialized with all 6s. Array type is complex: [[ 6.+0.j 6.+0.j 6.+0.j] [ 6.+0.j 6.+0.j 6.+0.j] [ 6.+0.j 6.+0.j 6.+0.j]] A random array: [[ 0.46829566 0.67079389] [ 0.09079849 0.95410464]] A sequential array with steps of 5: [ 0 5 10 15 20 25] A sequential array with 10 values between 0 and 5: [ 0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5. ] Original array: [[1 2 3 4] [5 2 4 2] [1 2 0 1]] Reshaped array: [[[1 2 3] [4 5 2]] [[4 2 1] [2 0 1]]] Original array: [[1 2 3] [4 5 6]] Fattened array: [1 2 3 4 5 6] 3. Array Indexing: Knowing the basics of array indexing is important for analysing and manipulating the array object. NumPy offers many ways to do array indexing. Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array. Integer array indexing: In this method, lists are passed for indexing for each dimension. One to one mapping of corresponding elements is done to construct a new arbitrary array. Boolean array indexing: This method is used when we want to pick elements from array which satisfy some condition. Python3 # Python program to demonstrate# indexing in numpyimport numpy as np # An exemplar arrayarr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0]]) # Slicing arraytemp = arr[:2, ::2]print ("Array with first 2 rows and alternate" "columns(0 and 2):\n", temp) # Integer array indexing exampletemp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]print ("\nElements at indices (0, 3), (1, 2), (2, 1)," "(3, 0):\n", temp) # boolean array indexing examplecond = arr > 0 # cond is a boolean arraytemp = arr[cond]print ("\nElements greater than 0:\n", temp) Output : Array with first 2 rows and alternatecolumns(0 and 2): [[-1. 0.] [ 4. 6.]] Elements at indices (0, 3), (1, 2), (2, 1),(3, 0): [ 4. 6. 0. 3.] Elements greater than 0: [ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ] 4. Basic operations: Plethora of built-in arithmetic functions are provided in NumPy. Operations on single array: We can use overloaded arithmetic operators to do element-wise operation on array to create a new array. In case of +=, -=, *= operators, the existing array is modified. Python3 # Python program to demonstrate# basic operations on single arrayimport numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every elementprint ("Adding 1 to every element:", a+1) # subtract 3 from each elementprint ("Subtracting 3 from each element:", a-3) # multiply each element by 10print ("Multiplying each element by 10:", a*10) # square each elementprint ("Squaring each element:", a**2) # modify existing arraya *= 2print ("Doubled each element of original array:", a) # transpose of arraya = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]]) print ("\nOriginal array:\n", a)print ("Transpose of array:\n", a.T) Output : Adding 1 to every element: [2 3 6 4] Subtracting 3 from each element: [-2 -1 2 0] Multiplying each element by 10: [10 20 50 30] Squaring each element: [ 1 4 25 9] Doubled each element of original array: [ 2 4 10 6] Original array: [[1 2 3] [3 4 5] [9 6 0]] Transpose of array: [[1 3 9] [2 4 6] [3 5 0]] Unary operators: Many unary operations are provided as a method of ndarray class. This includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting an axis parameter. Python3 # Python program to demonstrate# unary operators in numpyimport numpy as np arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) # maximum element of arrayprint ("Largest element is:", arr.max())print ("Row-wise maximum elements:", arr.max(axis = 1)) # minimum element of arrayprint ("Column-wise minimum elements:", arr.min(axis = 0)) # sum of array elementsprint ("Sum of all array elements:", arr.sum()) # cumulative sum along each rowprint ("Cumulative sum along each row:\n", arr.cumsum(axis = 1)) Output : Largest element is: 9 Row-wise maximum elements: [6 7 9] Column-wise minimum elements: [1 1 2] Sum of all array elements: 38 Cumulative sum along each row: [[ 1 6 12] [ 4 11 13] [ 3 4 13]] Binary operators: These operations apply on array elementwise and a new array is created. You can use all basic arithmetic operators like +, -, /, , etc. In case of +=, -=, = operators, the existing array is modified. Python3 # Python program to demonstrate# binary operators in Numpyimport numpy as np a = np.array([[1, 2], [3, 4]])b = np.array([[4, 3], [2, 1]]) # add arraysprint ("Array sum:\n", a + b) # multiply arrays (elementwise multiplication)print ("Array multiplication:\n", a*b) # matrix multiplicationprint ("Matrix multiplication:\n", a.dot(b)) Output: Array sum: [[5 5] [5 5]] Array multiplication: [[4 6] [6 4]] Matrix multiplication: [[ 8 5] [20 13]] Universal functions (ufunc): NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These functions also operate elementwise on an array, producing an array as output. Note: All the operations we did above using overloaded operators can be done using ufuncs like np.add, np.subtract, np.multiply, np.divide, np.sum, etc. Python3 # Python program to demonstrate# universal functions in numpyimport numpy as np # create an array of sine valuesa = np.array([0, np.pi/2, np.pi])print ("Sine values of array elements:", np.sin(a)) # exponential valuesa = np.array([0, 1, 2, 3])print ("Exponent of array elements:", np.exp(a)) # square root of array valuesprint ("Square root of array elements:", np.sqrt(a)) Output: Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-16] Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692] Square root of array elements: [ 0. 1. 1.41421356 1.73205081] 4. Sorting array: There is a simple np.sort method for sorting NumPy arrays. Let’s explore it a bit. Python3 # Python program to demonstrate sorting in numpyimport numpy as np a = np.array([[1, 4, 2], [3, 4, 6], [0, -1, 5]]) # sorted arrayprint ("Array elements in sorted order:\n", np.sort(a, axis = None)) # sort array row-wiseprint ("Row-wise sorted array:\n", np.sort(a, axis = 1)) # specify sort algorithmprint ("Column wise sort by applying merge-sort:\n", np.sort(a, axis = 0, kind = 'mergesort')) # Example to show sorting of structured array# set alias names for dtypesdtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)] # Values to be put in arrayvalues = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7), ('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)] # Creating arrayarr = np.array(values, dtype = dtypes)print ("\nArray sorted by names:\n", np.sort(arr, order = 'name')) print ("Array sorted by graduation year and then cgpa:\n", np.sort(arr, order = ['grad_year', 'cgpa'])) Output: Array elements in sorted order: [-1 0 1 2 3 4 4 5 6] Row-wise sorted array: [[ 1 2 4] [ 3 4 6] [-1 0 5]] Column wise sort by applying merge-sort: [[ 0 -1 2] [ 1 4 5] [ 3 4 6]] Array sorted by names: [('Aakash', 2009, 9.0) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5) ('Pankaj', 2008, 7.9)] Array sorted by graduation year and then cgpa: [('Pankaj', 2008, 7.9) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5) ('Aakash', 2009, 9.0)] So, this was a brief yet concise introduction-cum-tutorial of the NumPy library. For more detailed study, please refer NumPy Reference Guide . This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prachisoda1234 simmytarika5 VINOTHKUMAR A.K. Python numpy-Basics Python-numpy 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": 54, "s": 26, "text": "\n06 May, 2022" }, { "code": null, "e": 488, "s": 54, "text": "This article will help you get acquainted with the widely used array-processing library in Python, NumPy. What is NumPy? NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is open-source software. It contains various features including these important ones:" }, { "code": null, "e": 526, "s": 488, "text": "A powerful N-dimensional array object" }, { "code": null, "e": 565, "s": 526, "text": "Sophisticated (broadcasting) functions" }, { "code": null, "e": 610, "s": 565, "text": "Tools for integrating C/C++ and Fortran code" }, { "code": null, "e": 683, "s": 610, "text": "Useful linear algebra, Fourier transform, and random number capabilities" }, { "code": null, "e": 956, "s": 683, "text": "Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined using Numpy which allows NumPy to seamlessly and speedily integrate with a wide variety of databases. Installation:" }, { "code": null, "e": 1011, "s": 956, "text": "Mac and Linux users can install NumPy via pip command:" }, { "code": null, "e": 1029, "s": 1011, "text": "pip install numpy" }, { "code": null, "e": 1275, "s": 1029, "text": "Windows does not have any package manager analogous to that in linux or mac. Please download the pre-built windows installer for NumPy from here (according to your system configuration and Python version). And then install the packages manually." }, { "code": null, "e": 1428, "s": 1275, "text": "Note: All the examples discussed below will not run on an online IDE. 1. Arrays in NumPy: NumPy’s main object is the homogeneous multidimensional array." }, { "code": null, "e": 1536, "s": 1428, "text": "It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers." }, { "code": null, "e": 1601, "s": 1536, "text": "In NumPy dimensions are called axes. The number of axes is rank." }, { "code": null, "e": 1677, "s": 1601, "text": "NumPy’s array class is called ndarray. It is also known by the alias array." }, { "code": null, "e": 1687, "s": 1677, "text": "Example :" }, { "code": null, "e": 1878, "s": 1687, "text": "[[ 1, 2, 3],\n [ 4, 2, 5]]\nHere,\nrank = 2 (as it is 2-dimensional or it has 2 axes)\nfirst dimension(axis) length = 2, second dimension has length = 3\noverall shape can be expressed as: (2, 3)" }, { "code": null, "e": 1886, "s": 1878, "text": "Python3" }, { "code": "# Python program to demonstrate# basic array characteristicsimport numpy as np # Creating array objectarr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] ) # Printing type of arr objectprint(\"Array is of type: \", type(arr)) # Printing array dimensions (axes)print(\"No. of dimensions: \", arr.ndim) # Printing shape of arrayprint(\"Shape of array: \", arr.shape) # Printing size (total number of elements) of arrayprint(\"Size of array: \", arr.size) # Printing type of elements in arrayprint(\"Array stores elements of type: \", arr.dtype)", "e": 2424, "s": 1886, "text": null }, { "code": null, "e": 2433, "s": 2424, "text": "Output :" }, { "code": null, "e": 2555, "s": 2433, "text": "Array is of type: \nNo. of dimensions: 2\nShape of array: (2, 3)\nSize of array: 6\nArray stores elements of type: int64" }, { "code": null, "e": 2624, "s": 2555, "text": "2. Array creation: There are various ways to create arrays in NumPy." }, { "code": null, "e": 2814, "s": 2624, "text": "For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences." }, { "code": null, "e": 3110, "s": 2814, "text": "Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. For example: np.zeros, np.ones, np.full, np.empty, etc." }, { "code": null, "e": 3225, "s": 3110, "text": "To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists." }, { "code": null, "e": 3311, "s": 3225, "text": "arange: returns evenly spaced values within a given interval. step size is specified." }, { "code": null, "e": 3409, "s": 3311, "text": "linspace: returns evenly spaced values within a given interval. num no. of elements are returned." }, { "code": null, "e": 3736, "s": 3409, "text": "Reshaping array: We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, ..., aN). We can reshape and convert it into another array with shape (b1, b2, b3, ..., bM). The only required condition is: a1 x a2 x a3 ... x aN = b1 x b2 x b3 ... x bM . (i.e original size of array remains unchanged.)" }, { "code": null, "e": 3933, "s": 3736, "text": "Flatten array: We can use flatten method to get a copy of array collapsed into one dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for column major order." }, { "code": null, "e": 4002, "s": 3933, "text": "Note: Type of array can be explicitly defined while creating array. " }, { "code": null, "e": 4010, "s": 4002, "text": "Python3" }, { "code": "# Python program to demonstrate# array creation techniquesimport numpy as np # Creating array from list with type floata = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')print (\"Array created using passed list:\\n\", a) # Creating array from tupleb = np.array((1 , 3, 2))print (\"\\nArray created using passed tuple:\\n\", b) # Creating a 3X4 array with all zerosc = np.zeros((3, 4))print (\"\\nAn array initialized with all zeros:\\n\", c) # Create a constant value array of complex typed = np.full((3, 3), 6, dtype = 'complex')print (\"\\nAn array initialized with all 6s.\" \"Array type is complex:\\n\", d) # Create an array with random valuese = np.random.random((2, 2))print (\"\\nA random array:\\n\", e) # Create a sequence of integers# from 0 to 30 with steps of 5f = np.arange(0, 30, 5)print (\"\\nA sequential array with steps of 5:\\n\", f) # Create a sequence of 10 values in range 0 to 5g = np.linspace(0, 5, 10)print (\"\\nA sequential array with 10 values between\" \"0 and 5:\\n\", g) # Reshaping 3X4 array to 2X2X3 arrayarr = np.array([[1, 2, 3, 4], [5, 2, 4, 2], [1, 2, 0, 1]]) newarr = arr.reshape(2, 2, 3) print (\"\\nOriginal array:\\n\", arr)print (\"Reshaped array:\\n\", newarr) # Flatten arrayarr = np.array([[1, 2, 3], [4, 5, 6]])flarr = arr.flatten() print (\"\\nOriginal array:\\n\", arr)print (\"Fattened array:\\n\", flarr)", "e": 5403, "s": 4010, "text": null }, { "code": null, "e": 5412, "s": 5403, "text": "Output :" }, { "code": null, "e": 6247, "s": 5412, "text": "Array created using passed list:\n [[ 1. 2. 4.]\n [ 5. 8. 7.]]\n\nArray created using passed tuple:\n [1 3 2]\n\nAn array initialized with all zeros:\n [[ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]]\n\nAn array initialized with all 6s. Array type is complex:\n [[ 6.+0.j 6.+0.j 6.+0.j]\n [ 6.+0.j 6.+0.j 6.+0.j]\n [ 6.+0.j 6.+0.j 6.+0.j]]\n\nA random array:\n [[ 0.46829566 0.67079389]\n [ 0.09079849 0.95410464]]\n\nA sequential array with steps of 5:\n [ 0 5 10 15 20 25]\n\nA sequential array with 10 values between 0 and 5:\n [ 0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778\n 3.33333333 3.88888889 4.44444444 5. ]\n\nOriginal array:\n [[1 2 3 4]\n [5 2 4 2]\n [1 2 0 1]]\nReshaped array:\n [[[1 2 3]\n [4 5 2]]\n\n [[4 2 1]\n [2 0 1]]]\n\nOriginal array:\n [[1 2 3]\n [4 5 6]]\nFattened array:\n [1 2 3 4 5 6]" }, { "code": null, "e": 6410, "s": 6247, "text": "3. Array Indexing: Knowing the basics of array indexing is important for analysing and manipulating the array object. NumPy offers many ways to do array indexing." }, { "code": null, "e": 6570, "s": 6410, "text": "Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array." }, { "code": null, "e": 6749, "s": 6570, "text": "Integer array indexing: In this method, lists are passed for indexing for each dimension. One to one mapping of corresponding elements is done to construct a new arbitrary array." }, { "code": null, "e": 6864, "s": 6749, "text": "Boolean array indexing: This method is used when we want to pick elements from array which satisfy some condition." }, { "code": null, "e": 6872, "s": 6864, "text": "Python3" }, { "code": "# Python program to demonstrate# indexing in numpyimport numpy as np # An exemplar arrayarr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0]]) # Slicing arraytemp = arr[:2, ::2]print (\"Array with first 2 rows and alternate\" \"columns(0 and 2):\\n\", temp) # Integer array indexing exampletemp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]print (\"\\nElements at indices (0, 3), (1, 2), (2, 1),\" \"(3, 0):\\n\", temp) # boolean array indexing examplecond = arr > 0 # cond is a boolean arraytemp = arr[cond]print (\"\\nElements greater than 0:\\n\", temp)", "e": 7528, "s": 6872, "text": null }, { "code": null, "e": 7537, "s": 7528, "text": "Output :" }, { "code": null, "e": 7766, "s": 7537, "text": "Array with first 2 rows and alternatecolumns(0 and 2):\n [[-1. 0.]\n [ 4. 6.]]\n\nElements at indices (0, 3), (1, 2), (2, 1),(3, 0):\n [ 4. 6. 0. 3.]\n\nElements greater than 0:\n [ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]" }, { "code": null, "e": 7852, "s": 7766, "text": "4. Basic operations: Plethora of built-in arithmetic functions are provided in NumPy." }, { "code": null, "e": 8049, "s": 7852, "text": "Operations on single array: We can use overloaded arithmetic operators to do element-wise operation on array to create a new array. In case of +=, -=, *= operators, the existing array is modified." }, { "code": null, "e": 8057, "s": 8049, "text": "Python3" }, { "code": "# Python program to demonstrate# basic operations on single arrayimport numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every elementprint (\"Adding 1 to every element:\", a+1) # subtract 3 from each elementprint (\"Subtracting 3 from each element:\", a-3) # multiply each element by 10print (\"Multiplying each element by 10:\", a*10) # square each elementprint (\"Squaring each element:\", a**2) # modify existing arraya *= 2print (\"Doubled each element of original array:\", a) # transpose of arraya = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]]) print (\"\\nOriginal array:\\n\", a)print (\"Transpose of array:\\n\", a.T)", "e": 8668, "s": 8057, "text": null }, { "code": null, "e": 8677, "s": 8668, "text": "Output :" }, { "code": null, "e": 8993, "s": 8677, "text": "Adding 1 to every element: [2 3 6 4]\nSubtracting 3 from each element: [-2 -1 2 0]\nMultiplying each element by 10: [10 20 50 30]\nSquaring each element: [ 1 4 25 9]\nDoubled each element of original array: [ 2 4 10 6]\n\nOriginal array:\n [[1 2 3]\n [3 4 5]\n [9 6 0]]\nTranspose of array:\n [[1 3 9]\n [2 4 6]\n [3 5 0]]" }, { "code": null, "e": 9199, "s": 8993, "text": "Unary operators: Many unary operations are provided as a method of ndarray class. This includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting an axis parameter." }, { "code": null, "e": 9207, "s": 9199, "text": "Python3" }, { "code": "# Python program to demonstrate# unary operators in numpyimport numpy as np arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) # maximum element of arrayprint (\"Largest element is:\", arr.max())print (\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum element of arrayprint (\"Column-wise minimum elements:\", arr.min(axis = 0)) # sum of array elementsprint (\"Sum of all array elements:\", arr.sum()) # cumulative sum along each rowprint (\"Cumulative sum along each row:\\n\", arr.cumsum(axis = 1))", "e": 9829, "s": 9207, "text": null }, { "code": null, "e": 9838, "s": 9829, "text": "Output :" }, { "code": null, "e": 10031, "s": 9838, "text": "Largest element is: 9\nRow-wise maximum elements: [6 7 9]\nColumn-wise minimum elements: [1 1 2]\nSum of all array elements: 38\nCumulative sum along each row:\n[[ 1 6 12]\n [ 4 11 13]\n [ 3 4 13]]" }, { "code": null, "e": 10249, "s": 10031, "text": "Binary operators: These operations apply on array elementwise and a new array is created. You can use all basic arithmetic operators like +, -, /, , etc. In case of +=, -=, = operators, the existing array is modified." }, { "code": null, "e": 10257, "s": 10249, "text": "Python3" }, { "code": "# Python program to demonstrate# binary operators in Numpyimport numpy as np a = np.array([[1, 2], [3, 4]])b = np.array([[4, 3], [2, 1]]) # add arraysprint (\"Array sum:\\n\", a + b) # multiply arrays (elementwise multiplication)print (\"Array multiplication:\\n\", a*b) # matrix multiplicationprint (\"Matrix multiplication:\\n\", a.dot(b))", "e": 10612, "s": 10257, "text": null }, { "code": null, "e": 10620, "s": 10612, "text": "Output:" }, { "code": null, "e": 10725, "s": 10620, "text": "Array sum:\n[[5 5]\n [5 5]]\nArray multiplication:\n[[4 6]\n [6 4]]\nMatrix multiplication:\n[[ 8 5]\n [20 13]]" }, { "code": null, "e": 10913, "s": 10725, "text": "Universal functions (ufunc): NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These functions also operate elementwise on an array, producing an array as output." }, { "code": null, "e": 11067, "s": 10913, "text": "Note: All the operations we did above using overloaded operators can be done using ufuncs like np.add, np.subtract, np.multiply, np.divide, np.sum, etc. " }, { "code": null, "e": 11075, "s": 11067, "text": "Python3" }, { "code": "# Python program to demonstrate# universal functions in numpyimport numpy as np # create an array of sine valuesa = np.array([0, np.pi/2, np.pi])print (\"Sine values of array elements:\", np.sin(a)) # exponential valuesa = np.array([0, 1, 2, 3])print (\"Exponent of array elements:\", np.exp(a)) # square root of array valuesprint (\"Square root of array elements:\", np.sqrt(a))", "e": 11449, "s": 11075, "text": null }, { "code": null, "e": 11457, "s": 11449, "text": "Output:" }, { "code": null, "e": 11704, "s": 11457, "text": "Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-16]\nExponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692]\nSquare root of array elements: [ 0. 1. 1.41421356 1.73205081]" }, { "code": null, "e": 11806, "s": 11704, "text": "4. Sorting array: There is a simple np.sort method for sorting NumPy arrays. Let’s explore it a bit. " }, { "code": null, "e": 11814, "s": 11806, "text": "Python3" }, { "code": "# Python program to demonstrate sorting in numpyimport numpy as np a = np.array([[1, 4, 2], [3, 4, 6], [0, -1, 5]]) # sorted arrayprint (\"Array elements in sorted order:\\n\", np.sort(a, axis = None)) # sort array row-wiseprint (\"Row-wise sorted array:\\n\", np.sort(a, axis = 1)) # specify sort algorithmprint (\"Column wise sort by applying merge-sort:\\n\", np.sort(a, axis = 0, kind = 'mergesort')) # Example to show sorting of structured array# set alias names for dtypesdtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)] # Values to be put in arrayvalues = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7), ('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)] # Creating arrayarr = np.array(values, dtype = dtypes)print (\"\\nArray sorted by names:\\n\", np.sort(arr, order = 'name')) print (\"Array sorted by graduation year and then cgpa:\\n\", np.sort(arr, order = ['grad_year', 'cgpa']))", "e": 12833, "s": 11814, "text": null }, { "code": null, "e": 12841, "s": 12833, "text": "Output:" }, { "code": null, "e": 13291, "s": 12841, "text": "Array elements in sorted order:\n[-1 0 1 2 3 4 4 5 6]\nRow-wise sorted array:\n[[ 1 2 4]\n [ 3 4 6]\n [-1 0 5]]\nColumn wise sort by applying merge-sort:\n[[ 0 -1 2]\n [ 1 4 5]\n [ 3 4 6]]\n\nArray sorted by names:\n[('Aakash', 2009, 9.0) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5)\n ('Pankaj', 2008, 7.9)]\nArray sorted by graduation year and then cgpa:\n[('Pankaj', 2008, 7.9) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5)\n ('Aakash', 2009, 9.0)]" }, { "code": null, "e": 13855, "s": 13291, "text": "So, this was a brief yet concise introduction-cum-tutorial of the NumPy library. For more detailed study, please refer NumPy Reference Guide . This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 13870, "s": 13855, "text": "prachisoda1234" }, { "code": null, "e": 13883, "s": 13870, "text": "simmytarika5" }, { "code": null, "e": 13900, "s": 13883, "text": "VINOTHKUMAR A.K." }, { "code": null, "e": 13920, "s": 13900, "text": "Python numpy-Basics" }, { "code": null, "e": 13933, "s": 13920, "text": "Python-numpy" }, { "code": null, "e": 13940, "s": 13933, "text": "Python" }, { "code": null, "e": 14038, "s": 13940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14056, "s": 14038, "text": "Python Dictionary" }, { "code": null, "e": 14098, "s": 14056, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 14120, "s": 14098, "text": "Enumerate() in Python" }, { "code": null, "e": 14155, "s": 14120, "text": "Read a file line by line in Python" }, { "code": null, "e": 14181, "s": 14155, "text": "Python String | replace()" }, { "code": null, "e": 14213, "s": 14181, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 14242, "s": 14213, "text": "*args and **kwargs in Python" }, { "code": null, "e": 14272, "s": 14242, "text": "Iterate over a list in Python" }, { "code": null, "e": 14299, "s": 14272, "text": "Python Classes and Objects" } ]
Program to create grade calculator in Python
26 Oct, 2018 Given different scored marks of students. We need to find grades. The test score is an average of the respective marks scored in assignments, tests and lab-works. The final test score is assigned using below formula. 10 % of marks scored from submission of Assignments 70 % of marks scored from Test 20 % of marks scored in Lab-Works Grade will be calculated according to : 1. score >= 90 : "A" 2. score >= 80 : "B" 3. score >= 70 : "C" 4. score >= 60 : "D" Also, calculate the total class average and letter grade of class. Below is the implementation : # Python code for the Grade# Calculator program in action # Creating a dictionary which # consists of the student name,# assignment result test results# and their respective lab results # 1. Jack's dictionaryjack = { "name":"Jack Frost", "assignment" : [80, 50, 40, 20], "test" : [75, 75], "lab" : [78.20, 77.20] } # 2. James's dictionaryjames = { "name":"James Potter", "assignment" : [82, 56, 44, 30], "test" : [80, 80], "lab" : [67.90, 78.72] } # 3. Dylan's dictionarydylan = { "name" : "Dylan Rhodes", "assignment" : [77, 82, 23, 39], "test" : [78, 77], "lab" : [80, 80] } # 4. Jessica's dictionaryjess = { "name" : "Jessica Stone", "assignment" : [67, 55, 77, 21], "test" : [40, 50], "lab" : [69, 44.56] } # 5. Tom's dictionarytom = { "name" : "Tom Hanks", "assignment" : [29, 89, 60, 56], "test" : [65, 56], "lab" : [50, 40.6] } # Function calculates average def get_average(marks): total_sum = sum(marks) total_sum = float(total_sum) return total_sum / len(marks) # Function calculates total averagedef calculate_total_average(students): assignment = get_average(students["assignment"]) test = get_average(students["test"]) lab = get_average(students["lab"]) # Return the result based # on weightage supplied # 10 % from assignments # 70 % from test # 20 % from lab-works return (0.1 * assignment + 0.7 * test + 0.2 * lab) # Calculate letter grade of each studentdef assign_letter_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else : return "E" # Function to calculate the total# average marks of the whole classdef class_average_is(student_list): result_list = [] for student in student_list: stud_avg = calculate_total_average(student) result_list.append(stud_avg) return get_average(result_list) # Student list consisting the# dictionary of all studentsstudents = [jack, james, dylan, jess, tom] # Iterate through the students list# and calculate their respective# average marks and letter gradefor i in students : print(i["name"]) print("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=") print("Average marks of %s is : %s " %(i["name"], calculate_total_average(i))) print("Letter Grade of %s is : %s" %(i["name"], assign_letter_grade(calculate_total_average(i)))) print() # Calculate the average of whole classclass_av = class_average_is(students) print( "Class Average is %s" %(class_av))print("Letter Grade of the class is %s " %(assign_letter_grade(class_av))) Output : Jack Frost =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Average marks of Jack Frost is : 72.79 Letter Grade of Jack Frost is : C James Potter =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Average marks of James Potter is : 75.962 Letter Grade of James Potter is : C Dylan Rhodes =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Average marks of Dylan Rhodes is : 75.775 Letter Grade of Dylan Rhodes is : C Jessica Stone =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Average marks of Jessica Stone is : 48.356 Letter Grade of Jessica Stone is : E Tom Hanks =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Average marks of Tom Hanks is : 57.26 Letter Grade of Tom Hanks is : E Class Average is 72.79 Letter Grade of the class is C Python dictionary-programs python-dict Python Programs School Programming python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for factorial of a number Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Oct, 2018" }, { "code": null, "e": 269, "s": 52, "text": "Given different scored marks of students. We need to find grades. The test score is an average of the respective marks scored in assignments, tests and lab-works. The final test score is assigned using below formula." }, { "code": null, "e": 386, "s": 269, "text": "10 % of marks scored from submission of Assignments\n70 % of marks scored from Test\n20 % of marks scored in Lab-Works" }, { "code": null, "e": 427, "s": 386, "text": " Grade will be calculated according to :" }, { "code": null, "e": 512, "s": 427, "text": "1. score >= 90 : \"A\"\n2. score >= 80 : \"B\"\n3. score >= 70 : \"C\"\n4. score >= 60 : \"D\"\n" }, { "code": null, "e": 579, "s": 512, "text": "Also, calculate the total class average and letter grade of class." }, { "code": null, "e": 609, "s": 579, "text": "Below is the implementation :" }, { "code": "# Python code for the Grade# Calculator program in action # Creating a dictionary which # consists of the student name,# assignment result test results# and their respective lab results # 1. Jack's dictionaryjack = { \"name\":\"Jack Frost\", \"assignment\" : [80, 50, 40, 20], \"test\" : [75, 75], \"lab\" : [78.20, 77.20] } # 2. James's dictionaryjames = { \"name\":\"James Potter\", \"assignment\" : [82, 56, 44, 30], \"test\" : [80, 80], \"lab\" : [67.90, 78.72] } # 3. Dylan's dictionarydylan = { \"name\" : \"Dylan Rhodes\", \"assignment\" : [77, 82, 23, 39], \"test\" : [78, 77], \"lab\" : [80, 80] } # 4. Jessica's dictionaryjess = { \"name\" : \"Jessica Stone\", \"assignment\" : [67, 55, 77, 21], \"test\" : [40, 50], \"lab\" : [69, 44.56] } # 5. Tom's dictionarytom = { \"name\" : \"Tom Hanks\", \"assignment\" : [29, 89, 60, 56], \"test\" : [65, 56], \"lab\" : [50, 40.6] } # Function calculates average def get_average(marks): total_sum = sum(marks) total_sum = float(total_sum) return total_sum / len(marks) # Function calculates total averagedef calculate_total_average(students): assignment = get_average(students[\"assignment\"]) test = get_average(students[\"test\"]) lab = get_average(students[\"lab\"]) # Return the result based # on weightage supplied # 10 % from assignments # 70 % from test # 20 % from lab-works return (0.1 * assignment + 0.7 * test + 0.2 * lab) # Calculate letter grade of each studentdef assign_letter_grade(score): if score >= 90: return \"A\" elif score >= 80: return \"B\" elif score >= 70: return \"C\" elif score >= 60: return \"D\" else : return \"E\" # Function to calculate the total# average marks of the whole classdef class_average_is(student_list): result_list = [] for student in student_list: stud_avg = calculate_total_average(student) result_list.append(stud_avg) return get_average(result_list) # Student list consisting the# dictionary of all studentsstudents = [jack, james, dylan, jess, tom] # Iterate through the students list# and calculate their respective# average marks and letter gradefor i in students : print(i[\"name\"]) print(\"=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\") print(\"Average marks of %s is : %s \" %(i[\"name\"], calculate_total_average(i))) print(\"Letter Grade of %s is : %s\" %(i[\"name\"], assign_letter_grade(calculate_total_average(i)))) print() # Calculate the average of whole classclass_av = class_average_is(students) print( \"Class Average is %s\" %(class_av))print(\"Letter Grade of the class is %s \" %(assign_letter_grade(class_av)))", "e": 3429, "s": 609, "text": null }, { "code": null, "e": 3438, "s": 3429, "text": "Output :" }, { "code": null, "e": 4145, "s": 3438, "text": "Jack Frost\n=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\nAverage marks of Jack Frost is : 72.79 \nLetter Grade of Jack Frost is : C\n\nJames Potter\n=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\nAverage marks of James Potter is : 75.962 \nLetter Grade of James Potter is : C\n\nDylan Rhodes\n=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\nAverage marks of Dylan Rhodes is : 75.775 \nLetter Grade of Dylan Rhodes is : C\n\nJessica Stone\n=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\nAverage marks of Jessica Stone is : 48.356 \nLetter Grade of Jessica Stone is : E\n\nTom Hanks\n=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\nAverage marks of Tom Hanks is : 57.26 \nLetter Grade of Tom Hanks is : E\n\nClass Average is 72.79\nLetter Grade of the class is C \n" }, { "code": null, "e": 4172, "s": 4145, "text": "Python dictionary-programs" }, { "code": null, "e": 4184, "s": 4172, "text": "python-dict" }, { "code": null, "e": 4200, "s": 4184, "text": "Python Programs" }, { "code": null, "e": 4219, "s": 4200, "text": "School Programming" }, { "code": null, "e": 4231, "s": 4219, "text": "python-dict" }, { "code": null, "e": 4329, "s": 4231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4378, "s": 4329, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 4415, "s": 4378, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 4449, "s": 4415, "text": "Python program to add two numbers" }, { "code": null, "e": 4508, "s": 4449, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 4549, "s": 4508, "text": "Python Program for factorial of a number" }, { "code": null, "e": 4567, "s": 4549, "text": "Python Dictionary" }, { "code": null, "e": 4592, "s": 4567, "text": "Reverse a string in Java" }, { "code": null, "e": 4608, "s": 4592, "text": "Arrays in C/C++" }, { "code": null, "e": 4631, "s": 4608, "text": "Introduction To PYTHON" } ]
Python: Numpy’s Structured Array
27 Aug, 2021 Numpy’s Structured Array is similar to Struct in C. It is used for grouping data of different types and sizes. Structure array uses data containers called fields. Each data field can contain data of any type and size. Array elements can be accessed with the help of dot notation.Note: Arrays with named fields that can contain data of various types and sizes.Properties of Structured array All structs in array have same number of fields. All structs have same fields names. For example, consider a structured array of student which has different fields like name, year, marks. Each record in array student has a structure of class Struct. The array of a structure is referred to as struct as adding any new fields for a new struct in the array, contains the empty array. Example 1: Python3 # Python program to demonstrate# Structured array import numpy as np a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)]) print(a) [('Sana', 2, 21.0) ('Mansi', 7, 29.0)] Example 2: The structure array can be sorted by using numpy.sort() method and passing the order as parameter. This parameter takes the value of the field according to which it is needed to be sorted. Python3 # Python program to demonstrate# Structured array import numpy as np a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)]) # Sorting according to the nameb = np.sort(a, order='name')print('Sorting according to the name', b) # Sorting according to the ageb = np.sort(a, order='age')print('\nSorting according to the age', b) Sorting according to the name [('Mansi', 7, 29.0) ('Sana', 2, 21.0)] Sorting according to the age [('Sana', 2, 21.0) ('Mansi', 7, 29.0)] sagar0719kumar varshagumber28 Picked Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Aug, 2021" }, { "code": null, "e": 420, "s": 28, "text": "Numpy’s Structured Array is similar to Struct in C. It is used for grouping data of different types and sizes. Structure array uses data containers called fields. Each data field can contain data of any type and size. Array elements can be accessed with the help of dot notation.Note: Arrays with named fields that can contain data of various types and sizes.Properties of Structured array " }, { "code": null, "e": 469, "s": 420, "text": "All structs in array have same number of fields." }, { "code": null, "e": 505, "s": 469, "text": "All structs have same fields names." }, { "code": null, "e": 609, "s": 505, "text": "For example, consider a structured array of student which has different fields like name, year, marks. " }, { "code": null, "e": 815, "s": 609, "text": "Each record in array student has a structure of class Struct. The array of a structure is referred to as struct as adding any new fields for a new struct in the array, contains the empty array. Example 1: " }, { "code": null, "e": 823, "s": 815, "text": "Python3" }, { "code": "# Python program to demonstrate# Structured array import numpy as np a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)]) print(a)", "e": 1039, "s": 823, "text": null }, { "code": null, "e": 1078, "s": 1039, "text": "[('Sana', 2, 21.0) ('Mansi', 7, 29.0)]" }, { "code": null, "e": 1281, "s": 1080, "text": "Example 2: The structure array can be sorted by using numpy.sort() method and passing the order as parameter. This parameter takes the value of the field according to which it is needed to be sorted. " }, { "code": null, "e": 1289, "s": 1281, "text": "Python3" }, { "code": "# Python program to demonstrate# Structured array import numpy as np a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)]) # Sorting according to the nameb = np.sort(a, order='name')print('Sorting according to the name', b) # Sorting according to the ageb = np.sort(a, order='age')print('\\nSorting according to the age', b)", "e": 1710, "s": 1289, "text": null }, { "code": null, "e": 1848, "s": 1710, "text": "Sorting according to the name [('Mansi', 7, 29.0) ('Sana', 2, 21.0)]\n\nSorting according to the age [('Sana', 2, 21.0) ('Mansi', 7, 29.0)]" }, { "code": null, "e": 1865, "s": 1850, "text": "sagar0719kumar" }, { "code": null, "e": 1880, "s": 1865, "text": "varshagumber28" }, { "code": null, "e": 1887, "s": 1880, "text": "Picked" }, { "code": null, "e": 1900, "s": 1887, "text": "Python-numpy" }, { "code": null, "e": 1907, "s": 1900, "text": "Python" } ]
CSS - Visibility
A property called visibility allows you to hide an element from view. You can use this property along with JavaScript to create very complex menu and very complex webpage layouts. You may choose to use the visibility property to hide error messages that are only displayed if the user needs to see them, or to hide answers to a quiz until the user selects an option. NOTE − Remember that the source code will still contain whatever is in the invisible paragraph, so you should not use this to hide sensitive information such as credit card details or passwords. The visibility property can take the values listed in the table that follows − visible The box and its contents are shown to the user. hidden The box and its content are made invisible, although they still affect the layout of the page. collapse This is for use only with dynamic table columns and row effects. Here is an example − <html> <head> </head> <body> <p> This paragraph should be visible in normal way. </p> <p style = "visibility:hidden;"> This paragraph should not be visible. </p> </body> </html> It will produce the following result − This paragraph should be visible in normal way. This paragraph should not be visible.
[ { "code": null, "e": 2940, "s": 2760, "text": "A property called visibility allows you to hide an element from view. You can use this property along with JavaScript to create very complex menu and very complex webpage layouts." }, { "code": null, "e": 3127, "s": 2940, "text": "You may choose to use the visibility property to hide error messages that are only displayed if the user needs to see them, or to hide answers to a quiz until the user selects an option." }, { "code": null, "e": 3322, "s": 3127, "text": "NOTE − Remember that the source code will still contain whatever is in the invisible paragraph, so you should not use this to hide sensitive information such as credit card details or passwords." }, { "code": null, "e": 3401, "s": 3322, "text": "The visibility property can take the values listed in the table that follows −" }, { "code": null, "e": 3409, "s": 3401, "text": "visible" }, { "code": null, "e": 3457, "s": 3409, "text": "The box and its contents are shown to the user." }, { "code": null, "e": 3464, "s": 3457, "text": "hidden" }, { "code": null, "e": 3559, "s": 3464, "text": "The box and its content are made invisible, although they still affect the layout of the page." }, { "code": null, "e": 3568, "s": 3559, "text": "collapse" }, { "code": null, "e": 3633, "s": 3568, "text": "This is for use only with dynamic table columns and row effects." }, { "code": null, "e": 3654, "s": 3633, "text": "Here is an example −" }, { "code": null, "e": 3892, "s": 3654, "text": "<html>\n <head>\n </head>\n\n <body>\n <p>\n This paragraph should be visible in normal way.\n </p>\n \n <p style = \"visibility:hidden;\">\n This paragraph should not be visible.\n </p>\n </body>\n</html> " }, { "code": null, "e": 3931, "s": 3892, "text": "It will produce the following result −" }, { "code": null, "e": 3984, "s": 3931, "text": "\n This paragraph should be visible in normal way.\n" } ]
Gradient borders
23 May, 2019 Gradient borders are not directly supported by using CSS. There are two methods to create gradient borders which are listed below: Method 1: Using border-image with gradient: The border is created by using the size and color as transparent in the border property. The gradient is used to define the border-image property. The border-image-slice is set to 1 for a border to properly be displayed. This combination of properties creates a gradient border. Syntax: .border { width: 400px; border: 3px solid transparent; border-image: linear-gradient(to right, green, lightgreen); border-image-slice: 1; padding: 25px; } Example: <!DOCTYPE html><html> <head> <title>Gradient Borders</title> <style> .border { width: 400px; border: 3px solid transparent; border-image: linear-gradient(to right, green, lightgreen); border-image-slice: 1; padding: 25px; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b>Gradient Borders</b> <div class="border"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </div></body> </html> Output: Method 2: Setting the background as a gradient and overlaying the content with padding: This method involves wrapping the element on which the border is to be shown with an element with a normal gradient background. The content in the enclosing div is padded equally to the width of the border required background color of the page. This simulates a gradient border. Syntax: .border { width: 400px; position: relative; background: linear-gradient(to right, green, lightgreen); padding: 3px; } .inner { background: white; padding: 25px; } Example: <!DOCTYPE html><html> <head> <title>Gradient Borders</title> <style> .border { width: 400px; position: relative; background: linear-gradient(to right, green, lightgreen); padding: 3px; } .inner { background: white; padding: 25px; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b>Gradient Borders</b> <div class="border"> <div class="inner"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </div> </div></body> </html> Output: Picked Web Technologies Web technologies Questions 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Remove elements from a JavaScript Array How to get character array from string in JavaScript? Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 159, "s": 28, "text": "Gradient borders are not directly supported by using CSS. There are two methods to create gradient borders which are listed below:" }, { "code": null, "e": 482, "s": 159, "text": "Method 1: Using border-image with gradient: The border is created by using the size and color as transparent in the border property. The gradient is used to define the border-image property. The border-image-slice is set to 1 for a border to properly be displayed. This combination of properties creates a gradient border." }, { "code": null, "e": 490, "s": 482, "text": "Syntax:" }, { "code": null, "e": 665, "s": 490, "text": ".border {\n width: 400px;\n border: 3px solid transparent;\n border-image: linear-gradient(to right, green, lightgreen);\n border-image-slice: 1;\n padding: 25px;\n}" }, { "code": null, "e": 674, "s": 665, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Gradient Borders</title> <style> .border { width: 400px; border: 3px solid transparent; border-image: linear-gradient(to right, green, lightgreen); border-image-slice: 1; padding: 25px; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b>Gradient Borders</b> <div class=\"border\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </div></body> </html> ", "e": 1365, "s": 674, "text": null }, { "code": null, "e": 1373, "s": 1365, "text": "Output:" }, { "code": null, "e": 1740, "s": 1373, "text": "Method 2: Setting the background as a gradient and overlaying the content with padding: This method involves wrapping the element on which the border is to be shown with an element with a normal gradient background. The content in the enclosing div is padded equally to the width of the border required background color of the page. This simulates a gradient border." }, { "code": null, "e": 1748, "s": 1740, "text": "Syntax:" }, { "code": null, "e": 1936, "s": 1748, "text": ".border {\n width: 400px;\n position: relative;\n background: linear-gradient(to right, green, lightgreen);\n padding: 3px;\n}\n.inner {\n background: white;\n padding: 25px;\n}\n" }, { "code": null, "e": 1945, "s": 1936, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Gradient Borders</title> <style> .border { width: 400px; position: relative; background: linear-gradient(to right, green, lightgreen); padding: 3px; } .inner { background: white; padding: 25px; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b>Gradient Borders</b> <div class=\"border\"> <div class=\"inner\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </div> </div></body> </html> ", "e": 2729, "s": 1945, "text": null }, { "code": null, "e": 2737, "s": 2729, "text": "Output:" }, { "code": null, "e": 2744, "s": 2737, "text": "Picked" }, { "code": null, "e": 2761, "s": 2744, "text": "Web Technologies" }, { "code": null, "e": 2788, "s": 2761, "text": "Web technologies Questions" }, { "code": null, "e": 2886, "s": 2788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2947, "s": 2886, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2990, "s": 2947, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3062, "s": 2990, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3102, "s": 3062, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3126, "s": 3102, "text": "REST API (Introduction)" }, { "code": null, "e": 3166, "s": 3126, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3220, "s": 3166, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 3257, "s": 3220, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3296, "s": 3257, "text": "How to set space between the flexbox ?" } ]
JavaScript Array reduce() Method
01 Nov, 2021 Below is the example of Array reduce() method. Example:<!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from the left side </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Subtract: <span id="GFG"></span> <!-- Script to use reduce method --> <script> var arr = [175, 50, 25]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(subofArray); } </script></body> </html> <!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from the left side </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Subtract: <span id="GFG"></span> <!-- Script to use reduce method --> <script> var arr = [175, 50, 25]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(subofArray); } </script></body> </html> Output: The arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue ) Parameter: This method accepts five parameters as mentioned above and described below: function(total, currentValue, index, arr): It is the required parameter and used to run for each element of array. It contains four parameter which are listed below:total: It is required parameter and used to specify the initialValue, or the previously returned value of the function.currentValue: It is required parameter and used to specify the value of the current element.currentIndex: It is optional parameter and used to specify the array index of the current element.arr: It is optional parameter and used to specify the array object the current element belongs to. total: It is required parameter and used to specify the initialValue, or the previously returned value of the function. currentValue: It is required parameter and used to specify the value of the current element. currentIndex: It is optional parameter and used to specify the array index of the current element. arr: It is optional parameter and used to specify the array object the current element belongs to. initialValue: It is optional parameter and used to specify the value to be passed to the function as the initial value. Example 1: This example use reduce() method to return the sum of all array elements. <!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the sum of array elements </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Sum: <span id="GFG"></span> <!-- Script to use reduce method --> <script> var arr = [10, 20, 30, 40, 50, 60]; function sumofArray(sum, num) { return sum + num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(sumofArray); } </script></body> </html> Output: Example 2: This example use reduce() method to return the round sum of all array elements. <!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the sum of array elements </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Sum: <span id="GFG"></span> <!-- Script to use reduce method --> <script> var arr = [1.5, 20.3, 11.1, 40.7]; function sumofArray(sum, num) { return sum + Math.round(num); } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(sumofArray, 0); } </script></body> </html> Output:Supported Browsers: The browsers supported by JavaScript Array reduce() method are listed below: Google Chrome 3 and above Microsoft Edge 12 and above Mozilla Firefox 3.0 and above Safari 5 and above Opera 10.5 and above ysachin2314 javascript-array JavaScript-Methods Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2021" }, { "code": null, "e": 75, "s": 28, "text": "Below is the example of Array reduce() method." }, { "code": null, "e": 859, "s": 75, "text": "Example:<!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from the left side </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Subtract: <span id=\"GFG\"></span> <!-- Script to use reduce method --> <script> var arr = [175, 50, 25]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(subofArray); } </script></body> </html> " }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from the left side </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Subtract: <span id=\"GFG\"></span> <!-- Script to use reduce method --> <script> var arr = [175, 50, 25]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(subofArray); } </script></body> </html> ", "e": 1635, "s": 859, "text": null }, { "code": null, "e": 1643, "s": 1635, "text": "Output:" }, { "code": null, "e": 1875, "s": 1643, "text": "The arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator." }, { "code": null, "e": 1883, "s": 1875, "text": "Syntax:" }, { "code": null, "e": 1963, "s": 1883, "text": "array.reduce( function(total, currentValue, currentIndex, arr), \ninitialValue )" }, { "code": null, "e": 2050, "s": 1963, "text": "Parameter: This method accepts five parameters as mentioned above and described below:" }, { "code": null, "e": 2623, "s": 2050, "text": "function(total, currentValue, index, arr): It is the required parameter and used to run for each element of array. It contains four parameter which are listed below:total: It is required parameter and used to specify the initialValue, or the previously returned value of the function.currentValue: It is required parameter and used to specify the value of the current element.currentIndex: It is optional parameter and used to specify the array index of the current element.arr: It is optional parameter and used to specify the array object the current element belongs to." }, { "code": null, "e": 2743, "s": 2623, "text": "total: It is required parameter and used to specify the initialValue, or the previously returned value of the function." }, { "code": null, "e": 2836, "s": 2743, "text": "currentValue: It is required parameter and used to specify the value of the current element." }, { "code": null, "e": 2935, "s": 2836, "text": "currentIndex: It is optional parameter and used to specify the array index of the current element." }, { "code": null, "e": 3034, "s": 2935, "text": "arr: It is optional parameter and used to specify the array object the current element belongs to." }, { "code": null, "e": 3154, "s": 3034, "text": "initialValue: It is optional parameter and used to specify the value to be passed to the function as the initial value." }, { "code": null, "e": 3239, "s": 3154, "text": "Example 1: This example use reduce() method to return the sum of all array elements." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the sum of array elements </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Sum: <span id=\"GFG\"></span> <!-- Script to use reduce method --> <script> var arr = [10, 20, 30, 40, 50, 60]; function sumofArray(sum, num) { return sum + num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(sumofArray); } </script></body> </html> ", "e": 4004, "s": 3239, "text": null }, { "code": null, "e": 4012, "s": 4004, "text": "Output:" }, { "code": null, "e": 4103, "s": 4012, "text": "Example 2: This example use reduce() method to return the round sum of all array elements." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Array reduce() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the sum of array elements </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Sum: <span id=\"GFG\"></span> <!-- Script to use reduce method --> <script> var arr = [1.5, 20.3, 11.1, 40.7]; function sumofArray(sum, num) { return sum + Math.round(num); } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(sumofArray, 0); } </script></body> </html> ", "e": 4882, "s": 4103, "text": null }, { "code": null, "e": 4986, "s": 4882, "text": "Output:Supported Browsers: The browsers supported by JavaScript Array reduce() method are listed below:" }, { "code": null, "e": 5012, "s": 4986, "text": "Google Chrome 3 and above" }, { "code": null, "e": 5040, "s": 5012, "text": "Microsoft Edge 12 and above" }, { "code": null, "e": 5070, "s": 5040, "text": "Mozilla Firefox 3.0 and above" }, { "code": null, "e": 5089, "s": 5070, "text": "Safari 5 and above" }, { "code": null, "e": 5110, "s": 5089, "text": "Opera 10.5 and above" }, { "code": null, "e": 5122, "s": 5110, "text": "ysachin2314" }, { "code": null, "e": 5139, "s": 5122, "text": "javascript-array" }, { "code": null, "e": 5158, "s": 5139, "text": "JavaScript-Methods" }, { "code": null, "e": 5165, "s": 5158, "text": "Picked" }, { "code": null, "e": 5176, "s": 5165, "text": "JavaScript" }, { "code": null, "e": 5193, "s": 5176, "text": "Web Technologies" } ]
How to Access Index in Python’s for Loop
21 Jun, 2022 In this article, we will discuss how to access index in python for loop in Python Here, we will 4 different methods of Python program to access index of a list using for loop. we will cover different approaches to finding indexes in python for strings, lists, To handle looping requirements, the Python programming language supports the different types of loops. The loops can be executed in different ways in Python. FOR Loops are one of them, and they’re used for sequential traversal. For instance, traversing a list, text, or array , i.e. for (i=0; in; i++). There is a “for in” loop, which is similar to other languages for each loop in Python. We can access the index in Python by using: Using index elementUsing enumerate()Using List ComprehensionsUsing zip() Using index element Using enumerate() Using List Comprehensions Using zip() The index element is used to represent the location of an element in a list. Here we are accessing the index through the list of elements. Here, we are using an iterator variable to iterate through a String. Python3 # create a list of subjectsdata = "GEEKFORGEEKS" print("Indices and Index value in the list:") # display indices in the listfor i in range(len(data)): print(i, data[i]) Output: Indices and Index value in the list: 0 G 1 E 2 E 3 K 4 F 5 O 6 R 7 G 8 E 9 E 10 K 11 S This method is used in for loop in Python get index of item in list which is used to get the index along with the corresponding element over the range using a List in Python. Python3 # create a list of subjectsdata = ["java", "python", "HTML", "PHP"] print("Indices and values in list:") # get the indices and values using enumerate methodfor i in enumerate(data): print(i) Output: Indices and values in list: (0, 'java') (1, 'python') (2, 'HTML') (3, 'PHP') This will make a list of the index and then gives the index and index values. Python3 # create a list of subjectsdata = ["java", "python", "HTML", "PHP"] print("Indices in list:") # get the indices using list comprehension methodprint([i for i in range(len(data))]) print("values in list:") # get the values from indices using list# comprehension methodprint([data[i] for i in range(len(data))]) Output: Indices in list: [0, 1, 2, 3] values in list: ['java', 'python', 'HTML', 'PHP'] The zip method is used to zip the index and values at a time, we have to pass two lists one list is of index elements and another list is of elements. below is the example for Python for loop index and value Python3 # create a index list that stores listindexlist = [0, 1, 2, 3] # create a list of subjectsdata = ["java", "python", "HTML", "PHP"] print("index and values in list:") # get the values from indices using zip methodfor index, value in zip(indexlist, data): print(index, value) Output: index and values in list: 0 java 1 python 2 HTML 3 PHP In order to access the array of items refers to the index number. Use the index operator [ ] to access an item in an array. The index must be an integer. Python3 # Python program to demonstrate# accessing of element from list # importing array moduleimport array as arr # array with int typea = arr.array('i', [1, 2, 3, 4, 5, 6]) # accessing element of arrayprint("Access element is: ", a[0]) # accessing element of arrayprint("Access element is: ", a[3]) # array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # accessing element of arrayprint("Access element is: ", b[1]) # accessing element of arrayprint("Access element is: ", b[2]) Output: Access element is: 1 Access element is: 4 Access element is: 3.2 Access element is: 3.3 kapoorsagar226 surajkumarguptaintern Picked python-basics 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 | os.path.join() method Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 110, "s": 28, "text": "In this article, we will discuss how to access index in python for loop in Python" }, { "code": null, "e": 289, "s": 110, "text": "Here, we will 4 different methods of Python program to access index of a list using for loop. we will cover different approaches to finding indexes in python for strings, lists, " }, { "code": null, "e": 519, "s": 289, "text": "To handle looping requirements, the Python programming language supports the different types of loops. The loops can be executed in different ways in Python. FOR Loops are one of them, and they’re used for sequential traversal. " }, { "code": null, "e": 682, "s": 519, "text": "For instance, traversing a list, text, or array , i.e. for (i=0; in; i++). There is a “for in” loop, which is similar to other languages for each loop in Python. " }, { "code": null, "e": 726, "s": 682, "text": "We can access the index in Python by using:" }, { "code": null, "e": 799, "s": 726, "text": "Using index elementUsing enumerate()Using List ComprehensionsUsing zip()" }, { "code": null, "e": 819, "s": 799, "text": "Using index element" }, { "code": null, "e": 837, "s": 819, "text": "Using enumerate()" }, { "code": null, "e": 863, "s": 837, "text": "Using List Comprehensions" }, { "code": null, "e": 875, "s": 863, "text": "Using zip()" }, { "code": null, "e": 1083, "s": 875, "text": "The index element is used to represent the location of an element in a list. Here we are accessing the index through the list of elements. Here, we are using an iterator variable to iterate through a String." }, { "code": null, "e": 1091, "s": 1083, "text": "Python3" }, { "code": "# create a list of subjectsdata = \"GEEKFORGEEKS\" print(\"Indices and Index value in the list:\") # display indices in the listfor i in range(len(data)): print(i, data[i])", "e": 1264, "s": 1091, "text": null }, { "code": null, "e": 1272, "s": 1264, "text": "Output:" }, { "code": null, "e": 1359, "s": 1272, "text": "Indices and Index value in the list:\n0 G\n1 E\n2 E\n3 K\n4 F\n5 O\n6 R\n7 G\n8 E\n9 E\n10 K\n11 S" }, { "code": null, "e": 1534, "s": 1359, "text": "This method is used in for loop in Python get index of item in list which is used to get the index along with the corresponding element over the range using a List in Python." }, { "code": null, "e": 1542, "s": 1534, "text": "Python3" }, { "code": "# create a list of subjectsdata = [\"java\", \"python\", \"HTML\", \"PHP\"] print(\"Indices and values in list:\") # get the indices and values using enumerate methodfor i in enumerate(data): print(i)", "e": 1737, "s": 1542, "text": null }, { "code": null, "e": 1745, "s": 1737, "text": "Output:" }, { "code": null, "e": 1822, "s": 1745, "text": "Indices and values in list:\n(0, 'java')\n(1, 'python')\n(2, 'HTML')\n(3, 'PHP')" }, { "code": null, "e": 1901, "s": 1822, "text": "This will make a list of the index and then gives the index and index values. " }, { "code": null, "e": 1909, "s": 1901, "text": "Python3" }, { "code": "# create a list of subjectsdata = [\"java\", \"python\", \"HTML\", \"PHP\"] print(\"Indices in list:\") # get the indices using list comprehension methodprint([i for i in range(len(data))]) print(\"values in list:\") # get the values from indices using list# comprehension methodprint([data[i] for i in range(len(data))])", "e": 2221, "s": 1909, "text": null }, { "code": null, "e": 2229, "s": 2221, "text": "Output:" }, { "code": null, "e": 2309, "s": 2229, "text": "Indices in list:\n[0, 1, 2, 3]\nvalues in list:\n['java', 'python', 'HTML', 'PHP']" }, { "code": null, "e": 2517, "s": 2309, "text": "The zip method is used to zip the index and values at a time, we have to pass two lists one list is of index elements and another list is of elements. below is the example for Python for loop index and value" }, { "code": null, "e": 2525, "s": 2517, "text": "Python3" }, { "code": "# create a index list that stores listindexlist = [0, 1, 2, 3] # create a list of subjectsdata = [\"java\", \"python\", \"HTML\", \"PHP\"] print(\"index and values in list:\") # get the values from indices using zip methodfor index, value in zip(indexlist, data): print(index, value)", "e": 2804, "s": 2525, "text": null }, { "code": null, "e": 2812, "s": 2804, "text": "Output:" }, { "code": null, "e": 2867, "s": 2812, "text": "index and values in list:\n0 java\n1 python\n2 HTML\n3 PHP" }, { "code": null, "e": 3021, "s": 2867, "text": "In order to access the array of items refers to the index number. Use the index operator [ ] to access an item in an array. The index must be an integer." }, { "code": null, "e": 3029, "s": 3021, "text": "Python3" }, { "code": "# Python program to demonstrate# accessing of element from list # importing array moduleimport array as arr # array with int typea = arr.array('i', [1, 2, 3, 4, 5, 6]) # accessing element of arrayprint(\"Access element is: \", a[0]) # accessing element of arrayprint(\"Access element is: \", a[3]) # array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # accessing element of arrayprint(\"Access element is: \", b[1]) # accessing element of arrayprint(\"Access element is: \", b[2])", "e": 3508, "s": 3029, "text": null }, { "code": null, "e": 3516, "s": 3508, "text": "Output:" }, { "code": null, "e": 3608, "s": 3516, "text": "Access element is: 1\nAccess element is: 4\nAccess element is: 3.2\nAccess element is: 3.3" }, { "code": null, "e": 3623, "s": 3608, "text": "kapoorsagar226" }, { "code": null, "e": 3645, "s": 3623, "text": "surajkumarguptaintern" }, { "code": null, "e": 3652, "s": 3645, "text": "Picked" }, { "code": null, "e": 3666, "s": 3652, "text": "python-basics" }, { "code": null, "e": 3673, "s": 3666, "text": "Python" }, { "code": null, "e": 3771, "s": 3673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3803, "s": 3771, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3830, "s": 3803, "text": "Python Classes and Objects" }, { "code": null, "e": 3861, "s": 3830, "text": "Python | os.path.join() method" }, { "code": null, "e": 3882, "s": 3861, "text": "Python OOPs Concepts" }, { "code": null, "e": 3905, "s": 3882, "text": "Introduction To PYTHON" }, { "code": null, "e": 3961, "s": 3905, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4003, "s": 3961, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4045, "s": 4003, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4084, "s": 4045, "text": "Python | Get unique values from a list" } ]
DateTime.IsLeapYear() Method in C#
15 Jul, 2021 This method returns an indication of whether the specified year is a leap year or not. Here, the year is always interpreted as a year in the Gregorian calendar. Syntax: public static bool IsLeapYear (int year); Return Value: This method return true if year is a leap year otherwise it returns false. Exception: This method will give ArgumentOutOfRangeException if the year is less than 1 or greater than 9999. Below programs illustrate the use of above-discussed method: Example 1: C# // C# code to demonstrate the// IsLeapYear(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // Checking the leap year between 2000 to 2019 for (int y = 2000; y <= 2019; y++) { // using method if (DateTime.IsLeapYear(y)) { Console.WriteLine("{0} is a Leap Year.", y); } else { Console.WriteLine("{0} is not a Leap Year.", y); } } }} Output: 2000 is a Leap Year. 2001 is not a Leap Year. 2002 is not a Leap Year. 2003 is not a Leap Year. 2004 is a Leap Year. 2005 is not a Leap Year. 2006 is not a Leap Year. 2007 is not a Leap Year. 2008 is a Leap Year. 2009 is not a Leap Year. 2010 is not a Leap Year. 2011 is not a Leap Year. 2012 is a Leap Year. 2013 is not a Leap Year. 2014 is not a Leap Year. 2015 is not a Leap Year. 2016 is a Leap Year. 2017 is not a Leap Year. 2018 is not a Leap Year. 2019 is not a Leap Year. Example 2: C# // C# code to demonstrate the// IsLeapYear(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // using method if (DateTime.IsLeapYear(9999)) { Console.WriteLine("9999 is a Leap Year."); } else { Console.WriteLine("9999 is not a Leap Year."); } // using method will give an error // as year's value is greater than // 9999 if (DateTime.IsLeapYear(10000)) { Console.WriteLine(" 10000 is a Leap Year."); } else { Console.WriteLine("10000 is not a Leap Year."); } }} Runtime Error: Unhandled Exception: System.ArgumentOutOfRangeException: Year must be between 1 and 9999. Parameter name: year Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.isleapyear?view=netframework-4.7.2 sooda367 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class C# | .NET Framework (Basic Architecture and Component Stack) HashSet in C# with Examples Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jul, 2021" }, { "code": null, "e": 189, "s": 28, "text": "This method returns an indication of whether the specified year is a leap year or not. Here, the year is always interpreted as a year in the Gregorian calendar." }, { "code": null, "e": 198, "s": 189, "text": "Syntax: " }, { "code": null, "e": 240, "s": 198, "text": "public static bool IsLeapYear (int year);" }, { "code": null, "e": 329, "s": 240, "text": "Return Value: This method return true if year is a leap year otherwise it returns false." }, { "code": null, "e": 439, "s": 329, "text": "Exception: This method will give ArgumentOutOfRangeException if the year is less than 1 or greater than 9999." }, { "code": null, "e": 500, "s": 439, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 512, "s": 500, "text": "Example 1: " }, { "code": null, "e": 515, "s": 512, "text": "C#" }, { "code": "// C# code to demonstrate the// IsLeapYear(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // Checking the leap year between 2000 to 2019 for (int y = 2000; y <= 2019; y++) { // using method if (DateTime.IsLeapYear(y)) { Console.WriteLine(\"{0} is a Leap Year.\", y); } else { Console.WriteLine(\"{0} is not a Leap Year.\", y); } } }}", "e": 1031, "s": 515, "text": null }, { "code": null, "e": 1040, "s": 1031, "text": "Output: " }, { "code": null, "e": 1520, "s": 1040, "text": "2000 is a Leap Year.\n2001 is not a Leap Year.\n2002 is not a Leap Year.\n2003 is not a Leap Year.\n2004 is a Leap Year.\n2005 is not a Leap Year.\n2006 is not a Leap Year.\n2007 is not a Leap Year.\n2008 is a Leap Year.\n2009 is not a Leap Year.\n2010 is not a Leap Year.\n2011 is not a Leap Year.\n2012 is a Leap Year.\n2013 is not a Leap Year.\n2014 is not a Leap Year.\n2015 is not a Leap Year.\n2016 is a Leap Year.\n2017 is not a Leap Year.\n2018 is not a Leap Year.\n2019 is not a Leap Year." }, { "code": null, "e": 1531, "s": 1520, "text": "Example 2:" }, { "code": null, "e": 1534, "s": 1531, "text": "C#" }, { "code": "// C# code to demonstrate the// IsLeapYear(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // using method if (DateTime.IsLeapYear(9999)) { Console.WriteLine(\"9999 is a Leap Year.\"); } else { Console.WriteLine(\"9999 is not a Leap Year.\"); } // using method will give an error // as year's value is greater than // 9999 if (DateTime.IsLeapYear(10000)) { Console.WriteLine(\" 10000 is a Leap Year.\"); } else { Console.WriteLine(\"10000 is not a Leap Year.\"); } }}", "e": 2194, "s": 1534, "text": null }, { "code": null, "e": 2209, "s": 2194, "text": "Runtime Error:" }, { "code": null, "e": 2322, "s": 2209, "text": "Unhandled Exception: System.ArgumentOutOfRangeException: Year must be between 1 and 9999. Parameter name: year " }, { "code": null, "e": 2335, "s": 2322, "text": "Reference: " }, { "code": null, "e": 2430, "s": 2335, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.isleapyear?view=netframework-4.7.2" }, { "code": null, "e": 2441, "s": 2432, "text": "sooda367" }, { "code": null, "e": 2464, "s": 2441, "text": "CSharp DateTime Struct" }, { "code": null, "e": 2478, "s": 2464, "text": "CSharp-method" }, { "code": null, "e": 2481, "s": 2478, "text": "C#" }, { "code": null, "e": 2579, "s": 2481, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2622, "s": 2579, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2671, "s": 2622, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2694, "s": 2671, "text": "Extension Method in C#" }, { "code": null, "e": 2710, "s": 2694, "text": "C# | List Class" }, { "code": null, "e": 2771, "s": 2710, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2799, "s": 2771, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2822, "s": 2799, "text": "Switch Statement in C#" }, { "code": null, "e": 2847, "s": 2822, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2869, "s": 2847, "text": "Partial Classes in C#" } ]
numpy.arange() in Python
08 Nov, 2021 The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop) Parameters : start : [optional] start of interval range. By default start = 0 stop : end of interval range step : [optional] step size of interval. By default step size = 1, For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. dtype : type of output array Return: Array of evenly spaced values. Length of array being generated = Ceil((Stop - Start) / Step) Example: Python3 # Python Programming illustrating# numpy.arange method import numpy as geek print("A\n", geek.arange(4).reshape(2, 2), "\n")print("A\n", geek.arange(4, 10), "\n")print("A\n", geek.arange(4, 20, 3), "\n") Output : A [[0 1] [2 3]] A [4 5 6 7 8 9] A [ 4 7 10 13 16 19] Note: These NumPy-Python programs won’t run on onlineID, so run them on your systems to explore them. The advantage of numpy.arange() over the normal in-built range() function is that it allows us to generate sequences of numbers that are not integers. Example: Python3 # Python Programming illustrating# numpy.arange method import numpy as np # Printing all numbers from 1 to# 2 in steps of 0.1print(np.arange(1, 2, 0.1)) Output: [1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9] If you try it with the range() function, you get a TypeError. This article is contributed by Mohit Gupta_OMG . 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. AshwinShenoy adnanirshad158 shreybitz akshaysingh98088 johannes124 Python numpy-arrayCreation Python-numpy 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 ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Nov, 2021" }, { "code": null, "e": 224, "s": 54, "text": "The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop) " }, { "code": null, "e": 238, "s": 224, "text": "Parameters : " }, { "code": null, "e": 522, "s": 238, "text": "start : [optional] start of interval range. By default start = 0\nstop : end of interval range\nstep : [optional] step size of interval. By default step size = 1, \nFor any output out, this is the distance between two adjacent values, out[i+1] - out[i]. \ndtype : type of output array" }, { "code": null, "e": 531, "s": 522, "text": "Return: " }, { "code": null, "e": 626, "s": 531, "text": "Array of evenly spaced values.\nLength of array being generated = Ceil((Stop - Start) / Step) " }, { "code": null, "e": 635, "s": 626, "text": "Example:" }, { "code": null, "e": 643, "s": 635, "text": "Python3" }, { "code": "# Python Programming illustrating# numpy.arange method import numpy as geek print(\"A\\n\", geek.arange(4).reshape(2, 2), \"\\n\")print(\"A\\n\", geek.arange(4, 10), \"\\n\")print(\"A\\n\", geek.arange(4, 20, 3), \"\\n\")", "e": 847, "s": 643, "text": null }, { "code": null, "e": 857, "s": 847, "text": "Output : " }, { "code": null, "e": 917, "s": 857, "text": "A\n [[0 1]\n [2 3]]\n\nA\n [4 5 6 7 8 9]\n\nA\n [ 4 7 10 13 16 19]" }, { "code": null, "e": 924, "s": 917, "text": "Note: " }, { "code": null, "e": 1020, "s": 924, "text": "These NumPy-Python programs won’t run on onlineID, so run them on your systems to explore them." }, { "code": null, "e": 1171, "s": 1020, "text": "The advantage of numpy.arange() over the normal in-built range() function is that it allows us to generate sequences of numbers that are not integers." }, { "code": null, "e": 1180, "s": 1171, "text": "Example:" }, { "code": null, "e": 1188, "s": 1180, "text": "Python3" }, { "code": "# Python Programming illustrating# numpy.arange method import numpy as np # Printing all numbers from 1 to# 2 in steps of 0.1print(np.arange(1, 2, 0.1))", "e": 1341, "s": 1188, "text": null }, { "code": null, "e": 1350, "s": 1341, "text": "Output: " }, { "code": null, "e": 1392, "s": 1350, "text": "[1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]" }, { "code": null, "e": 1454, "s": 1392, "text": "If you try it with the range() function, you get a TypeError." }, { "code": null, "e": 1878, "s": 1454, "text": "This article is contributed by Mohit Gupta_OMG . 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": 1891, "s": 1878, "text": "AshwinShenoy" }, { "code": null, "e": 1906, "s": 1891, "text": "adnanirshad158" }, { "code": null, "e": 1916, "s": 1906, "text": "shreybitz" }, { "code": null, "e": 1933, "s": 1916, "text": "akshaysingh98088" }, { "code": null, "e": 1945, "s": 1933, "text": "johannes124" }, { "code": null, "e": 1972, "s": 1945, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 1985, "s": 1972, "text": "Python-numpy" }, { "code": null, "e": 1992, "s": 1985, "text": "Python" }, { "code": null, "e": 2090, "s": 1992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2132, "s": 2090, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2154, "s": 2132, "text": "Enumerate() in Python" }, { "code": null, "e": 2186, "s": 2154, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2212, "s": 2186, "text": "Python String | replace()" }, { "code": null, "e": 2241, "s": 2212, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2268, "s": 2241, "text": "Python Classes and Objects" }, { "code": null, "e": 2289, "s": 2268, "text": "Python OOPs Concepts" }, { "code": null, "e": 2312, "s": 2289, "text": "Introduction To PYTHON" }, { "code": null, "e": 2343, "s": 2312, "text": "Python | os.path.join() method" } ]
HTML | <body> alink Attribute
05 Jan, 2022 The HTML <body> alink Attribute is used to specify the color of an active link in a document. Note: The HTML <body> alink attribute is not supported by HTML5. Syntax: <body alink="color_name|hex_number|rgb_number"> Attribute Values: color_name: It specifies the name of the color of an active link. hex_number: It specifies the color of the activated link in terms of hex code. rgb_number: It specifies the color of the activated link in terms of RGB value. Example: <!DOCTYPE html> <html> <head> <title> HTML body alink Attribute </title> </head> <body alink="red" link="blue"> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>HTML <body> alink Attribute</h2> <a href="#"> A computer science portal for geeks </a> </center> </body> </html> Output: Supported Browsers: The browser supported by HTML <body> alink attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? 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": "\n05 Jan, 2022" }, { "code": null, "e": 122, "s": 28, "text": "The HTML <body> alink Attribute is used to specify the color of an active link in a document." }, { "code": null, "e": 187, "s": 122, "text": "Note: The HTML <body> alink attribute is not supported by HTML5." }, { "code": null, "e": 195, "s": 187, "text": "Syntax:" }, { "code": null, "e": 243, "s": 195, "text": "<body alink=\"color_name|hex_number|rgb_number\">" }, { "code": null, "e": 261, "s": 243, "text": "Attribute Values:" }, { "code": null, "e": 327, "s": 261, "text": "color_name: It specifies the name of the color of an active link." }, { "code": null, "e": 406, "s": 327, "text": "hex_number: It specifies the color of the activated link in terms of hex code." }, { "code": null, "e": 486, "s": 406, "text": "rgb_number: It specifies the color of the activated link in terms of RGB value." }, { "code": null, "e": 495, "s": 486, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML body alink Attribute </title> </head> <body alink=\"red\" link=\"blue\"> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>HTML <body> alink Attribute</h2> <a href=\"#\"> A computer science portal for geeks </a> </center> </body> </html> ", "e": 917, "s": 495, "text": null }, { "code": null, "e": 925, "s": 917, "text": "Output:" }, { "code": null, "e": 1016, "s": 925, "text": "Supported Browsers: The browser supported by HTML <body> alink attribute are listed below:" }, { "code": null, "e": 1030, "s": 1016, "text": "Google Chrome" }, { "code": null, "e": 1048, "s": 1030, "text": "Internet Explorer" }, { "code": null, "e": 1056, "s": 1048, "text": "Firefox" }, { "code": null, "e": 1063, "s": 1056, "text": "Safari" }, { "code": null, "e": 1069, "s": 1063, "text": "Opera" }, { "code": null, "e": 1083, "s": 1069, "text": "ManasChhabra2" }, { "code": null, "e": 1099, "s": 1083, "text": "HTML-Attributes" }, { "code": null, "e": 1104, "s": 1099, "text": "HTML" }, { "code": null, "e": 1121, "s": 1104, "text": "Web Technologies" }, { "code": null, "e": 1126, "s": 1121, "text": "HTML" }, { "code": null, "e": 1224, "s": 1126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1248, "s": 1224, "text": "REST API (Introduction)" }, { "code": null, "e": 1285, "s": 1248, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1313, "s": 1285, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1352, "s": 1313, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1402, "s": 1352, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1435, "s": 1402, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1496, "s": 1435, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1539, "s": 1496, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1611, "s": 1539, "text": "Differences between Functional Components and Class Components in React" } ]
How to Install PHP on Linux?
06 Dec, 2021 PHP is a general-purpose scripting language that is especially used in web development. It was created in 1994 by Rasmus Lerdorf. It is used to manage dynamic content, databases, session tracking, and build entire e-commerce websites and Linux is an open-source operating system. It was first released on 17 September 1991 by Linus Torvalds. In this article, we will know that How can we install PHP on Linux operating system. An ANSI C compiler. Module-specific components like GD graphics libraries or PDF libraries. Optional: Autoconf 2.59+ (for PHP versions < 7.0), Autoconf 2.64+ (for PHP versions > 7.2), Automake 1.4+, Libtool 1.4+, re2c 0.13.4+, and Bison. Follow the below steps to install PHP on Linux: Step 1: Open your terminal in Linux On your Linux computer open the terminal. You can also open the terminal by using Ctrl+Alt+T. Step 2: Update your packages On your terminal update your packages using the following command. # sudo apt-get update Step 3: Upgrade your packages Now install available upgrades of all packages currently installed on the system using the following command. # sudo apt-get upgrade Step 4: Install PHP Now we are ready to install PHP. The following command will install PHP on our system. # sudo apt-get install php After entering the above command a prompt will appear enter Y and press enter key. Within few minutes the latest version of PHP along with several extensions will install on your Linux system. You can verify the PHP version after installation using the following command. # php --version As you can see the output PHP version shown that means we have successfully installed PHP in our system. how-to-install PHP-basics Picked How To Installation Guide PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers? How to Install Git in VS Code? Installation of Node.js on Linux Installation of Node.js on Windows How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2021" }, { "code": null, "e": 457, "s": 28, "text": "PHP is a general-purpose scripting language that is especially used in web development. It was created in 1994 by Rasmus Lerdorf. It is used to manage dynamic content, databases, session tracking, and build entire e-commerce websites and Linux is an open-source operating system. It was first released on 17 September 1991 by Linus Torvalds. In this article, we will know that How can we install PHP on Linux operating system." }, { "code": null, "e": 477, "s": 457, "text": "An ANSI C compiler." }, { "code": null, "e": 549, "s": 477, "text": "Module-specific components like GD graphics libraries or PDF libraries." }, { "code": null, "e": 695, "s": 549, "text": "Optional: Autoconf 2.59+ (for PHP versions < 7.0), Autoconf 2.64+ (for PHP versions > 7.2), Automake 1.4+, Libtool 1.4+, re2c 0.13.4+, and Bison." }, { "code": null, "e": 743, "s": 695, "text": "Follow the below steps to install PHP on Linux:" }, { "code": null, "e": 779, "s": 743, "text": "Step 1: Open your terminal in Linux" }, { "code": null, "e": 873, "s": 779, "text": "On your Linux computer open the terminal. You can also open the terminal by using Ctrl+Alt+T." }, { "code": null, "e": 902, "s": 873, "text": "Step 2: Update your packages" }, { "code": null, "e": 969, "s": 902, "text": "On your terminal update your packages using the following command." }, { "code": null, "e": 994, "s": 969, "text": "# sudo apt-get update" }, { "code": null, "e": 1024, "s": 994, "text": "Step 3: Upgrade your packages" }, { "code": null, "e": 1134, "s": 1024, "text": "Now install available upgrades of all packages currently installed on the system using the following command." }, { "code": null, "e": 1160, "s": 1134, "text": "# sudo apt-get upgrade" }, { "code": null, "e": 1180, "s": 1160, "text": "Step 4: Install PHP" }, { "code": null, "e": 1267, "s": 1180, "text": "Now we are ready to install PHP. The following command will install PHP on our system." }, { "code": null, "e": 1297, "s": 1267, "text": "# sudo apt-get install php" }, { "code": null, "e": 1490, "s": 1297, "text": "After entering the above command a prompt will appear enter Y and press enter key. Within few minutes the latest version of PHP along with several extensions will install on your Linux system." }, { "code": null, "e": 1569, "s": 1490, "text": "You can verify the PHP version after installation using the following command." }, { "code": null, "e": 1588, "s": 1569, "text": "# php --version" }, { "code": null, "e": 1693, "s": 1588, "text": "As you can see the output PHP version shown that means we have successfully installed PHP in our system." }, { "code": null, "e": 1708, "s": 1693, "text": "how-to-install" }, { "code": null, "e": 1719, "s": 1708, "text": "PHP-basics" }, { "code": null, "e": 1726, "s": 1719, "text": "Picked" }, { "code": null, "e": 1733, "s": 1726, "text": "How To" }, { "code": null, "e": 1752, "s": 1733, "text": "Installation Guide" }, { "code": null, "e": 1756, "s": 1752, "text": "PHP" }, { "code": null, "e": 1760, "s": 1756, "text": "PHP" }, { "code": null, "e": 1858, "s": 1760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1907, "s": 1858, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 1949, "s": 1907, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 1988, "s": 1949, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 2042, "s": 1988, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 2073, "s": 2042, "text": "How to Install Git in VS Code?" }, { "code": null, "e": 2106, "s": 2073, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2141, "s": 2106, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2183, "s": 2141, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 2222, "s": 2183, "text": "How to Install and Use NVM on Windows?" } ]
PHP | check if a number is Even or Odd
31 Jul, 2021 A number is called even if the number is divisible by 2 and is called odd if it is not divisible by 2. Given a number, we need to check whether it is odd or even in PHP. Examples : Input : 42 Output : Even Explanation: The number 42 is divisible by 2 Input : 39 Output : Odd Explanation: The number 39 is not divisible by 2 We can solve this problem in two different ways as described below: Using modulo (%) operator: This is the simplest method of checking for even and odd and in this method, we simply check whether the number is divisible by 2 or not using the modulo ‘%’ operator.Below program explains the above approach:PHPPHP<?php// PHP code to check whether the number // is Even or Odd in Normal wayfunction check($number){ if($number % 2 == 0){ echo "Even"; } else{ echo "Odd"; }} // Driver Code$number = 39;check($number)?>Output :Odd Time Complexity: O(1)Recursive method: In the recursive approach, we reduce the number by 2 in each recursive call. If the final number is 0 then its even or else it is 1, the result will be odd.Below is the implementation of above approach:PHPPHP<?php// Recursive function to check whether// the number is Even or Odd function check($number){ if($number == 0) return 1; else if($number == 1) return 0; else if($number<0) return check(-$number); else return check($number-2); } // Driver Code$number = 39;if(check($number)) echo "Even";else echo "Odd";?>Output :Odd Time Complexity: O(n)Using Bit Manipulation:In this method we will find bit-wise AND of the number with 1. If the bit-wise AND is 1, then the number is odd, else even.Below is the implementation of above idea.PHPPHP<?php// PHP code to check whether the number // is Even or Odd using Bitwise Operatorfunction check($number){ // One $one = 1; // Bitwise AND $bitwiseAnd = $number & $one; if($bitwiseAnd == 1) { echo "Odd"; } else{ echo "Even"; }} // Driver Code$number = 39;check($number)?>Output :Odd Time Complexity: O(1) Using modulo (%) operator: This is the simplest method of checking for even and odd and in this method, we simply check whether the number is divisible by 2 or not using the modulo ‘%’ operator.Below program explains the above approach:PHPPHP<?php// PHP code to check whether the number // is Even or Odd in Normal wayfunction check($number){ if($number % 2 == 0){ echo "Even"; } else{ echo "Odd"; }} // Driver Code$number = 39;check($number)?>Output :Odd Time Complexity: O(1) Below program explains the above approach: PHP <?php// PHP code to check whether the number // is Even or Odd in Normal wayfunction check($number){ if($number % 2 == 0){ echo "Even"; } else{ echo "Odd"; }} // Driver Code$number = 39;check($number)?> Odd Time Complexity: O(1) Recursive method: In the recursive approach, we reduce the number by 2 in each recursive call. If the final number is 0 then its even or else it is 1, the result will be odd.Below is the implementation of above approach:PHPPHP<?php// Recursive function to check whether// the number is Even or Odd function check($number){ if($number == 0) return 1; else if($number == 1) return 0; else if($number<0) return check(-$number); else return check($number-2); } // Driver Code$number = 39;if(check($number)) echo "Even";else echo "Odd";?>Output :Odd Time Complexity: O(n) PHP <?php// Recursive function to check whether// the number is Even or Odd function check($number){ if($number == 0) return 1; else if($number == 1) return 0; else if($number<0) return check(-$number); else return check($number-2); } // Driver Code$number = 39;if(check($number)) echo "Even";else echo "Odd";?> Odd Time Complexity: O(n) Using Bit Manipulation:In this method we will find bit-wise AND of the number with 1. If the bit-wise AND is 1, then the number is odd, else even.Below is the implementation of above idea.PHPPHP<?php// PHP code to check whether the number // is Even or Odd using Bitwise Operatorfunction check($number){ // One $one = 1; // Bitwise AND $bitwiseAnd = $number & $one; if($bitwiseAnd == 1) { echo "Odd"; } else{ echo "Even"; }} // Driver Code$number = 39;check($number)?>Output :Odd Time Complexity: O(1) Below is the implementation of above idea. PHP <?php// PHP code to check whether the number // is Even or Odd using Bitwise Operatorfunction check($number){ // One $one = 1; // Bitwise AND $bitwiseAnd = $number & $one; if($bitwiseAnd == 1) { echo "Odd"; } else{ echo "Even"; }} // Driver Code$number = 39;check($number)?> Odd Time Complexity: O(1) 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. ShivamKD PHP-basics school-programming PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2021" }, { "code": null, "e": 198, "s": 28, "text": "A number is called even if the number is divisible by 2 and is called odd if it is not divisible by 2. Given a number, we need to check whether it is odd or even in PHP." }, { "code": null, "e": 209, "s": 198, "text": "Examples :" }, { "code": null, "e": 354, "s": 209, "text": "Input : 42\nOutput : Even\nExplanation: The number 42 is divisible by 2\n\nInput : 39\nOutput : Odd\nExplanation: The number 39 is not divisible by 2\n" }, { "code": null, "e": 422, "s": 354, "text": "We can solve this problem in two different ways as described below:" }, { "code": null, "e": 2110, "s": 422, "text": "Using modulo (%) operator: This is the simplest method of checking for even and odd and in this method, we simply check whether the number is divisible by 2 or not using the modulo ‘%’ operator.Below program explains the above approach:PHPPHP<?php// PHP code to check whether the number // is Even or Odd in Normal wayfunction check($number){ if($number % 2 == 0){ echo \"Even\"; } else{ echo \"Odd\"; }} // Driver Code$number = 39;check($number)?>Output :Odd\nTime Complexity: O(1)Recursive method: In the recursive approach, we reduce the number by 2 in each recursive call. If the final number is 0 then its even or else it is 1, the result will be odd.Below is the implementation of above approach:PHPPHP<?php// Recursive function to check whether// the number is Even or Odd function check($number){ if($number == 0) return 1; else if($number == 1) return 0; else if($number<0) return check(-$number); else return check($number-2); } // Driver Code$number = 39;if(check($number)) echo \"Even\";else echo \"Odd\";?>Output :Odd\nTime Complexity: O(n)Using Bit Manipulation:In this method we will find bit-wise AND of the number with 1. If the bit-wise AND is 1, then the number is odd, else even.Below is the implementation of above idea.PHPPHP<?php// PHP code to check whether the number // is Even or Odd using Bitwise Operatorfunction check($number){ // One $one = 1; // Bitwise AND $bitwiseAnd = $number & $one; if($bitwiseAnd == 1) { echo \"Odd\"; } else{ echo \"Even\"; }} // Driver Code$number = 39;check($number)?>Output :Odd\nTime Complexity: O(1)" }, { "code": null, "e": 2616, "s": 2110, "text": "Using modulo (%) operator: This is the simplest method of checking for even and odd and in this method, we simply check whether the number is divisible by 2 or not using the modulo ‘%’ operator.Below program explains the above approach:PHPPHP<?php// PHP code to check whether the number // is Even or Odd in Normal wayfunction check($number){ if($number % 2 == 0){ echo \"Even\"; } else{ echo \"Odd\"; }} // Driver Code$number = 39;check($number)?>Output :Odd\nTime Complexity: O(1)" }, { "code": null, "e": 2659, "s": 2616, "text": "Below program explains the above approach:" }, { "code": null, "e": 2663, "s": 2659, "text": "PHP" }, { "code": "<?php// PHP code to check whether the number // is Even or Odd in Normal wayfunction check($number){ if($number % 2 == 0){ echo \"Even\"; } else{ echo \"Odd\"; }} // Driver Code$number = 39;check($number)?>", "e": 2894, "s": 2663, "text": null }, { "code": null, "e": 2899, "s": 2894, "text": "Odd\n" }, { "code": null, "e": 2921, "s": 2899, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3542, "s": 2921, "text": "Recursive method: In the recursive approach, we reduce the number by 2 in each recursive call. If the final number is 0 then its even or else it is 1, the result will be odd.Below is the implementation of above approach:PHPPHP<?php// Recursive function to check whether// the number is Even or Odd function check($number){ if($number == 0) return 1; else if($number == 1) return 0; else if($number<0) return check(-$number); else return check($number-2); } // Driver Code$number = 39;if(check($number)) echo \"Even\";else echo \"Odd\";?>Output :Odd\nTime Complexity: O(n)" }, { "code": null, "e": 3546, "s": 3542, "text": "PHP" }, { "code": "<?php// Recursive function to check whether// the number is Even or Odd function check($number){ if($number == 0) return 1; else if($number == 1) return 0; else if($number<0) return check(-$number); else return check($number-2); } // Driver Code$number = 39;if(check($number)) echo \"Even\";else echo \"Odd\";?>", "e": 3908, "s": 3546, "text": null }, { "code": null, "e": 3913, "s": 3908, "text": "Odd\n" }, { "code": null, "e": 3935, "s": 3913, "text": "Time Complexity: O(n)" }, { "code": null, "e": 4498, "s": 3935, "text": "Using Bit Manipulation:In this method we will find bit-wise AND of the number with 1. If the bit-wise AND is 1, then the number is odd, else even.Below is the implementation of above idea.PHPPHP<?php// PHP code to check whether the number // is Even or Odd using Bitwise Operatorfunction check($number){ // One $one = 1; // Bitwise AND $bitwiseAnd = $number & $one; if($bitwiseAnd == 1) { echo \"Odd\"; } else{ echo \"Even\"; }} // Driver Code$number = 39;check($number)?>Output :Odd\nTime Complexity: O(1)" }, { "code": null, "e": 4541, "s": 4498, "text": "Below is the implementation of above idea." }, { "code": null, "e": 4545, "s": 4541, "text": "PHP" }, { "code": "<?php// PHP code to check whether the number // is Even or Odd using Bitwise Operatorfunction check($number){ // One $one = 1; // Bitwise AND $bitwiseAnd = $number & $one; if($bitwiseAnd == 1) { echo \"Odd\"; } else{ echo \"Even\"; }} // Driver Code$number = 39;check($number)?>", "e": 4881, "s": 4545, "text": null }, { "code": null, "e": 4886, "s": 4881, "text": "Odd\n" }, { "code": null, "e": 4908, "s": 4886, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5077, "s": 4908, "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": 5086, "s": 5077, "text": "ShivamKD" }, { "code": null, "e": 5097, "s": 5086, "text": "PHP-basics" }, { "code": null, "e": 5116, "s": 5097, "text": "school-programming" }, { "code": null, "e": 5120, "s": 5116, "text": "PHP" }, { "code": null, "e": 5137, "s": 5120, "text": "Web Technologies" }, { "code": null, "e": 5141, "s": 5137, "text": "PHP" } ]
Channel Assignment Problem
23 Jun, 2022 There are M transmitter and N receiver stations. Given a matrix that keeps track of the number of packets to be transmitted from a given transmitter to a receiver. If the (i; j)-th entry of the matrix is k, it means at that time the station i has k packets for transmission to station j. During a time slot, a transmitter can send only one packet and a receiver can receive only one packet. Find the channel assignments so that maximum number of packets are transferred from transmitters to receivers during the next time slot. Example: 0 2 0 3 0 1 2 4 0 The above is the input format. We call the above matrix M. Each value M[i; j] represents the number of packets Transmitter ‘i’ has to send to Receiver ‘j’. The output should be: The number of maximum packets sent in the time slot is 3 T1 -> R2 T2 -> R3 T3 -> R1 Note that the maximum number of packets that can be transferred in any slot is min(M, N). Algorithm: The channel assignment problem between sender and receiver can be easily transformed into Maximum Bipartite Matching(MBP) problem that can be solved by converting it into a flow network. Step 1: Build a Flow Network There must be a source and sink in a flow network. So we add a dummy source and add edges from source to all senders. Similarly, add edges from all receivers to dummy sink. The capacity of all added edges is marked as 1 unit. Step 2: Find the maximum flow. We use Ford-Fulkerson algorithm to find the maximum flow in the flow network built in step 1. The maximum flow is actually the maximum number of packets that can be transmitted without bandwidth interference in a time slot. Implementation: Let us first define input and output forms. Input is in the form of Edmonds matrix which is a 2D array ‘table[M][N]‘ with M rows (for M senders) and N columns (for N receivers). The value table[i][j] is the number of packets that has to be sent from transmitter ‘i’ to receiver ‘j’. Output is the maximum number of packets that can be transmitted without bandwidth interference in a time slot. A simple way to implement this is to create a matrix that represents adjacency matrix representation of a directed graph with M+N+2 vertices. Call the fordFulkerson() for the matrix. This implementation requires O((M+N)*(M+N)) extra space. Extra space can be reduced and code can be simplified using the fact that the graph is bipartite. The idea is to use DFS traversal to find a receiver for a transmitter (similar to augmenting path in Ford-Fulkerson). We call bpm() for every applicant, bpm() is the DFS based function that tries all possibilities to assign a receiver to the sender. In bpm(), we one by one try all receivers that a sender ‘u’ is interested in until we find a receiver or all receivers are tried without luck. For every receiver we try, we do following: If a receiver is not assigned to anybody, we simply assign it to the sender and return true. If a receiver is assigned to somebody else say x, then we recursively check whether x can be assigned some other receiver. To make sure that x doesn’t get the same receiver again, we mark the receiver ‘v’ as seen before we make recursive call for x. If x can get other receiver, we change the sender for receiver ‘v’ and return true. We use an array maxR[0..N-1] that stores the senders assigned to different receivers. If bmp() returns true, then it means that there is an augmenting path in flow network and 1 unit of flow is added to the result in maxBPM(). Time and space complexity analysis: In case of bipartite matching problem, F ? |V| since there can be only |V| possible edges coming out from source node. So the total running time is O(m’n) = O((m + n)n). The space complexity is also substantially reduced from O ((M+N)*(M+N)) to just a single dimensional array of size M thus storing the mapping between M and N. C++ Java Python3 C# Javascript #include <iostream>#include <string.h>#include <vector>#define M 3#define N 4using namespace std; // A Depth First Search based recursive function that returns true// if a matching for vertex u is possiblebool bpm(int table[M][N], int u, bool seen[], int matchR[]){ // Try every receiver one by one for (int v = 0; v < N; v++) { // If sender u has packets to send to receiver v and // receiver v is not already mapped to any other sender // just check if the number of packets is greater than '0' // because only one packet can be sent in a time frame anyways if (table[u][v]>0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to any sender OR // previously assigned sender for receiver v (which is // matchR[v]) has an alternate receiver available. Since // v is marked as visited in the above line, matchR[v] in // the following recursive call will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets that can be sent parallelly in 1// time slot from sender to receiverint maxBPM(int table[M][N]){ // An array to keep track of the receivers assigned to the senders. // The value of matchR[i] is the sender ID assigned to receiver i. // the value -1 indicates nobody is assigned. int matchR[N]; // Initially all receivers are not mapped to any senders memset(matchR, -1, sizeof(matchR)); int result = 0; // Count of receivers assigned to senders for (int u = 0; u < M; u++) { // Mark all receivers as not seen for next sender bool seen[N]; memset(seen, 0, sizeof(seen)); // Find if the sender 'u' can be assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } cout << "The number of maximum packets sent in the time slot is " << result << "\n"; for (int x=0; x<N; x++) if (matchR[x]+1!=0) cout << "T" << matchR[x]+1 << "-> R" << x+1 << "\n"; return result;} // Driver program to test above functionint main(){ int table[M][N] = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; int max_flow = maxBPM(table); return 0;} import java.util.*;class GFG{static int M = 3;static int N = 3; // A Depth First Search based recursive function// that returns true if a matching for vertex u is possiblestatic boolean bpm(int table[][], int u, boolean seen[], int matchR[]){ // Try every receiver one by one for (int v = 0; v < N; v++) { // If sender u has packets to send // to receiver v and receiver v is not // already mapped to any other sender // just check if the number of packets is // greater than '0' because only one packet // can be sent in a time frame anyways if (table[u][v] > 0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to // any sender OR previously assigned sender // for receiver v (which is matchR[v]) has an // alternate receiver available. Since v is // marked as visited in the above line, // matchR[v] in the following recursive call // will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets// that can be sent parallelly in// 1 time slot from sender to receiverstatic int maxBPM(int table[][]){ // An array to keep track of the receivers // assigned to the senders. The value of matchR[i] // is the sender ID assigned to receiver i. // The value -1 indicates nobody is assigned. int []matchR = new int[N]; // Initially all receivers are // not mapped to any senders Arrays.fill(matchR, -1); int result = 0; // Count of receivers assigned to senders for (int u = 0; u < M; u++) { // Mark all receivers as not seen for next sender boolean []seen = new boolean[N]; Arrays.fill(seen, false); // Find if the sender 'u' can be // assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } System.out.println("The number of maximum packets" + " sent in the time slot is " + result); for (int x = 0; x < N; x++) if (matchR[x] + 1 != 0) System.out.println("T" + (matchR[x] + 1) + "-> R" + (x + 1)); return result;} // Driver Codepublic static void main(String[] args){ int table[][] = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; maxBPM(table);}} // This code is contributed by Rajput-Ji # A Depth First Search based recursive# function that returns true if a matching# for vertex u is possibledef bpm(table, u, seen, matchR): global M, N # Try every receiver one by one for v in range(N): # If sender u has packets to send to # receiver v and receiver v is not # already mapped to any other sender # just check if the number of packets # is greater than '0' because only one # packet can be sent in a time frame anyways if (table[u][v] > 0 and not seen[v]): seen[v] = True # Mark v as visited # If receiver 'v' is not assigned to any # sender OR previously assigned sender # for receiver v (which is matchR[v]) has # an alternate receiver available. Since # v is marked as visited in the above line, # matchR[v] in the following recursive call # will not get receiver 'v' again if (matchR[v] < 0 or bpm(table, matchR[v], seen, matchR)): matchR[v] = u return True return False # Returns maximum number of packets# that can be sent parallelly in 1# time slot from sender to receiverdef maxBPM(table): global M, N # An array to keep track of the receivers # assigned to the senders. The value of # matchR[i] is the sender ID assigned to # receiver i. The value -1 indicates nobody # is assigned. # Initially all receivers are not mapped # to any senders matchR = [-1] * N result = 0 # Count of receivers assigned to senders for u in range(M): # Mark all receivers as not seen # for next sender seen = [0] * N # Find if the sender 'u' can be assigned # to the receiver if (bpm(table, u, seen, matchR)): result += 1 print("The number of maximum packets sent", "in the time slot is", result) for x in range(N): if (matchR[x] + 1 != 0): print("T", matchR[x] + 1, "-> R", x + 1) return result # Driver CodeM = 3N = 4 table = [[0, 2, 0], [3, 0, 1], [2, 4, 0]]max_flow = maxBPM(table) # This code is contributed by PranchalK // C# implementation of the above approachusing System; class GFG{static int M = 3;static int N = 3; // A Depth First Search based recursive function// that returns true if a matching for vertex u is possiblestatic Boolean bpm(int [,]table, int u, Boolean []seen, int []matchR){ // Try every receiver one by one for (int v = 0; v < N; v++) { // If sender u has packets to send // to receiver v and receiver v is not // already mapped to any other sender // just check if the number of packets is // greater than '0' because only one packet // can be sent in a time frame anyways if (table[u, v] > 0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to // any sender OR previously assigned sender // for receiver v (which is matchR[v]) has an // alternate receiver available. Since v is // marked as visited in the above line, // matchR[v] in the following recursive call // will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets// that can be sent parallelly in// 1 time slot from sender to receiverstatic int maxBPM(int [,]table){ // An array to keep track of the receivers // assigned to the senders. The value of matchR[i] // is the sender ID assigned to receiver i. // The value -1 indicates nobody is assigned. int []matchR = new int[N]; // Initially all receivers are // not mapped to any senders for(int i = 0; i < N; i++) matchR[i] = -1; int result = 0; // Count of receivers assigned to senders for (int u = 0; u < M; u++) { // Mark all receivers as not seen for next sender Boolean []seen = new Boolean[N]; // Find if the sender 'u' can be // assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } Console.WriteLine("The number of maximum packets" + " sent in the time slot is " + result); for (int x = 0; x < N; x++) if (matchR[x] + 1 != 0) Console.WriteLine("T" + (matchR[x] + 1) + "-> R" + (x + 1)); return result;} // Driver Codepublic static void Main(String[] args){ int [,]table = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; maxBPM(table);}} // This code is contributed by 29AjayKumar <script> let M = 3;let N = 3; // A Depth First Search based recursive function// that returns true if a matching for vertex u is possiblefunction bpm(table,u,seen,matchR){ // Try every receiver one by one for (let v = 0; v < N; v++) { // If sender u has packets to send // to receiver v and receiver v is not // already mapped to any other sender // just check if the number of packets is // greater than '0' because only one packet // can be sent in a time frame anyways if (table[u][v] > 0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to // any sender OR previously assigned sender // for receiver v (which is matchR[v]) has an // alternate receiver available. Since v is // marked as visited in the above line, // matchR[v] in the following recursive call // will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets// that can be sent parallelly in// 1 time slot from sender to receiverfunction maxBPM(table){ // An array to keep track of the receivers // assigned to the senders. The value of matchR[i] // is the sender ID assigned to receiver i. // The value -1 indicates nobody is assigned. let matchR = new Array(N); // Initially all receivers are // not mapped to any senders for(let i=0;i<N;i++) { matchR[i]=-1; } let result = 0; // Count of receivers assigned to senders for (let u = 0; u < M; u++) { // Mark all receivers as not seen for next sender let seen = new Array(N); for(let i=0;i<N;i++) { seen[i]=false; } // Find if the sender 'u' can be // assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } document.write("The number of maximum packets" + " sent in the time slot is " + result+"<br>"); for (let x = 0; x < N; x++) if (matchR[x] + 1 != 0) document.write("T" + (matchR[x] + 1) + "-> R" + (x + 1)+"<br>"); return result;} // Driver Codelet table= [[0, 2, 0], [3, 0, 1], [2, 4, 0]];maxBPM(table); // This code is contributed by rag2127 </script> The number of maximum packets sent in the time slot is 3 T3-> R1 T1-> R2 T2-> R3 PranchalKatiyar Rajput-Ji 29AjayKumar rag2127 saurabh1990aror hardikkoriintern Graph Graph 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, 2022" }, { "code": null, "e": 583, "s": 54, "text": "There are M transmitter and N receiver stations. Given a matrix that keeps track of the number of packets to be transmitted from a given transmitter to a receiver. If the (i; j)-th entry of the matrix is k, it means at that time the station i has k packets for transmission to station j. During a time slot, a transmitter can send only one packet and a receiver can receive only one packet. Find the channel assignments so that maximum number of packets are transferred from transmitters to receivers during the next time slot. " }, { "code": null, "e": 593, "s": 583, "text": "Example: " }, { "code": null, "e": 611, "s": 593, "text": "0 2 0\n3 0 1\n2 4 0" }, { "code": null, "e": 789, "s": 611, "text": "The above is the input format. We call the above matrix M. Each value M[i; j] represents the number of packets Transmitter ‘i’ has to send to Receiver ‘j’. The output should be:" }, { "code": null, "e": 874, "s": 789, "text": "The number of maximum packets sent in the time slot is 3\nT1 -> R2\nT2 -> R3\nT3 -> R1 " }, { "code": null, "e": 964, "s": 874, "text": "Note that the maximum number of packets that can be transferred in any slot is min(M, N)." }, { "code": null, "e": 976, "s": 964, "text": "Algorithm: " }, { "code": null, "e": 1163, "s": 976, "text": "The channel assignment problem between sender and receiver can be easily transformed into Maximum Bipartite Matching(MBP) problem that can be solved by converting it into a flow network." }, { "code": null, "e": 1193, "s": 1163, "text": "Step 1: Build a Flow Network " }, { "code": null, "e": 1419, "s": 1193, "text": "There must be a source and sink in a flow network. So we add a dummy source and add edges from source to all senders. Similarly, add edges from all receivers to dummy sink. The capacity of all added edges is marked as 1 unit." }, { "code": null, "e": 1451, "s": 1419, "text": "Step 2: Find the maximum flow. " }, { "code": null, "e": 1675, "s": 1451, "text": "We use Ford-Fulkerson algorithm to find the maximum flow in the flow network built in step 1. The maximum flow is actually the maximum number of packets that can be transmitted without bandwidth interference in a time slot." }, { "code": null, "e": 1692, "s": 1675, "text": "Implementation: " }, { "code": null, "e": 2327, "s": 1692, "text": "Let us first define input and output forms. Input is in the form of Edmonds matrix which is a 2D array ‘table[M][N]‘ with M rows (for M senders) and N columns (for N receivers). The value table[i][j] is the number of packets that has to be sent from transmitter ‘i’ to receiver ‘j’. Output is the maximum number of packets that can be transmitted without bandwidth interference in a time slot. A simple way to implement this is to create a matrix that represents adjacency matrix representation of a directed graph with M+N+2 vertices. Call the fordFulkerson() for the matrix. This implementation requires O((M+N)*(M+N)) extra space. " }, { "code": null, "e": 2819, "s": 2327, "text": "Extra space can be reduced and code can be simplified using the fact that the graph is bipartite. The idea is to use DFS traversal to find a receiver for a transmitter (similar to augmenting path in Ford-Fulkerson). We call bpm() for every applicant, bpm() is the DFS based function that tries all possibilities to assign a receiver to the sender. In bpm(), we one by one try all receivers that a sender ‘u’ is interested in until we find a receiver or all receivers are tried without luck. " }, { "code": null, "e": 2864, "s": 2819, "text": "For every receiver we try, we do following: " }, { "code": null, "e": 3378, "s": 2864, "text": "If a receiver is not assigned to anybody, we simply assign it to the sender and return true. If a receiver is assigned to somebody else say x, then we recursively check whether x can be assigned some other receiver. To make sure that x doesn’t get the same receiver again, we mark the receiver ‘v’ as seen before we make recursive call for x. If x can get other receiver, we change the sender for receiver ‘v’ and return true. We use an array maxR[0..N-1] that stores the senders assigned to different receivers. " }, { "code": null, "e": 3519, "s": 3378, "text": "If bmp() returns true, then it means that there is an augmenting path in flow network and 1 unit of flow is added to the result in maxBPM()." }, { "code": null, "e": 3556, "s": 3519, "text": "Time and space complexity analysis: " }, { "code": null, "e": 3885, "s": 3556, "text": "In case of bipartite matching problem, F ? |V| since there can be only |V| possible edges coming out from source node. So the total running time is O(m’n) = O((m + n)n). The space complexity is also substantially reduced from O ((M+N)*(M+N)) to just a single dimensional array of size M thus storing the mapping between M and N." }, { "code": null, "e": 3889, "s": 3885, "text": "C++" }, { "code": null, "e": 3894, "s": 3889, "text": "Java" }, { "code": null, "e": 3902, "s": 3894, "text": "Python3" }, { "code": null, "e": 3905, "s": 3902, "text": "C#" }, { "code": null, "e": 3916, "s": 3905, "text": "Javascript" }, { "code": "#include <iostream>#include <string.h>#include <vector>#define M 3#define N 4using namespace std; // A Depth First Search based recursive function that returns true// if a matching for vertex u is possiblebool bpm(int table[M][N], int u, bool seen[], int matchR[]){ // Try every receiver one by one for (int v = 0; v < N; v++) { // If sender u has packets to send to receiver v and // receiver v is not already mapped to any other sender // just check if the number of packets is greater than '0' // because only one packet can be sent in a time frame anyways if (table[u][v]>0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to any sender OR // previously assigned sender for receiver v (which is // matchR[v]) has an alternate receiver available. Since // v is marked as visited in the above line, matchR[v] in // the following recursive call will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets that can be sent parallelly in 1// time slot from sender to receiverint maxBPM(int table[M][N]){ // An array to keep track of the receivers assigned to the senders. // The value of matchR[i] is the sender ID assigned to receiver i. // the value -1 indicates nobody is assigned. int matchR[N]; // Initially all receivers are not mapped to any senders memset(matchR, -1, sizeof(matchR)); int result = 0; // Count of receivers assigned to senders for (int u = 0; u < M; u++) { // Mark all receivers as not seen for next sender bool seen[N]; memset(seen, 0, sizeof(seen)); // Find if the sender 'u' can be assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } cout << \"The number of maximum packets sent in the time slot is \" << result << \"\\n\"; for (int x=0; x<N; x++) if (matchR[x]+1!=0) cout << \"T\" << matchR[x]+1 << \"-> R\" << x+1 << \"\\n\"; return result;} // Driver program to test above functionint main(){ int table[M][N] = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; int max_flow = maxBPM(table); return 0;}", "e": 6313, "s": 3916, "text": null }, { "code": "import java.util.*;class GFG{static int M = 3;static int N = 3; // A Depth First Search based recursive function// that returns true if a matching for vertex u is possiblestatic boolean bpm(int table[][], int u, boolean seen[], int matchR[]){ // Try every receiver one by one for (int v = 0; v < N; v++) { // If sender u has packets to send // to receiver v and receiver v is not // already mapped to any other sender // just check if the number of packets is // greater than '0' because only one packet // can be sent in a time frame anyways if (table[u][v] > 0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to // any sender OR previously assigned sender // for receiver v (which is matchR[v]) has an // alternate receiver available. Since v is // marked as visited in the above line, // matchR[v] in the following recursive call // will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets// that can be sent parallelly in// 1 time slot from sender to receiverstatic int maxBPM(int table[][]){ // An array to keep track of the receivers // assigned to the senders. The value of matchR[i] // is the sender ID assigned to receiver i. // The value -1 indicates nobody is assigned. int []matchR = new int[N]; // Initially all receivers are // not mapped to any senders Arrays.fill(matchR, -1); int result = 0; // Count of receivers assigned to senders for (int u = 0; u < M; u++) { // Mark all receivers as not seen for next sender boolean []seen = new boolean[N]; Arrays.fill(seen, false); // Find if the sender 'u' can be // assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } System.out.println(\"The number of maximum packets\" + \" sent in the time slot is \" + result); for (int x = 0; x < N; x++) if (matchR[x] + 1 != 0) System.out.println(\"T\" + (matchR[x] + 1) + \"-> R\" + (x + 1)); return result;} // Driver Codepublic static void main(String[] args){ int table[][] = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; maxBPM(table);}} // This code is contributed by Rajput-Ji", "e": 8964, "s": 6313, "text": null }, { "code": "# A Depth First Search based recursive# function that returns true if a matching# for vertex u is possibledef bpm(table, u, seen, matchR): global M, N # Try every receiver one by one for v in range(N): # If sender u has packets to send to # receiver v and receiver v is not # already mapped to any other sender # just check if the number of packets # is greater than '0' because only one # packet can be sent in a time frame anyways if (table[u][v] > 0 and not seen[v]): seen[v] = True # Mark v as visited # If receiver 'v' is not assigned to any # sender OR previously assigned sender # for receiver v (which is matchR[v]) has # an alternate receiver available. Since # v is marked as visited in the above line, # matchR[v] in the following recursive call # will not get receiver 'v' again if (matchR[v] < 0 or bpm(table, matchR[v], seen, matchR)): matchR[v] = u return True return False # Returns maximum number of packets# that can be sent parallelly in 1# time slot from sender to receiverdef maxBPM(table): global M, N # An array to keep track of the receivers # assigned to the senders. The value of # matchR[i] is the sender ID assigned to # receiver i. The value -1 indicates nobody # is assigned. # Initially all receivers are not mapped # to any senders matchR = [-1] * N result = 0 # Count of receivers assigned to senders for u in range(M): # Mark all receivers as not seen # for next sender seen = [0] * N # Find if the sender 'u' can be assigned # to the receiver if (bpm(table, u, seen, matchR)): result += 1 print(\"The number of maximum packets sent\", \"in the time slot is\", result) for x in range(N): if (matchR[x] + 1 != 0): print(\"T\", matchR[x] + 1, \"-> R\", x + 1) return result # Driver CodeM = 3N = 4 table = [[0, 2, 0], [3, 0, 1], [2, 4, 0]]max_flow = maxBPM(table) # This code is contributed by PranchalK", "e": 11177, "s": 8964, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{static int M = 3;static int N = 3; // A Depth First Search based recursive function// that returns true if a matching for vertex u is possiblestatic Boolean bpm(int [,]table, int u, Boolean []seen, int []matchR){ // Try every receiver one by one for (int v = 0; v < N; v++) { // If sender u has packets to send // to receiver v and receiver v is not // already mapped to any other sender // just check if the number of packets is // greater than '0' because only one packet // can be sent in a time frame anyways if (table[u, v] > 0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to // any sender OR previously assigned sender // for receiver v (which is matchR[v]) has an // alternate receiver available. Since v is // marked as visited in the above line, // matchR[v] in the following recursive call // will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets// that can be sent parallelly in// 1 time slot from sender to receiverstatic int maxBPM(int [,]table){ // An array to keep track of the receivers // assigned to the senders. The value of matchR[i] // is the sender ID assigned to receiver i. // The value -1 indicates nobody is assigned. int []matchR = new int[N]; // Initially all receivers are // not mapped to any senders for(int i = 0; i < N; i++) matchR[i] = -1; int result = 0; // Count of receivers assigned to senders for (int u = 0; u < M; u++) { // Mark all receivers as not seen for next sender Boolean []seen = new Boolean[N]; // Find if the sender 'u' can be // assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } Console.WriteLine(\"The number of maximum packets\" + \" sent in the time slot is \" + result); for (int x = 0; x < N; x++) if (matchR[x] + 1 != 0) Console.WriteLine(\"T\" + (matchR[x] + 1) + \"-> R\" + (x + 1)); return result;} // Driver Codepublic static void Main(String[] args){ int [,]table = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; maxBPM(table);}} // This code is contributed by 29AjayKumar", "e": 13853, "s": 11177, "text": null }, { "code": "<script> let M = 3;let N = 3; // A Depth First Search based recursive function// that returns true if a matching for vertex u is possiblefunction bpm(table,u,seen,matchR){ // Try every receiver one by one for (let v = 0; v < N; v++) { // If sender u has packets to send // to receiver v and receiver v is not // already mapped to any other sender // just check if the number of packets is // greater than '0' because only one packet // can be sent in a time frame anyways if (table[u][v] > 0 && !seen[v]) { seen[v] = true; // Mark v as visited // If receiver 'v' is not assigned to // any sender OR previously assigned sender // for receiver v (which is matchR[v]) has an // alternate receiver available. Since v is // marked as visited in the above line, // matchR[v] in the following recursive call // will not get receiver 'v' again if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number of packets// that can be sent parallelly in// 1 time slot from sender to receiverfunction maxBPM(table){ // An array to keep track of the receivers // assigned to the senders. The value of matchR[i] // is the sender ID assigned to receiver i. // The value -1 indicates nobody is assigned. let matchR = new Array(N); // Initially all receivers are // not mapped to any senders for(let i=0;i<N;i++) { matchR[i]=-1; } let result = 0; // Count of receivers assigned to senders for (let u = 0; u < M; u++) { // Mark all receivers as not seen for next sender let seen = new Array(N); for(let i=0;i<N;i++) { seen[i]=false; } // Find if the sender 'u' can be // assigned to the receiver if (bpm(table, u, seen, matchR)) result++; } document.write(\"The number of maximum packets\" + \" sent in the time slot is \" + result+\"<br>\"); for (let x = 0; x < N; x++) if (matchR[x] + 1 != 0) document.write(\"T\" + (matchR[x] + 1) + \"-> R\" + (x + 1)+\"<br>\"); return result;} // Driver Codelet table= [[0, 2, 0], [3, 0, 1], [2, 4, 0]];maxBPM(table); // This code is contributed by rag2127 </script>", "e": 16436, "s": 13853, "text": null }, { "code": null, "e": 16518, "s": 16436, "text": "The number of maximum packets sent in the time slot is 3\nT3-> R1\nT1-> R2\nT2-> R3\n" }, { "code": null, "e": 16534, "s": 16518, "text": "PranchalKatiyar" }, { "code": null, "e": 16544, "s": 16534, "text": "Rajput-Ji" }, { "code": null, "e": 16556, "s": 16544, "text": "29AjayKumar" }, { "code": null, "e": 16564, "s": 16556, "text": "rag2127" }, { "code": null, "e": 16580, "s": 16564, "text": "saurabh1990aror" }, { "code": null, "e": 16597, "s": 16580, "text": "hardikkoriintern" }, { "code": null, "e": 16603, "s": 16597, "text": "Graph" }, { "code": null, "e": 16609, "s": 16603, "text": "Graph" } ]
Python – Create a dictionary using list with none values
11 Sep, 2021 Sometimes you might need to convert a list to dict object for some better and fast operation. Let’s see how to convert a list into a dictionary of none values. Here we will find three methods of doing this. Method #1: Using zip()and dict Python3 # Python code to demonstrate# converting list into dictionary with none values# using zip() and dictionary # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint ("initial list", str(ini_list)) # Converting list into dictionary using zip() and dictionaryres = dict(zip(ini_list, [None]*len(ini_list))) # printing final resultprint ("final dictionary", str(res)) initial list [1, 2, 3, 4, 5] final dictionary {1: None, 2: None, 3: None, 4: None, 5: None} Method #2: Using dict Python3 # Python code to demonstrate converting# list into dictionary with none values# using dict() # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint ("initial list", str(ini_list)) # Converting list into dict()res = dict.fromkeys(ini_list) # printing final resultprint ("final dictionary", str(res)) initial list [1, 2, 3, 4, 5] final dictionary {1: None, 2: None, 3: None, 4: None, 5: None} Method #3: Using dict comprehension Python3 # Python code to demonstrate converting# list into dictionary with none values# using dict comprehension # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint ("initial list", str(ini_list)) # Converting list into dict()res = {key: None for key in ini_list} # printing final resultprint ("final dictionary", str(res)) initial list [1, 2, 3, 4, 5] final dictionary {1: None, 2: None, 3: None, 4: None, 5: None} arorakashish0911 Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Sep, 2021" }, { "code": null, "e": 261, "s": 54, "text": "Sometimes you might need to convert a list to dict object for some better and fast operation. Let’s see how to convert a list into a dictionary of none values. Here we will find three methods of doing this." }, { "code": null, "e": 293, "s": 261, "text": "Method #1: Using zip()and dict " }, { "code": null, "e": 301, "s": 293, "text": "Python3" }, { "code": "# Python code to demonstrate# converting list into dictionary with none values# using zip() and dictionary # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint (\"initial list\", str(ini_list)) # Converting list into dictionary using zip() and dictionaryres = dict(zip(ini_list, [None]*len(ini_list))) # printing final resultprint (\"final dictionary\", str(res))", "e": 687, "s": 301, "text": null }, { "code": null, "e": 779, "s": 687, "text": "initial list [1, 2, 3, 4, 5]\nfinal dictionary {1: None, 2: None, 3: None, 4: None, 5: None}" }, { "code": null, "e": 804, "s": 781, "text": "Method #2: Using dict " }, { "code": null, "e": 812, "s": 804, "text": "Python3" }, { "code": "# Python code to demonstrate converting# list into dictionary with none values# using dict() # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint (\"initial list\", str(ini_list)) # Converting list into dict()res = dict.fromkeys(ini_list) # printing final resultprint (\"final dictionary\", str(res))", "e": 1135, "s": 812, "text": null }, { "code": null, "e": 1227, "s": 1135, "text": "initial list [1, 2, 3, 4, 5]\nfinal dictionary {1: None, 2: None, 3: None, 4: None, 5: None}" }, { "code": null, "e": 1267, "s": 1229, "text": "Method #3: Using dict comprehension " }, { "code": null, "e": 1275, "s": 1267, "text": "Python3" }, { "code": "# Python code to demonstrate converting# list into dictionary with none values# using dict comprehension # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint (\"initial list\", str(ini_list)) # Converting list into dict()res = {key: None for key in ini_list} # printing final resultprint (\"final dictionary\", str(res))", "e": 1618, "s": 1275, "text": null }, { "code": null, "e": 1710, "s": 1618, "text": "initial list [1, 2, 3, 4, 5]\nfinal dictionary {1: None, 2: None, 3: None, 4: None, 5: None}" }, { "code": null, "e": 1729, "s": 1712, "text": "arorakashish0911" }, { "code": null, "e": 1756, "s": 1729, "text": "Python dictionary-programs" }, { "code": null, "e": 1768, "s": 1756, "text": "python-dict" }, { "code": null, "e": 1775, "s": 1768, "text": "Python" }, { "code": null, "e": 1791, "s": 1775, "text": "Python Programs" }, { "code": null, "e": 1803, "s": 1791, "text": "python-dict" } ]
Python Program for N Queen Problem | Backtracking-3
31 May, 2022 The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix that has 1s for the blocks where queens are placed. For example, the following is the output matrix for above 4 queen solution. { 0, 1, 0, 0} { 0, 0, 0, 1} { 1, 0, 0, 0} { 0, 0, 1, 0} Python3 # Python program to solve N Queen# Problem using backtracking global NN = 4 def printSolution(board): for i in range(N): for j in range(N): print (board[i][j],end=' ') print() # A utility function to check if a queen can# be placed on board[row][col]. Note that this# function is called when "col" queens are# already placed in columns from 0 to col -1.# So we need to check only left side for# attacking queensdef isSafe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def solveNQUtil(board, col): # base case: If all queens are placed # then return true if col >= N: return True # Consider this column and try placing # this queen in all rows one by one for i in range(N): if isSafe(board, i, col): # Place this queen in board[i][col] board[i][col] = 1 # recur to place rest of the queens if solveNQUtil(board, col + 1) == True: return True # If placing queen in board[i][col # doesn't lead to a solution, then # queen from board[i][col] board[i][col] = 0 # if the queen can not be placed in any row in # this column col then return false return False # This function solves the N Queen problem using# Backtracking. It mainly uses solveNQUtil() to# solve the problem. It returns false if queens# cannot be placed, otherwise return true and# placement of queens in the form of 1s.# note that there may be more than one# solutions, this function prints one of the# feasible solutions.def solveNQ(): board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if solveNQUtil(board, 0) == False: print ("Solution does not exist") return False printSolution(board) return True # driver program to test above functionsolveNQ() # This code is contributed by Divyanshu Mehta 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 Time Complexity: O(N2) Auxiliary Space: O(N) Please refer complete article on N Queen Problem | Backtracking-3 for more details! anikakapoor amartyaghoshgfg chandramauliguptach Python DSA-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers Python program to check whether a number is Prime or not Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python | Convert set into a list
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2022" }, { "code": null, "e": 231, "s": 54, "text": "The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem." }, { "code": null, "e": 398, "s": 231, "text": "The expected output is a binary matrix that has 1s for the blocks where queens are placed. For example, the following is the output matrix for above 4 queen solution." }, { "code": null, "e": 522, "s": 398, "text": " { 0, 1, 0, 0}\n { 0, 0, 0, 1}\n { 1, 0, 0, 0}\n { 0, 0, 1, 0}" }, { "code": null, "e": 530, "s": 522, "text": "Python3" }, { "code": "# Python program to solve N Queen# Problem using backtracking global NN = 4 def printSolution(board): for i in range(N): for j in range(N): print (board[i][j],end=' ') print() # A utility function to check if a queen can# be placed on board[row][col]. Note that this# function is called when \"col\" queens are# already placed in columns from 0 to col -1.# So we need to check only left side for# attacking queensdef isSafe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def solveNQUtil(board, col): # base case: If all queens are placed # then return true if col >= N: return True # Consider this column and try placing # this queen in all rows one by one for i in range(N): if isSafe(board, i, col): # Place this queen in board[i][col] board[i][col] = 1 # recur to place rest of the queens if solveNQUtil(board, col + 1) == True: return True # If placing queen in board[i][col # doesn't lead to a solution, then # queen from board[i][col] board[i][col] = 0 # if the queen can not be placed in any row in # this column col then return false return False # This function solves the N Queen problem using# Backtracking. It mainly uses solveNQUtil() to# solve the problem. It returns false if queens# cannot be placed, otherwise return true and# placement of queens in the form of 1s.# note that there may be more than one# solutions, this function prints one of the# feasible solutions.def solveNQ(): board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if solveNQUtil(board, 0) == False: print (\"Solution does not exist\") return False printSolution(board) return True # driver program to test above functionsolveNQ() # This code is contributed by Divyanshu Mehta", "e": 2865, "s": 530, "text": null }, { "code": null, "e": 2897, "s": 2865, "text": "0 0 1 0\n1 0 0 0\n0 0 0 1\n0 1 0 0" }, { "code": null, "e": 2922, "s": 2899, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 2944, "s": 2922, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 3029, "s": 2944, "text": "Please refer complete article on N Queen Problem | Backtracking-3 for more details! " }, { "code": null, "e": 3041, "s": 3029, "text": "anikakapoor" }, { "code": null, "e": 3057, "s": 3041, "text": "amartyaghoshgfg" }, { "code": null, "e": 3077, "s": 3057, "text": "chandramauliguptach" }, { "code": null, "e": 3098, "s": 3077, "text": "Python DSA-exercises" }, { "code": null, "e": 3114, "s": 3098, "text": "Python Programs" }, { "code": null, "e": 3212, "s": 3114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3250, "s": 3212, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3299, "s": 3250, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 3336, "s": 3299, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 3393, "s": 3336, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 3427, "s": 3393, "text": "Python program to add two numbers" }, { "code": null, "e": 3486, "s": 3427, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 3527, "s": 3486, "text": "Python Program for factorial of a number" }, { "code": null, "e": 3582, "s": 3527, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 3628, "s": 3582, "text": "Iterate over characters of a string in Python" } ]
World Wide Web (WWW)
03 Jul, 2022 The World Wide Web is abbreviated as WWW and is commonly known as the web. The WWW was initiated by CERN (European library for Nuclear Research) in 1989. History: It is a project created, by Timothy Berner Lee in 1989, for researchers to work together effectively at CERN. is an organization, named the World Wide Web Consortium (W3C), which was developed for further development of the web. This organization is directed by Tim Berner’s Lee, aka the father of the web. System Architecture: From the user’s point of view, the web consists of a vast, worldwide connection of documents or web pages. Each page may contain links to other pages anywhere in the world. The pages can be retrieved and viewed by using browsers of which internet explorer, Netscape Navigator, Google Chrome, etc are the popular ones. The browser fetches the page requested interprets the text and formatting commands on it, and displays the page, properly formatted, on the screen. The basic model of how the web works are shown in the figure below. Here the browser is displaying a web page on the client machine. When the user clicks on a line of text that is linked to a page on the abd.com server, the browser follows the hyperlink by sending a message to the abd.com server asking it for the page. Here the browser displays a web page on the client machine when the user clicks on a line of text that is linked to a page on abd.com, the browser follows the hyperlink by sending a message to the abd.com server asking for the page. Working of WWW: The World Wide Web is based on several different technologies: Web browsers, Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP). A Web browser is used to access web pages. Web browsers can be defined as programs which display text, data, pictures, animation and video on the Internet. Hyperlinked resources on the World Wide Web can be accessed using software interfaces provided by Web browsers. Initially, Web browsers were used only for surfing the Web but now they have become more universal. Web browsers can be used for several tasks including conducting searches, mailing, transferring files, and much more. Some of the commonly used browsers are Internet Explorer, Opera Mini, and Google Chrome. Features of WWW: HyperText Information System Cross-Platform Distributed Open Standards and Open Source Uses Web Browsers to provide a single interface for many services Dynamic, Interactive and Evolving. “Web 2.0” Components of the Web: There are 3 components of the web: Uniform Resource Locator (URL): serves as a system for resources on the web. HyperText Transfer Protocol (HTTP): specifies communication of browser and server. Hyper Text Markup Language (HTML): defines the structure, organisation and content of a webpage. Uniform Resource Locator (URL): serves as a system for resources on the web. HyperText Transfer Protocol (HTTP): specifies communication of browser and server. Hyper Text Markup Language (HTML): defines the structure, organisation and content of a webpage. tajnur tanujrarhmovies velagabhanuprakash Web technologies Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2022" }, { "code": null, "e": 209, "s": 54, "text": "The World Wide Web is abbreviated as WWW and is commonly known as the web. The WWW was initiated by CERN (European library for Nuclear Research) in 1989. " }, { "code": null, "e": 526, "s": 209, "text": "History: It is a project created, by Timothy Berner Lee in 1989, for researchers to work together effectively at CERN. is an organization, named the World Wide Web Consortium (W3C), which was developed for further development of the web. This organization is directed by Tim Berner’s Lee, aka the father of the web. " }, { "code": null, "e": 1014, "s": 526, "text": "System Architecture: From the user’s point of view, the web consists of a vast, worldwide connection of documents or web pages. Each page may contain links to other pages anywhere in the world. The pages can be retrieved and viewed by using browsers of which internet explorer, Netscape Navigator, Google Chrome, etc are the popular ones. The browser fetches the page requested interprets the text and formatting commands on it, and displays the page, properly formatted, on the screen. " }, { "code": null, "e": 1336, "s": 1014, "text": "The basic model of how the web works are shown in the figure below. Here the browser is displaying a web page on the client machine. When the user clicks on a line of text that is linked to a page on the abd.com server, the browser follows the hyperlink by sending a message to the abd.com server asking it for the page. " }, { "code": null, "e": 1572, "s": 1338, "text": "Here the browser displays a web page on the client machine when the user clicks on a line of text that is linked to a page on abd.com, the browser follows the hyperlink by sending a message to the abd.com server asking for the page. " }, { "code": null, "e": 1739, "s": 1572, "text": "Working of WWW: The World Wide Web is based on several different technologies: Web browsers, Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP). " }, { "code": null, "e": 2315, "s": 1739, "text": "A Web browser is used to access web pages. Web browsers can be defined as programs which display text, data, pictures, animation and video on the Internet. Hyperlinked resources on the World Wide Web can be accessed using software interfaces provided by Web browsers. Initially, Web browsers were used only for surfing the Web but now they have become more universal. Web browsers can be used for several tasks including conducting searches, mailing, transferring files, and much more. Some of the commonly used browsers are Internet Explorer, Opera Mini, and Google Chrome. " }, { "code": null, "e": 2333, "s": 2315, "text": "Features of WWW: " }, { "code": null, "e": 2363, "s": 2333, "text": "HyperText Information System " }, { "code": null, "e": 2379, "s": 2363, "text": "Cross-Platform " }, { "code": null, "e": 2392, "s": 2379, "text": "Distributed " }, { "code": null, "e": 2424, "s": 2392, "text": "Open Standards and Open Source " }, { "code": null, "e": 2491, "s": 2424, "text": "Uses Web Browsers to provide a single interface for many services " }, { "code": null, "e": 2527, "s": 2491, "text": "Dynamic, Interactive and Evolving. " }, { "code": null, "e": 2539, "s": 2527, "text": "“Web 2.0” " }, { "code": null, "e": 2599, "s": 2539, "text": "Components of the Web: There are 3 components of the web: " }, { "code": null, "e": 2858, "s": 2599, "text": "Uniform Resource Locator (URL): serves as a system for resources on the web. HyperText Transfer Protocol (HTTP): specifies communication of browser and server. Hyper Text Markup Language (HTML): defines the structure, organisation and content of a webpage. " }, { "code": null, "e": 2936, "s": 2858, "text": "Uniform Resource Locator (URL): serves as a system for resources on the web. " }, { "code": null, "e": 3020, "s": 2936, "text": "HyperText Transfer Protocol (HTTP): specifies communication of browser and server. " }, { "code": null, "e": 3119, "s": 3020, "text": "Hyper Text Markup Language (HTML): defines the structure, organisation and content of a webpage. " }, { "code": null, "e": 3128, "s": 3121, "text": "tajnur" }, { "code": null, "e": 3144, "s": 3128, "text": "tanujrarhmovies" }, { "code": null, "e": 3163, "s": 3144, "text": "velagabhanuprakash" }, { "code": null, "e": 3180, "s": 3163, "text": "Web technologies" }, { "code": null, "e": 3198, "s": 3180, "text": "Computer Networks" }, { "code": null, "e": 3216, "s": 3198, "text": "Computer Networks" } ]