title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python – Remove given character from first element of Tuple
02 Dec, 2021 Given a Tuple list, remove K character from 1st element of Tuple being String. Input : test_list = [(“GF$g!”, 5), (“!i$s”, 4), (“best!$”, 10)], K = ‘$’Output : [(‘GFg!’, 5), (‘!is’, 4), (‘best!’, 10)]Explanation : First element’s strings K value removed. Input : test_list = [(“GF$g!”, 5), (“best!$”, 10)], K = ‘$’Output : [(‘GFg!’, 5), (‘best!’, 10)]Explanation : First element’s strings K value removed. Method #1 : Using replace() + list comprehension In this, we use replace() to perform task of removal of K character and list comprehension to reform tuple. Python3 # Python3 code to demonstrate working of # Remove K character from first element of Tuple# Using replace() + list comprehension # initializing listtest_list = [("GF ! g !", 5), ("! i ! s", 4), ("best !!", 10)] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = "!" # replace with empty string removes the desired char.res = [(sub[0].replace(K, ''), sub[1]) for sub in test_list] # printing result print("The filtered tuples : " + str(res)) The original list is : [('GF!g!', 5), ('!i!s', 4), ('best!!', 10)] The filtered tuples : [('GFg', 5), ('is', 4), ('best', 10)] Method #2 : Using translate() + list comprehension In this, we perform task of removal using translate(), which needs conversion to ascii using ord(), and replaced with empty character. Python3 # Python3 code to demonstrate working of # Remove K character from first element of Tuple# Using translate() + list comprehension # initializing listtest_list = [("GF ! g !", 5), ("! i ! s", 4), ("best !!", 10)] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = "!" # translation after conversion to ascii number res = [(sub[0].translate({ord(K): None}), sub[1]) for sub in test_list] # printing result print("The filtered tuples : " + str(res)) The original list is : [('GF!g!', 5), ('!i!s', 4), ('best!!', 10)] The filtered tuples : [('GFg', 5), ('is', 4), ('best', 10)] rkbhola5 Python tuple-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 ? Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2021" }, { "code": null, "e": 107, "s": 28, "text": "Given a Tuple list, remove K character from 1st element of Tuple being String." }, { "code": null, "e": 283, "s": 107, "text": "Input : test_list = [(“GF$g...
Reactive Programming
Reactive programming is a programming paradigm that deals with data flows and the propagation of change. It means that when a data flow is emitted by one component, the change will be propagated to other components by reactive programming library. The propagation of change will continue until it reaches the final receiver. The difference between event-driven and reactive programming is that event-driven programming revolves around events and reactive programming revolves around data. ReactiveX or Raective Extension is the most famous implementation of reactive programming. The working of ReactiveX depends upon the following two classes − This class is the source of data stream or events and it packs the incoming data so that the data can be passed from one thread to another. It will not give data until some observer subscribe to it. This class consumes the data stream emitted by observable. There can be multiple observers with observable and each observer will receive each data item that is emitted. The observer can receive three type of events by subscribing to observable − on_next() event − It implies there is an element in the data stream. on_next() event − It implies there is an element in the data stream. on_completed() event − It implies end of emission and no more items are coming. on_completed() event − It implies end of emission and no more items are coming. on_error() event − It also implies end of emission but in case when an error is thrown by observable. on_error() event − It also implies end of emission but in case when an error is thrown by observable. RxPY is a Python module which can be used for reactive programming. We need to ensure that the module is installed. The following command can be used to install the RxPY module − pip install RxPY Following is a Python script, which uses RxPY module and its classes Observable and Observe for reactive programming. There are basically two classes − get_strings() − for getting the strings from observer. get_strings() − for getting the strings from observer. PrintObserver() − for printing the strings from observer. It uses all three events of observer class. It also uses subscribe() class. PrintObserver() − for printing the strings from observer. It uses all three events of observer class. It also uses subscribe() class. from rx import Observable, Observer def get_strings(observer): observer.on_next("Ram") observer.on_next("Mohan") observer.on_next("Shyam") observer.on_completed() class PrintObserver(Observer): def on_next(self, value): print("Received {0}".format(value)) def on_completed(self): print("Finished") def on_error(self, error): print("Error: {0}".format(error)) source = Observable.create(get_strings) source.subscribe(PrintObserver()) Received Ram Received Mohan Received Shyam Finished PyFunctionalis another Python library that can be used for reactive programming. It enables us to create functional programs using the Python programming language. It is useful because it allows us to create data pipelines by using chained functional operators. Both the libraries are used for reactive programming and handle the stream in similar fashion but the main difference between both of them depends upon the handling of data. RxPY handles data and events in the system while PyFunctional is focused on transformation of data using functional programming paradigms. We need to install this module before using it. It can be installed with the help of pip command as follows − pip install pyfunctional Following example uses the PyFunctional module and its seq class which act as the stream object with which we can iterate and manipulate. In this program, it maps the sequence by using the lamda function that doubles every value, then filters the value where x is greater than 4 and finally it reduces the sequence into a sum of all the remaining values. from functional import seq result = seq(1,2,3).map(lambda x: x*2).filter(lambda x: x > 4).reduce(lambda x, y: x + y) print ("Result: {}".format(result))
[ { "code": null, "e": 2545, "s": 2056, "text": "Reactive programming is a programming paradigm that deals with data flows and the propagation of change. It means that when a data flow is emitted by one component, the change will be propagated to other components by reactive programming library. The p...
Python | Remove consecutive duplicates from list
11 Feb, 2019 In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession. This is a quite easy task and having a shorthand for it can be useful. Let’s discuss certain ways in which this task can be performed. Method #1 : Using groupby() + list comprehensionUsing the groupby function, we can group the together occurring elements as one and can remove all the duplicates in succession and just let one element be in the list. # Python3 code to demonstrate # removing consecutive duplicates# using groupby() + list comprehensionfrom itertools import groupby # initializing listtest_list = [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # using groupby() + list comprehension# removing consecutive duplicates res = [i[0] for i in groupby(test_list)] # printing result print ("The list after removing consecutive duplicates : " + str(res)) The original list is : [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] The list after removing consecutive duplicates : [1, 4, 5, 6, 7, 4, 3, 9] Method #2 : Using zip_longest() + list comprehensionThis function can be used to keep the element and delete the successive elements with the use of slicing. The zip_longest function does the task of getting the values together in the one list. # Python3 code to demonstrate # removing consecutive duplicates# using zip_longest()+ list comprehensionfrom itertools import zip_longest # initializing listtest_list = [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # using zip_longest()+ list comprehension# removing consecutive duplicates res = [i for i, j in zip_longest(test_list, test_list[1:]) if i != j] # printing result print ("List after removing consecutive duplicates : " + str(res)) The original list is : [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] List after removing consecutive duplicates : [1, 4, 5, 6, 7, 4, 3, 9] Python list-programs python-list Python python-list 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": "\n11 Feb, 2019" }, { "code": null, "e": 339, "s": 28, "text": "In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession....
Producer Consumer Problem using Semaphores
The producer consumer problem is a synchronization problem. There is a fixed size buffer and the producer produces items and enters them into the buffer. The consumer removes the items from the buffer and consumes them. A producer should not produce items into the buffer when the consumer is consuming an item from the buffer and vice versa. So the buffer should only be accessed by the producer or consumer at a time. The producer consumer problem can be resolved using semaphores. The codes for the producer and consumer process are given as follows − The code that defines the producer process is given below − do { . . PRODUCE ITEM . wait(empty); wait(mutex); . . PUT ITEM IN BUFFER . signal(mutex); signal(full); } while(1); In the above code, mutex, empty and full are semaphores. Here mutex is initialized to 1, empty is initialized to n (maximum size of the buffer) and full is initialized to 0. The mutex semaphore ensures mutual exclusion. The empty and full semaphores count the number of empty and full spaces in the buffer. After the item is produced, wait operation is carried out on empty. This indicates that the empty space in the buffer has decreased by 1. Then wait operation is carried out on mutex so that consumer process cannot interfere. After the item is put in the buffer, signal operation is carried out on mutex and full. The former indicates that consumer process can now act and the latter shows that the buffer is full by 1. The code that defines the consumer process is given below: do { wait(full); wait(mutex); . . . REMOVE ITEM FROM BUFFER . signal(mutex); signal(empty); . . CONSUME ITEM . } while(1); The wait operation is carried out on full. This indicates that items in the buffer have decreased by 1. Then wait operation is carried out on mutex so that producer process cannot interfere. Then the item is removed from buffer. After that, signal operation is carried out on mutex and empty. The former indicates that consumer process can now act and the latter shows that the empty space in the buffer has increased by 1.
[ { "code": null, "e": 1407, "s": 1187, "text": "The producer consumer problem is a synchronization problem. There is a fixed size buffer and the producer produces items and enters them into the buffer. The consumer removes the items from the buffer and consumes them." }, { "code": null, "...
How to sort lines of text files in Linux?
To sort lines of text files, we use the sort command in the Linux system. The sort command is used to prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The operation of sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as the sort key. The general syntax of the sort command is as follows. sort [OPTION]... [FILE]... sort [OPTION]... --files0-from=F Brief description of options available in the sort command. Here, we will create a file using the cat command and sort this file using the sort command in the Linux system. $ cat >text.txt Sid Vikash Gaurav ^C $ sort text.txt Gaurav Sid Vikash Here, we will sort a file in the reverse order using the -r or --reverse option with the sort command in the Linux operating system. $ cat >text.txt Sid Vikash Gaurav ^C $ sort text.txt Vikash Sid Gaurav In the above example, we already saw that how can we sort a file but output of the sort command on standard output. Here, we will save output into a new file in the file system. $ sort text.txt > newtext.txt After executing the above command, a new file will be created with the newtext.txt name. To check more information and options with descriptions about the sort command, we use the --help option with the sort command as shown below. $ sort --help To check in which version the sort command is working, we use the --version option with the sort command in the Linux system as shown below. $ sort --version
[ { "code": null, "e": 1261, "s": 1187, "text": "To sort lines of text files, we use the sort command in the Linux system." }, { "code": null, "e": 1548, "s": 1261, "text": "The sort command is used to prints the lines of its input or concatenation of all files listed in its argume...
Bar Charts - Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Bar Charts. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Directions: Answer the questions given below using the graph below: Q 1 - How many people preferring to play Tennis in 2006 (in million) were fewer than the number of people preferring to play Tennis in 2005? A - 115 B - 120 C - 100 D - 97 Answer - C Explanation Required difference =(275-175) = 100 millions Directions: Following bar diagrams depict the changes in student of a collage in four faculties from 2004- 05 to 2006-07. Study the diagram and answer the questions given below it: Q 2 - Which of the following was the percent increase in Science students from the year 2004-05 to 2006-07? A - 50% B - 200/3% C - 75% D - 150% Answer - A Explanation Required% = {(600-400/400)*100}% = 50% Directions: Study the given bar graph carefully and answer the questions given below: Q 3 - In which of the following year the difference between the working and non-working women was the highest? A - 2005 B - 2007 C - 2003 D - 2004 Answer - B Explanation Required difference in various years are 2003 (60-50)millions =10 millions, 2004 (60-50) millions = 10 millions 2005 (70-40) millions= 30 millions 2006 (70-40)= 30 millions 2007 (75-35) millions= 40 millions It is highest in the year 2007. Directions: Study the given bar graph carefully and answer the questions given below: Q 4 - From 2002 to 2007, the total number of people who preferred to travel by rail was approximately how many in million? A - 1300 B - 1800 C - 1600 D - 1700 Answer - B Explanation Required number = (350+300+300+275+300+275)= 1800 million. Directions: Given below is a multiple bar diagram depicting the changes in student of a collage in four faculties from 2004- 05 to 2006-07. Study the diagram and answer the questions given below it.: Q 5 - How much percent was the increase in Science students in 2006-07 over 2005-06? A - 50% B - 150% C - 200/3% D - 75% Answer - A Explanation Number of science student in 2004-05 was 400. Number of science student in 2006-07 was 600. Increase% = (200/400*100)% = 50% Directions: The following bar diagram given below shows the result of B.S.C students of a collage for three years. Study the bar diagram and answer the questions given below: Q 6 - Which of the following % of the students passed in first division in 2005? A - 20% B - 34% C - 100/7% D - 100/9% Answer - D Explanation Percentage of 1st divisioners = (200/1800*100)% = 100/9% Directions: The following bar diagram given below shows the result of B.S.C students of a collage for three years. Study the bar diagram and answer the questions given below: Q 7 - Which of the following is the number of third divisions in 2007? A - 1650 B - 750 C - 700 D - 650 Answer - B Explanation Number of 3rd divisions in 2007 = (1750-1000)= 750
[ { "code": null, "e": 4350, "s": 4026, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Bar Charts. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. Y...
What are the differences between any vs Object in TypeScript?
31 Jan, 2020 TypeScript is an open-source programming language. It is a superset of JavaScript language. TypeScript is designed for the development of large applications. any: It is a built-in data type in TypeScript which helps in describing the type of variable which we are unsure of while writing the code.Though the data type ‘any’ is useful it shouldn’t be used unnecessarily. Syntax:var x: any; // This means x has no interface. var x: any; // This means x has no interface. Features:This data type can be used when there are no type definitions available.The ‘any’ datatype can be used to denote any JavaScript value. This data type can be used when there are no type definitions available. The ‘any’ datatype can be used to denote any JavaScript value. Examples: Below codes illustrates any datatype in TypeScript:Code 1:<script>function add(one: any, two: any): number { return one + two;} console.log(add('Geeks', 'forgeeks')); </script> Output:GeeksforgeeksCode 2:<script>function subtract(one: any, two: any): number { return one - two;} console.log(subtract(9, 5)); </script>Output:4 Code 1:<script>function add(one: any, two: any): number { return one + two;} console.log(add('Geeks', 'forgeeks')); </script> <script>function add(one: any, two: any): number { return one + two;} console.log(add('Geeks', 'forgeeks')); </script> Output:Geeksforgeeks Geeksforgeeks Code 2:<script>function subtract(one: any, two: any): number { return one - two;} console.log(subtract(9, 5)); </script> <script>function subtract(one: any, two: any): number { return one - two;} console.log(subtract(9, 5)); </script> Output:4 4 Object: It describes the functionality, object helps in representing the non-primitive types that is everything except number, string, boolean, big int, symbol, undefined and null. In TypeScript Object(O uppercased) is different from object(o lowercased). Syntax:var y: Object; // This means y has Object interface. var y: Object; // This means y has Object interface. Features:Object exposes the functions and properties defined within the Object class.The object is a more specific way of declaration. Object exposes the functions and properties defined within the Object class. The object is a more specific way of declaration. Examples: Below codes illustrates object in TypeScript:Code 1:<script> Student={roll_no:11,name:"XYZ"} document.write(Student.roll_no+" "+Student.name+" "); </script>Output:11 XYZCode 2:<script> emp={id:102,name:"ABC",salary:10000} document.write(emp.id+" "+emp.name+" "+emp.salary); </script> Output:102 ABC 10000 Code 1:<script> Student={roll_no:11,name:"XYZ"} document.write(Student.roll_no+" "+Student.name+" "); </script> <script> Student={roll_no:11,name:"XYZ"} document.write(Student.roll_no+" "+Student.name+" "); </script> Output:11 XYZ 11 XYZ Code 2:<script> emp={id:102,name:"ABC",salary:10000} document.write(emp.id+" "+emp.name+" "+emp.salary); </script> <script> emp={id:102,name:"ABC",salary:10000} document.write(emp.id+" "+emp.name+" "+emp.salary); </script> Output:102 ABC 10000 102 ABC 10000 Difference between any and Object in TypeScript: Picked Technical Scripter 2019 JavaScript Technical Scripter 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Jan, 2020" }, { "code": null, "e": 212, "s": 54, "text": "TypeScript is an open-source programming language. It is a superset of JavaScript language. TypeScript is designed for the development of large applications." }, { "c...
Python Dictionary
07 Jul, 2022 Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other data types which hold only a single value as an element. Dictionary holds key:value pair. Key-Value is provided in the dictionary to make it more optimized. Python3 Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print(Dict) Output: {1: 'Geeks', 2: 'For', 3: 'Geeks'} In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable. Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly. Python3 # Creating a Dictionary# with Integer KeysDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print("\nDictionary with the use of Integer Keys: ")print(Dict) # Creating a Dictionary# with Mixed keysDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print("\nDictionary with the use of Mixed Keys: ")print(Dict) Output: Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with the use of Mixed Keys: {'Name': 'Geeks', 1: [1, 2, 3, 4]} Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}. Python3 # Creating an empty DictionaryDict = {}print("Empty Dictionary: ")print(Dict) # Creating a Dictionary# with dict() methodDict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})print("\nDictionary with the use of dict(): ")print(Dict) # Creating a Dictionary# with each item as a PairDict = dict([(1, 'Geeks'), (2, 'For')])print("\nDictionary with each item as a pair: ")print(Dict) Output: Empty Dictionary: {} Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with each item as a pair: {1: 'Geeks', 2: 'For'} Time complexity: O(len(dict)) Space complexity: O(n) Python3 # Creating a Nested Dictionary# as shown in the below imageDict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}} print(Dict) Output: {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}} Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary. Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary. Python3 # Creating an empty DictionaryDict = {}print("Empty Dictionary: ")print(Dict) # Adding elements one at a timeDict[0] = 'Geeks'Dict[2] = 'For'Dict[3] = 1print("\nDictionary after adding 3 elements: ")print(Dict) # Adding set of values# to a single KeyDict['Value_set'] = 2, 3, 4print("\nDictionary after adding 3 elements: ")print(Dict) # Updating existing Key's ValueDict[2] = 'Welcome'print("\nUpdated key value: ")print(Dict) # Adding Nested Key value to DictionaryDict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}print("\nAdding a Nested Key: ")print(Dict) Output: Empty Dictionary: {} Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1} Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)} Updated key value: {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)} Adding a Nested Key: {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}} Time complexity: O(1)/O(n) Space complexity: O(1) In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. Python3 # Python program to demonstrate# accessing a element from a Dictionary # Creating a DictionaryDict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using keyprint("Accessing a element using key:")print(Dict['name']) # accessing a element using keyprint("Accessing a element using key:")print(Dict[1]) Output: Accessing a element using key: For Accessing a element using key: Geeks There is also a method called get() that will also help in accessing the element from a dictionary.This method accepts key as argument and returns the value. Time complexity: O(1) Space complexity: O(1) Python3 # Creating a DictionaryDict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using get()# methodprint("Accessing a element using get:")print(Dict.get(3)) Output: Accessing a element using get: Geeks In order to access the value of any key in the nested dictionary, use indexing [] syntax. Python3 # Creating a DictionaryDict = {'Dict1': {1: 'Geeks'}, 'Dict2': {'Name': 'For'}} # Accessing element using keyprint(Dict['Dict1'])print(Dict['Dict1'][1])print(Dict['Dict2']['Name']) Output: {1: 'Geeks'} Geeks For clear() – Remove all the elements from the dictionary copy() – Returns a copy of the dictionary get() – Returns the value of specified key items() – Returns a list containing a tuple for each key value pair keys() – Returns a list containing dictionary’s keys pop() – Remove the element with specified key popitem() – Removes the last inserted key-value pair update() – Updates dictionary with specified key-value pairs values() – Returns a list of all the values of dictionary Python3 # demo for all dictionary methodsdict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"} # copy() methoddict2 = dict1.copy()print(dict2) # clear() methoddict1.clear()print(dict1) # get() methodprint(dict2.get(1)) # items() methodprint(dict2.items()) # keys() methodprint(dict2.keys()) # pop() methoddict2.pop(4)print(dict2) # popitem() methoddict2.popitem()print(dict2) # update() methoddict2.update({3: "Scala"})print(dict2) # values() methodprint(dict2.values()) Output: {1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'} {} Python dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')]) dict_keys([1, 2, 3, 4]) {1: 'Python', 2: 'Java', 3: 'Ruby'} {1: 'Python', 2: 'Java'} {1: 'Python', 2: 'Java', 3: 'Scala'} dict_values(['Python', 'Java', 'Scala']) nikhilaggarwal3 vaishnavipandey1 arpitkakkar267 dariouchbabai kogantibhavya santeswar kumar_satyam python-dict Python School Programming python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Reverse a string in Java Arrays in C/C++ Interfaces in Java Inheritance in C++ Object Oriented Programming in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 231, "s": 52, "text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other data types which hold only a single value as an elem...
How to hide border and background on empty cells in a table using CSS ?
06 Apr, 2021 In this article, we will learn how to hide borders and backgrounds on empty cells in a table using CSS. The empty-cells property of CSS is used to hide the borders and backgrounds on empty cells. Approach: The empty-cells property of CSS is used to hide the borders and backgrounds on empty cells. To hide the borders and backgrounds on empty cells, we will set the empty-cells value to hide that will hide the borders and backgrounds of empty-cells. Syntax: empty-cells: hide; Example HTML <!DOCTYPE html><html lang="en"> <head> <style> .gfg { font-size: 50px; empty-cells: hide; } td, th { background-color: rgb(0, 168, 0); border: solid 1px red; } </style></head> <body> <table class="gfg" border="1"> <tr> <td>Name</td> <td>Marks</td> </tr> <tr> <td>Nikhil</td> <td>200</td> </tr> <tr> <td>Vijay</td> <td></td> </tr> </table></body> </html> Output: Before applying empty-cells property: After applying empty-cells property: CSS-Properties CSS-Questions HTML-Questions HTML-Tags Picked CSS 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": "\n06 Apr, 2021" }, { "code": null, "e": 224, "s": 28, "text": "In this article, we will learn how to hide borders and backgrounds on empty cells in a table using CSS. The empty-cells property of CSS is used to hide the borders and backgro...
Print left rotation of array in O(n) time and O(1) space
27 May, 2022 Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations? Examples : Input : arr[] = {1, 3, 5, 7, 9} k1 = 1 k2 = 3 k3 = 4 k4 = 6 Output : 3 5 7 9 1 7 9 1 3 5 9 1 3 5 7 3 5 7 9 1 Input : arr[] = {1, 3, 5, 7, 9} k1 = 14 Output : 9 1 3 5 7 We have discussed a solution in the below post. Quickly find multiple left rotations of an array | Set 1Method I: The solution discussed above requires extra space. In this post, an optimized solution is discussed that doesn’t require extra space. C++ Java Python C# PHP Javascript // C++ implementation of left rotation of// an array K number of times#include <bits/stdc++.h>using namespace std; // Function to leftRotate array multiple timesvoid leftRotate(int arr[], int n, int k){ /* To get the starting point of rotated array */ int mod = k % n; // Prints the rotated array from start position for (int i = 0; i < n; i++) cout << (arr[(mod + i) % n]) << " "; cout << "\n";} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; // Function Call leftRotate(arr, n, k); k = 3; // Function Call leftRotate(arr, n, k); k = 4; // Function Call leftRotate(arr, n, k); return 0;} // JAVA implementation of left rotation// of an array K number of timesimport java.util.*;import java.lang.*;import java.io.*; class arr_rot { // Function to leftRotate array multiple // times static void leftRotate(int arr[], int n, int k) { /* To get the starting point of rotated array */ int mod = k % n; // Prints the rotated array from // start position for (int i = 0; i < n; ++i) System.out.print(arr[(i + mod) % n] + " "); System.out.println(); } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 5, 7, 9 }; int n = arr.length; int k = 2; // Function Call leftRotate(arr, n, k); k = 3; // Function Call leftRotate(arr, n, k); k = 4; // Function Call leftRotate(arr, n, k); }} // This code is contributed by Sanjal # Python implementation of left rotation of# an array K number of times # Function to leftRotate array multiple times def leftRotate(arr, n, k): # To get the starting point of rotated array mod = k % n s = "" # Prints the rotated array from start position for i in range(n): print str(arr[(mod + i) % n]), print return # Driver codearr = [1, 3, 5, 7, 9]n = len(arr)k = 2 # Function CallleftRotate(arr, n, k) k = 3 # Function CallleftRotate(arr, n, k) k = 4 # Function CallleftRotate(arr, n, k) # This code is contributed by Sachin Bisht // C# implementation of left// rotation of an array K// number of timesusing System; class GFG { // Function to leftRotate // array multiple times static void leftRotate(int[] arr, int n, int k) { // To get the starting // point of rotated array int mod = k % n; // Prints the rotated array // from start position for (int i = 0; i < n; ++i) Console.Write(arr[(i + mod) % n] + " "); Console.WriteLine(); } // Driver Code static public void Main() { int[] arr = { 1, 3, 5, 7, 9 }; int n = arr.Length; int k = 2; // Function Call leftRotate(arr, n, k); k = 3; // Function Call leftRotate(arr, n, k); k = 4; // Function Call leftRotate(arr, n, k); }} // This code is contributed by m_kit <?php// PHP implementation of// left rotation of an// array K number of times // Function to leftRotate// array multiple timesfunction leftRotate($arr, $n, $k){ // To get the starting // point of rotated array $mod = $k % $n; // Prints the rotated array // from start position for ($i = 0; $i < $n; $i++) echo ($arr[($mod + $i) % $n]) , " "; echo "\n";} // Driver Code$arr = array(1, 3, 5, 7, 9);$n = sizeof($arr); $k = 2; // Function CallleftRotate($arr, $n, $k); $k = 3; // Function CallleftRotate($arr, $n, $k); $k = 4; // Function CallleftRotate($arr, $n, $k); // This code is contributed by m_kit?> <script>// JavaScript implementation of left rotation of// an array K number of times // Function to leftRotate array multiple timesfunction leftRotate(arr, n, k){ /* To get the starting point of rotated array */ let mod = k % n; // Prints the rotated array from start position for (let i = 0; i < n; i++) document.write((arr[(mod + i) % n]) + " "); document.write("\n");} // Driver Codelet arr = [ 1, 3, 5, 7, 9 ];let n = arr.length; let k = 2;// Function CallleftRotate(arr, n, k);document.write("<br>"); k = 3;// Function CallleftRotate(arr, n, k);document.write("<br>"); k = 4;// Function CallleftRotate(arr, n, k); </script> 5 7 9 1 3 7 9 1 3 5 9 1 3 5 7 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space. Method II: In the below implementation we will use Standard Template Library (STL) which will be making the solution more optimize and easy to Implement. C++ Java Python3 C# Javascript // C++ Implementation For Print Left Rotation Of Any Array K// Times #include <bits/stdc++.h>#include <iostream>using namespace std;// Function For The k Times Left Rotationvoid leftRotate(int arr[], int k, int n){ // Stl function rotates takes three parameters - the // beginning,the position by which it should be rotated // ,the end address of the array // The below function will be rotating the array left // in linear time (k%arraySize) times rotate(arr, arr + (k % n), arr + n); // Print the rotated array from start position for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\n";}// Driver programint main(){ int arr[] = { 1, 3, 5, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; // Function Call leftRotate(arr, k, n); return 0;} // Java implementation for print left// rotation of any array K timesimport java.io.*;import java.util.*; class GFG{ // Function for the k times left rotationstatic void leftRotate(Integer arr[], int k, int n){ // In Collection class rotate function // takes two parameters - the name of // array and the position by which it // should be rotated // The below function will be rotating // the array left in linear time // Collections.rotate()rotate the // array from right hence n-k Collections.rotate(Arrays.asList(arr), n - k); // Print the rotated array from start position for(int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Driver codepublic static void main(String[] args){ Integer arr[] = { 1, 3, 5, 7, 9 }; int n = arr.length; int k = 2; // Function call leftRotate(arr, k, n);}} // This code is contributed by chahattekwani71 # Python3 implementation to print left# rotation of any array K timesfrom collections import deque # Function For The k Times Left Rotationdef leftRotate(arr, k, n): # The collections module has deque class # which provides the rotate(), which is # inbuilt function to allow rotation arr = deque(arr) # using rotate() to left rotate by k arr.rotate(-k) arr = list(arr) # Print the rotated array from # start position for i in range(n): print(arr[i], end = " ") # Driver Codeif __name__ == '__main__': arr = [ 1, 3, 5, 7, 9 ] n = len(arr) k = 2 # Function Call leftRotate(arr, k, n) # This code is contributed by math_lover // C# program for the above approachusing System; class GFG{ static void leftRotate(int[] arr, int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int[] arr, int n) { int i, temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp; } /* utility function to print an array */ static void printArray(int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + " "); } // Driver Codepublic static void Main(){ int[] arr = { 1, 3, 5, 7, 9 }; int n = arr.Length; int k = 2; // Function call leftRotate(arr, k, n); printArray(arr, n);}} // This code is contributed by avijitmondal1998. <script>// Javascript program for the above approachfunction leftRotate(arr, d, n){ for (let i = 0; i < d; i++) leftRotatebyOne(arr, n);} function leftRotatebyOne(arr, n){ let i, temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp;} /* utility function to print an array */function printArray(arr, size){ for (let i = 0; i < size; i++) document.write(arr[i] + " ");} // Driver Codelet arr = [ 1, 3, 5, 7, 9 ];let n = arr.length;let k = 2; // Function callleftRotate(arr, k, n);printArray(arr, n); // This code is contributed by Samim Hossain Mondal.</script> 5 7 9 1 3 Note: the array itself gets updated after the rotation. Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Sridhar Babu and improved by Geetansh Sahni. 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. jit_t geetansh044 chahattekwani71 math_lover rohitsingh07052 avijitmondal1998 samim2000 rohitkumarsinghcna rotation Arrays Arrays 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 Arrays in C/C++ Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Subset Sum Problem | DP-25
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2022" }, { "code": null, "e": 190, "s": 52, "text": "Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations?" }, { "code": null, "e":...
How to Calculate a Bootstrap Standard Error in R?
04 Jan, 2022 In this article, we will be looking at the different approaches to calculate a bootstrap standard error using various packages and their functionalities in the R programming language. Bootstrap Standard Error: The standard deviation of the bootstrap samples (also known as the bootstrap standard error) is an estimate of the standard deviation of the sampling distribution of the mean. Steps to calculate the bootstrap standard error of given data: Take k repeated samples with replacement from a given dataset. For each sample, calculate the standard error: s/√n. This results in k different estimates for the standard error. To find the bootstrapped standard error, take the mean of the k standard errors. In this method, the user first needs to install and import the boot package in the working R console, then the user needs to call the boot() function with the required data passed into it as its parameter, which will further return the Bootstrap Standard Error of the given data in R programming language. Syntax to install and import the boot package: install.packages('boot') library('boot') Boot() function: This function provides a simple front-end to the boot function in the boot package that is tailored to bootstrapping based on regression models. Syntax: Boot(object, f=coef, labels=names(f(object)),R=999, ...) Parameters: object: An object of the class. f: A function whose one argument is the name of a regression object that will be applied to the updated regression object to compute the statistics of interest. labels: Provides labels for the statistics computed by f. R: Number of bootstrap samples. Example: In this example, we will be using the boot() function from the boot package to the bootstrap standard error of the vector containing 10 elements and using 100 bootstrapped samples in the R programming language. R library(boot) # Create datagfg <- c(244,753,596,645,874,141,639,465,999,654) # Calculating the mean m <- function(gfg,i){mean(gfg[i])} # Calculate standard error using 100# bootstrapped samplesboot(gfg, m, 100) Output: ORDINARY NONPARAMETRIC BOOTSTRAP Call: boot(data = gfg, statistic = m, R = 100) Bootstrap Statistics : original bias std. error t1* 601 -3.231 80.02706 In this method to calculate the bootstrap standard error, the user needs to use the direct formula to get the same, simply without any use of any packages in the R programming language. Example: In this example, we will be using the direct formula to get the bootstrap standard error of the vector containing 10 elements in the R programming language. R # Create datagfg <- c(244,753,596,645,874,141,639,465,999,654) # Calculating the bootstrap standard error mean(replicate(100, sd(sample( gfg, replace=T))/sqrt(length(gfg)))) Output: [1] 78.53055 Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2022" }, { "code": null, "e": 212, "s": 28, "text": "In this article, we will be looking at the different approaches to calculate a bootstrap standard error using various packages and their functionalities in the R programming l...
Priority Interrupts | (S/W Polling and Daisy Chaining)
23 Mar, 2022 In I/O Interface (Interrupt and DMA Mode), we have discussed the concept behind the Interrupt-initiated I/O. To summarize, when I/O devices are ready for I/O transfer, they generate an interrupt request signal to the computer. The CPU receives this signal, suspends the current instructions it is executing, and then moves forward to service that transfer request. But what if multiple devices generate interrupts simultaneously. In that case, we have a way to decide which interrupt is to be serviced first. In other words, we have to set a priority among all the devices for systemic interrupt servicing. The concept of defining the priority among devices so as to know which one is to be serviced first in case of simultaneous requests is called a priority interrupt system. This could be done with either software or hardware methods. SOFTWARE METHOD – POLLING In this method, all interrupts are serviced by branching to the same service program. This program then checks with each device if it is the one generating the interrupt. The order of checking is determined by the priority that has to be set. The device having the highest priority is checked first and then devices are checked in descending order of priority. If the device is checked to be generating the interrupt, another service program is called which works specifically for that particular device. The structure will look something like this- if (device[0].flag) device[0].service(); else if (device[1].flag) device[1].service(); . . . . . . else //raise error The major disadvantage of this method is that it is quite slow. To overcome this, we can use hardware solution, one of which involves connecting the devices in series. This is called Daisy-chaining method. HARDWARE METHOD – DAISY CHAINING The daisy-chaining method involves connecting all the devices that can request an interrupt in a serial manner. This configuration is governed by the priority of the devices. The device with the highest priority is placed first followed by the second highest priority device and so on. The given figure depicts this arrangement. WORKING: There is an interrupt request line which is common to all the devices and goes into the CPU. When no interrupts are pending, the line is in HIGH state. But if any of the devices raises an interrupt, it places the interrupt request line in the LOW state. The CPU acknowledges this interrupt request from the line and then enables the interrupt acknowledge line in response to the request. This signal is received at the PI(Priority in) input of device 1. If the device has not requested the interrupt, it passes this signal to the next device through its PO(priority out) output. (PI = 1 & PO = 1) However, if the device had requested the interrupt, (PI =1 & PO = 0)The device consumes the acknowledge signal and block its further use by placing 0 at its PO(priority out) output.The device then proceeds to place its interrupt vector address(VAD) into the data bus of CPU.The device puts its interrupt request signal in HIGH state to indicate its interrupt has been taken care of. The device consumes the acknowledge signal and block its further use by placing 0 at its PO(priority out) output. The device then proceeds to place its interrupt vector address(VAD) into the data bus of CPU. The device puts its interrupt request signal in HIGH state to indicate its interrupt has been taken care of. If a device gets 0 at its PI input, it generates 0 at the PO output to tell other devices that acknowledge signal has been blocked. (PI = 0 & PO = 0) Hence, the device having PI = 1 and PO = 0 is the highest priority device that is requesting an interrupt. Therefore, by daisy chain arrangement we have ensured that the highest priority interrupt gets serviced first and have established a hierarchy. The farther a device is from the first device, the lower its priority. This article is contributed by Jatin Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. kumarohit1202 Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Decimal to Binary Conversion Logical and Physical Address in Operating System Direct Access Media (DMA) Controller in Computer Architecture Interrupts Control Characters Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor Programmable peripheral interface 8255 Architecture of 8086 Write Through and Write Back in Cache
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Mar, 2022" }, { "code": null, "e": 893, "s": 54, "text": "In I/O Interface (Interrupt and DMA Mode), we have discussed the concept behind the Interrupt-initiated I/O. To summarize, when I/O devices are ready for I/O transfer, they g...
Unix / Linux Shell - The select Loop
The select loop provides an easy way to create a numbered menu from which users can select options. It is useful when you need to ask the user to choose one or more items from a list of choices. select var in word1 word2 ... wordN do Statement(s) to be executed for every word. done Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN. For every selection, a set of commands will be executed within the loop. This loop was introduced in ksh and has been adapted into bash. It is not available in sh. Here is a simple example to let the user select a drink of choice − #!/bin/ksh select DRINK in tea cofee water juice appe all none do case $DRINK in tea|cofee|water|all) echo "Go to canteen" ;; juice|appe) echo "Available at home" ;; none) break ;; *) echo "ERROR: Invalid selection" ;; esac done The menu presented by the select loop looks like the following − $./test.sh 1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none #? juice Available at home #? none $ You can change the prompt displayed by the select loop by altering the variable PS3 as follows − $PS3 = "Please make a selection => " ; export PS3 $./test.sh 1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none Please make a selection => juice Available at home Please make a selection => none
[ { "code": null, "e": 3076, "s": 2881, "text": "The select loop provides an easy way to create a numbered menu from which users can select options. It is useful when you need to ask the user to choose one or more items from a list of choices." }, { "code": null, "e": 3168, "s": 3076, ...
Python VLC MediaList – Adding Media to it
29 Aug, 2020 In this article we will see how we can add media to the MediaList object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaList object contains the multiple media, in other words it has list of media which can be used with MediaListPlayer object to play these multiple media object. Adding media act similar to inserting media at the end of the list. In order to do this we will use add_media method with the MediaList object Syntax : media_list.add_media(media) Argument : It takes Media object as argument Return : It returns None Below is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating a media player objectmedia_player = vlc.MediaListPlayer() # creating Instance class objectplayer = vlc.Instance() # creating a media list objectmedia_list = vlc.MediaList() # creating a new mediamedia = player.media_new("death_note.mkv") # adding media to media listmedia_list.add_media(media) # creating a new mediamedia = player.media_new("1.mp4") # adding media to media listmedia_list.add_media(media) # setting media list to the media playermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Another example # importing vlc moduleimport vlc # importing time moduleimport time # creating a media player objectmedia_player = vlc.MediaListPlayer() # creating Instance class objectplayer = vlc.Instance() # creating a media list objectmedia_list = vlc.MediaList() # creating a new mediamedia = player.media_new("1.mp4") # adding media to media listmedia_list.add_media(media) # creating a new mediamedia = player.media_new("death_note.mkv") # adding media to media listmedia_list.add_media(media) # setting media list to the media playermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Python vlc-mediaList Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 511, "s": 28, "text": "In this article we will see how we can add media to the MediaList object in the python vlc module. VLC media player is a free and open-source portable cross-platform media pla...
Classes and Object in MATLAB
09 May, 2021 A class is a blueprint that defines the variables and the methods which provide a commonly shared basis for its corresponding objects. It defines an object that encapsulates data and the operations performed on that data. classdef is a keyword used to define MATLAB classes. Syntax to define a class: classdef (Attributes) ClassName < SuperclassName properties (Attributes) PropertyName PropertyName size class {validation functions} end methods (Attributes) function obj = methodName(obj,arg2,...) ... end end events (Attributes) EventName end end MATLAB class has three major components (which are MATLAB functions used to query the respective class members for a given object or class name): Properties blocks: Define the properties that store data for each of the objects of the class. Methods blocks: Contain a set of functions that define the operations that can be performed on each object of the class. Events blocks: Define messages that an object will send to other parts of an application when something changes in that object. Here is an example of a MATLAB class, SimpleClass defines a property and two methods that operate on the data in that property: Matlab classdef SimpleClass properties Value {mustBeNumeric} end methods function R = roundOff(object) R = round([object.Value],2); end function R = DivideBy(object,n) R = [object.Value] / n; end endend In the above example: Value – Property that holds the numeric data stored in an object of the class. roundOff – Method that roundoff the value of the property to two decimal places. DivideBy – Method that multiplies the value of the property by the specified number. To use the class: Save the class definition with the same name as the class, keep the extension of the file as (.m). Create an object of the class. Access the properties to assign data and call methods to perform an operation on the data. Similar to any other programming language, objects in MATLAB are instances of their respective classes. In MATLAB, objects of a class can be created in two ways: Create object: Below is the script to create an object of the above class. Matlab a = SimpleClass a = SimpleClass with properties: Value: [] Initially, the property value is empty. Access Properties: Using the object variable and a dot before the property name, we can assign value to the Value property : Matlab a.Value = pi; Property value is returned if we use dot notation without the assignment: Matlab a.Value Output: ans = 3.1416 Call Methods: Call the roundOff method on object a: Matlab roundOff(a) Output: ans = 3.1400 Pass the object as the first argument to a method that takes multiple arguments, as in this call to the DivideBy method: Matlab DivideBy(a,3) Output: ans = 1.0472 The method can also be called using dot notation: Matlab a.DivideBy(3) Output: ans = 1.0472 It is not mandatory to pass the object explicitly as an argument when using dot notation. We can also create an object(or an array of objects) using a class constructor. Constructor methods enable us to pass arguments to the constructor, which you can assign as property values. The mustBeNumeric function restricts the possible values of SimpleClass Value property. Constructor is called like any MATLAB function. You can access object properties and object methods are called just like ordinary MATLAB functions. Here is a constructor for the SimpleClass class. When the constructor is called with an input argument, it is assigned to the Value property, but if it is called without an input argument, it has a default value of empty ([]). Matlab classdef SimpleClass properties Value {mustBeNumeric} end methods function obj = SimpleClass(val) if nargin == 1 obj.Value = val; end end endend We can create an object and set the property value in one step by adding a constructor to the class definition: Matlab a = SimpleClass(pi/3) Output: a = SimpleClass with properties: Value: 1.0472 The constructor is also used in performing operations related to creating objects of the class. Note: MATLAB objects have unique features relative to other languages. For example, you can modify a class at any time, and the objects of that class will update immediately. Managing the lifecycle of objects in MATLAB is done without requiring any explicit memory allocation or deallocation. A snap of object creation of class SimpleClass in MATLAB: MATLAB-OOPs Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2021" }, { "code": null, "e": 303, "s": 28, "text": "A class is a blueprint that defines the variables and the methods which provide a commonly shared basis for its corresponding objects. It defines an object that encapsulates d...
Python | os.mkfifo() method
26 Aug, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.mkfifo() method in Python is used to create a FIFO (a named pipe) named path with the specified mode. FIFOs are named pipe which can be accessed like other regular files. This method only create FIFO but don’t open it and the created FIFO does exist until they are deleted. FIFOs are generally us as rendezvous between client and “server type processes. Syntax: os.mkfifo(path, mode = 0o666, *, dir_fd = None) Parameters:path: A path-like object representing the file system path. It can be a string or bytes object representing a file path.mode (optional): A numeric value representing the mode of the FIFO (named pipe) to be created. The default value of mode parameter is 0o666 (octal).dir_fd (optional): This is a file descriptor referring to a directory. Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as a positional parameter. Return type: This method does not return any value. Code: Use of os.mkfifo() method # Python3 program to explain os.mkfifo() method # importing os moduleimport os # Pathpath = "./mypipe" # Mode of the FIFO (a named pipe)# to be createdmode = 0o600 # Create a FIFO named path# with the specified mode# using os.mkfifo() methodos.mkfifo(path, mode) print("FIFO named '% s' is created successfully." % path) FIFO named './mypipe' is created successfully. python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of usin...
Point to next higher value node in a linked list with an arbitrary pointer
27 Jun, 2022 Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. Need to make the “arbitrary” pointer point to the next higher value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node which has the next greater value of the current node and change the next pointer. Time Complexity of this solution is O(n2). An Efficient Solution works in O(nLogn) time. The idea is to use Merge Sort for linked list. Traverse input list and copy next pointer to arbit pointer for every node. Do Merge Sort for the linked list formed by arbit pointers. Traverse input list and copy next pointer to arbit pointer for every node. Do Merge Sort for the linked list formed by arbit pointers. Below is the implementation of the above idea. All of the merger sort functions are taken from here. The taken functions are modified here so that they work on arbit pointers instead of next pointers. C++ C Java Python3 C# Javascript // C++ program to populate arbit pointers// to next higher value using merge sort#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{ public: int data; Node* next, *arbit;}; /* function prototypes */Node* SortedMerge(Node* a, Node* b);void FrontBackSplit(Node* source, Node** frontRef, Node** backRef); /* sorts the linked list formed by arbit pointers(does not change next pointer or data) */void MergeSort(Node** headRef){ Node* head = *headRef; Node* a, *b; /* Base case -- length 0 or 1 */ if ((head == NULL) || (head->arbit == NULL)) return; /* Split head into 'a' and 'b' sublists */ FrontBackSplit(head, &a, &b); /* Recursively sort the sublists */ MergeSort(&a); MergeSort(&b); /* answer = merge the two sorted lists together */ *headRef = SortedMerge(a, b);} /* See https://www.geeksforgeeks.org/?p=3622 for details of this function */Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* Base cases */ if (a == NULL) return (b); else if (b == NULL) return (a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->arbit = SortedMerge(a->arbit, b); } else { result = b; result->arbit = SortedMerge(a, b->arbit); } return (result);} /* Split the nodes of the given list into frontand back halves, and return the two lists usingthe reference parameters. If the length is odd,the extra node should go in the front list.Uses the fast/slow pointer strategy. */void FrontBackSplit(Node* source, Node** frontRef, Node** backRef){ Node* fast, *slow; if (source == NULL || source->arbit == NULL) { /* length < 2 cases */ *frontRef = source; *backRef = NULL; return; } slow = source, fast = source->arbit; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != NULL) { fast = fast->arbit; if (fast != NULL) { slow = slow->arbit; fast = fast->arbit; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ *frontRef = source; *backRef = slow->arbit; slow->arbit = NULL;} /* Function to insert a node at thebeginning of the linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); new_node->arbit = NULL; /* move the head to point to the new node */ (*head_ref) = new_node;} // Utility function to print result linked listvoid printListafter(Node *node, Node *anode){ cout<<"Traversal using Next Pointer\n"; while (node!=NULL) { cout << node->data << ", "; node = node->next; } printf("\nTraversal using Arbit Pointer\n"); while (anode!=NULL) { cout << anode->data << ", "; anode = anode->arbit; }} // This function populates arbit pointer in every node to the// next higher value. And returns pointer to the node with// minimum valueNode* populateArbit(Node *head){ // Copy next pointers to arbit pointers Node *temp = head; while (temp != NULL) { temp->arbit = temp->next; temp = temp->next; } // Do merge sort for arbitrary pointers MergeSort(&head); // Return head of arbitrary pointer linked list return head;} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Let us create the list shown above */ push(&head, 3); push(&head, 2); push(&head, 10); push(&head, 5); /* Sort the above created Linked List */ Node *ahead = populateArbit(head); cout << "Result Linked List is: \n"; printListafter(head, ahead); return 0;} // This is code is contributed by rathbhupendra // C program to populate arbit pointers to next higher value// using merge sort#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next, *arbit;}; /* function prototypes */struct Node* SortedMerge(struct Node* a, struct Node* b);void FrontBackSplit(struct Node* source, struct Node** frontRef, struct Node** backRef); /* sorts the linked list formed by arbit pointers (does not change next pointer or data) */void MergeSort(struct Node** headRef){ struct Node* head = *headRef; struct Node* a, *b; /* Base case -- length 0 or 1 */ if ((head == NULL) || (head->arbit == NULL)) return; /* Split head into 'a' and 'b' sublists */ FrontBackSplit(head, &a, &b); /* Recursively sort the sublists */ MergeSort(&a); MergeSort(&b); /* answer = merge the two sorted lists together */ *headRef = SortedMerge(a, b);} /* See https://www.geeksforgeeks.org/?p=3622 for details of this function */struct Node* SortedMerge(struct Node* a, struct Node* b){ struct Node* result = NULL; /* Base cases */ if (a == NULL) return (b); else if (b==NULL) return (a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->arbit = SortedMerge(a->arbit, b); } else { result = b; result->arbit = SortedMerge(a, b->arbit); } return (result);} /* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. If the length is odd, the extra node should go in the front list. Uses the fast/slow pointer strategy. */void FrontBackSplit(struct Node* source, struct Node** frontRef, struct Node** backRef){ struct Node* fast, *slow; if (source==NULL || source->arbit==NULL) { /* length < 2 cases */ *frontRef = source; *backRef = NULL; return; } slow = source, fast = source->arbit; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != NULL) { fast = fast->arbit; if (fast != NULL) { slow = slow->arbit; fast = fast->arbit; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ *frontRef = source; *backRef = slow->arbit; slow->arbit = NULL;} /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); new_node->arbit = NULL; /* move the head to point to the new node */ (*head_ref) = new_node;} // Utility function to print result linked listvoid printListafter(struct Node *node, struct Node *anode){ printf("Traversal using Next Pointer\n"); while (node!=NULL) { printf("%d, ", node->data); node = node->next; } printf("\nTraversal using Arbit Pointer\n"); while (anode!=NULL) { printf("%d, ", anode->data); anode = anode->arbit; }} // This function populates arbit pointer in every node to the// next higher value. And returns pointer to the node with// minimum valuestruct Node* populateArbit(struct Node *head){ // Copy next pointers to arbit pointers struct Node *temp = head; while (temp != NULL) { temp->arbit = temp->next; temp = temp->next; } // Do merge sort for arbitrary pointers MergeSort(&head); // Return head of arbitrary pointer linked list return head;} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create the list shown above */ push(&head, 3); push(&head, 2); push(&head, 10); push(&head, 5); /* Sort the above created Linked List */ struct Node *ahead = populateArbit(head); printf("\nResult Linked List is: \n"); printListafter(head, ahead); getchar(); return 0;} // Java program to populate arbit pointers// to next higher value using merge sortclass LinkedList{ static Node head; /* Link list node */ static class Node { int data; Node next, arbit; Node(int data) { this.data = data; next = null; arbit = null; } } // Utility function to print result linked list void printList(Node node, Node anode) { System.out.println("Traversal using Next Pointer"); while (node != null) { System.out.print(node.data + " "); node = node.next; } System.out.println("\nTraversal using Arbit Pointer"); while (anode != null) { System.out.print(anode.data + " "); anode = anode.arbit; } } // This function populates arbit pointer in every node to the // next higher value. And returns pointer to the node with // minimum value private Node populateArbit(Node start) { Node temp = start; // Copy next pointers to arbit pointers while (temp != null) { temp.arbit = temp.next; temp = temp.next; } // Do merge sort for arbitrary pointers and // return head of arbitrary pointer linked list return MergeSort(start); } /* sorts the linked list formed by arbit pointers (does not change next pointer or data) */ private Node MergeSort(Node start) { /* Base case -- length 0 or 1 */ if (start == null || start.arbit == null) { return start; } /* Split head into 'middle' and 'nextofmiddle' sublists */ Node middle = getMiddle(start); Node nextofmiddle = middle.arbit; middle.arbit = null; /* Recursively sort the sublists */ Node left = MergeSort(start); Node right = MergeSort(nextofmiddle); /* answer = merge the two sorted lists together */ Node sortedlist = SortedMerge(left, right); return sortedlist; } // Utility function to get the middle of the linked list private Node getMiddle(Node source) { // Base case if (source == null) return source; Node fastptr = source.arbit; Node slowptr = source; // Move fastptr by two and slow ptr by one // Finally slowptr will point to middle node while (fastptr != null) { fastptr = fastptr.arbit; if (fastptr != null) { slowptr = slowptr.arbit; fastptr = fastptr.arbit; } } return slowptr; } private Node SortedMerge(Node a, Node b) { Node result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.arbit = SortedMerge(a.arbit, b); } else { result = b; result.arbit = SortedMerge(a, b.arbit); } return result; } // Driver code public static void main(String[] args) { LinkedList list = new LinkedList(); /* Let us create the list shown above */ list.head = new Node(5); list.head.next = new Node(10); list.head.next.next = new Node(2); list.head.next.next.next = new Node(3); /* Sort the above created Linked List */ Node ahead = list.populateArbit(head); System.out.println("Result Linked List is:"); list.printList(head, ahead); }} // This code is contributed by shubham96301 # Python3 program to populate arbit pointers# to next higher value using merge sorthead = None # Link l nodeclass Node: def __init__(self, data): self.data = data self.next = None self.arbit = None # Utility function to print result linked ldef printList(node, anode): print("Traversal using Next Pointer") while (node != None): print(node.data, end = ", ") node = node.next print("\nTraversal using Arbit Pointer"); while (anode != None): print(anode.data, end = ", ") anode = anode.arbit # This function populates arbit pointer in# every node to the next higher value. And# returns pointer to the node with minimum# valuedef populateArbit(start): temp = start # Copy next pointers to arbit pointers while (temp != None): temp.arbit = temp.next temp = temp.next # Do merge sort for arbitrary pointers and # return head of arbitrary pointer linked l return MergeSort(start) # Sorts the linked l formed by arbit pointers# (does not change next pointer or data)def MergeSort(start): # Base case -- length 0 or 1 if (start == None or start.arbit == None): return start # Split head into 'middle' and # 'nextofmiddle' sublists middle = getMiddle(start) nextofmiddle = middle.arbit middle.arbit = None # Recursively sort the sublists left = MergeSort(start) right = MergeSort(nextofmiddle) # answer = merge the two sorted lists together sortedlist = SortedMerge(left, right) return sortedlist # Utility function to get the# middle of the linked ldef getMiddle(source): # Base case if (source == None): return source fastptr = source.arbit slowptr = source # Move fastptr by two and slow ptr by one # Finally slowptr will point to middle node while (fastptr != None): fastptr = fastptr.arbit if (fastptr != None): slowptr = slowptr.arbit fastptr = fastptr.arbit return slowptr def SortedMerge(a, b): result = None # Base cases if (a == None): return b elif (b == None): return a # Pick either a or b, and recur if (a.data <= b.data): result = a result.arbit = SortedMerge(a.arbit, b) else: result = b result.arbit = SortedMerge(a, b.arbit) return result # Driver codeif __name__=='__main__': # Let us create the l shown above head = Node(5) head.next = Node(10) head.next.next = Node(2) head.next.next.next = Node(3) # Sort the above created Linked List ahead = populateArbit(head) print("Result Linked List is:") printList(head, ahead) # This code is contributed by rutvik_56 // C# program to populate arbit pointers// to next higher value using merge sortusing System;public class LinkedList{ public Node head; /* Link list node */ public class Node { public int data; public Node next, arbit; public Node(int data) { this.data = data; next = null; arbit = null; } } // Utility function to print result linked list void printList(Node node, Node anode) { Console.WriteLine("Traversal using Next Pointer"); while (node != null) { Console.Write(node.data + " "); node = node.next; } Console.WriteLine("\nTraversal using Arbit Pointer"); while (anode != null) { Console.Write(anode.data + " "); anode = anode.arbit; } } // This function populates arbit pointer in every node to the // next higher value. And returns pointer to the node with // minimum value private Node populateArbit(Node start) { Node temp = start; // Copy next pointers to arbit pointers while (temp != null) { temp.arbit = temp.next; temp = temp.next; } // Do merge sort for arbitrary pointers and // return head of arbitrary pointer linked list return MergeSort(start); } /* sorts the linked list formed by arbit pointers (does not change next pointer or data) */ private Node MergeSort(Node start) { /* Base case -- length 0 or 1 */ if (start == null || start.arbit == null) { return start; } /* Split head into 'middle' and 'nextofmiddle' sublists */ Node middle = getMiddle(start); Node nextofmiddle = middle.arbit; middle.arbit = null; /* Recursively sort the sublists */ Node left = MergeSort(start); Node right = MergeSort(nextofmiddle); /* answer = merge the two sorted lists together */ Node sortedlist = SortedMerge(left, right); return sortedlist; } // Utility function to get the middle of the linked list private Node getMiddle(Node source) { // Base case if (source == null) return source; Node fastptr = source.arbit; Node slowptr = source; // Move fastptr by two and slow ptr by one // Finally slowptr will point to middle node while (fastptr != null) { fastptr = fastptr.arbit; if (fastptr != null) { slowptr = slowptr.arbit; fastptr = fastptr.arbit; } } return slowptr; } private Node SortedMerge(Node a, Node b) { Node result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.arbit = SortedMerge(a.arbit, b); } else { result = b; result.arbit = SortedMerge(a, b.arbit); } return result; } // Driver code public static void Main(String[] args) { LinkedList list = new LinkedList(); /* Let us create the list shown above */ list.head = new Node(5); list.head.next = new Node(10); list.head.next.next = new Node(2); list.head.next.next.next = new Node(3); /* Sort the above created Linked List */ Node ahead = list.populateArbit(list.head); Console.WriteLine("Result Linked List is:"); list.printList(list.head, ahead); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to// populate arbit pointers// to next higher value using// merge sortvar head; /* Link list node */ class Node { constructor(val) { this.data = val; this.arbit = null; this.next = null; } } // Utility function to print // result linked list function printList(node, anode) { document.write( "Traversal using Next Pointer<br/>" ); while (node != null) { document.write(node.data + ", "); node = node.next; } document.write( "<br/>Traversal using Arbit Pointer<br/>" ); while (anode != null) { document.write(anode.data + ", "); anode = anode.arbit; } } // This function populates arbit // pointer in every node to the // next higher value. And returns // pointer to the node with // minimum value function populateArbit(start) { var temp = start; // Copy next pointers to arbit pointers while (temp != null) { temp.arbit = temp.next; temp = temp.next; } // Do merge sort for arbitrary pointers and // return head of arbitrary pointer linked list return MergeSort(start); } /* sorts the linked list formed by arbit pointers (does not change next pointer or data) */ function MergeSort(start) { /* Base case -- length 0 or 1 */ if (start == null || start.arbit == null) { return start; } /* Split head into 'middle' and 'nextofmiddle' sublists */ var middle = getMiddle(start); var nextofmiddle = middle.arbit; middle.arbit = null; /* Recursively sort the sublists */var left = MergeSort(start);var right = MergeSort(nextofmiddle); /* answer = merge the two sorted lists together */var sortedlist = SortedMerge(left, right); return sortedlist; } // Utility function to get the // middle of the linked list function getMiddle(source) { // Base case if (source == null) return source;var fastptr = source.arbit;var slowptr = source; // Move fastptr by two and slow ptr by one // Finally slowptr will point to middle node while (fastptr != null) { fastptr = fastptr.arbit; if (fastptr != null) { slowptr = slowptr.arbit; fastptr = fastptr.arbit; } } return slowptr; } function SortedMerge(a, b) {var result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.arbit = SortedMerge(a.arbit, b); } else { result = b; result.arbit = SortedMerge(a, b.arbit); } return result; } // Driver code /* Let us create the list shown above */ head = new Node(5); head.next = new Node(10); head.next.next = new Node(2); head.next.next.next = new Node(3); /* Sort the above created Linked List */ var ahead = populateArbit(head); document.write("Result Linked List is:<br/>"); printList(head, ahead); // This code contributed by gauravrajput1 </script> Result Linked List is: Traversal using Next Pointer 5, 10, 2, 3, Traversal using Arbit Pointer 2, 3, 5, 10, This article is contributed by Saurabh Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rathbhupendra nobody_cares princiraj1992 nidhi_biet rutvik_56 GauravRajput1 simranarora5sos ankita_saini arorakashish0911 hardikkoriintern Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jun, 2022" }, { "code": null, "e": 241, "s": 54, "text": "Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. Need to make the “arbitrary” pointer point to the next higher...
ReactJS shouldComponentUpdate() Method
16 Nov, 2020 The shouldComponentUpdate method allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. It only updates the component if the props passed to it changes. The shouldComponentUpdate method is majorly used for optimizing the performance and to increase the responsiveness of the website but do not rely on it to prevent rendering as it may lead to bugs. Syntax: shouldComponentUpdate(nextProps, nextState) Return value: It by default it returns true and if it returns false then render(), componentWillUpdate() and componentDidUpdate() method does not gets invoked. Example: In this example, we are going to build a counter application which only renders when its props value is changed. App.js Javascript import React, { useState } from "react";import Counter1 from "./Counter1";import Counter2 from "./Counter2"; const App = () => { // Using useState hooks for defining state const [counter1, setCounter1] = useState(0); const increase1 = () => { setCounter1(counter1 + 1); }; const [counter2, setCounter2] = useState(0); const increase2 = () => { setCounter2(counter2 + 1); }; return ( <div className="container"> <div> <Counter1 value={counter1} onClick={increase1} /> </div> <div> <Counter2 value={counter2} onClick={increase2} /> </div> </div> );}; export default App; Without using shouldComponentUpdate() method: Counter1.jsJavascriptJavascriptimport React, { Component } from "react"; class Counter1 extends Component { render() { console.log("Counter 1 is calling"); return ( <div> <h2>Counter 1:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter1; Counter1.js Javascript import React, { Component } from "react"; class Counter1 extends Component { render() { console.log("Counter 1 is calling"); return ( <div> <h2>Counter 1:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter1; Counter2.jsJavascriptJavascriptimport React, { Component } from "react"; class Counter2 extends Component { render() { console.log("Counter 2 is calling"); return ( <div> <h2>Counter 2:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter2; Counter2.js Javascript import React, { Component } from "react"; class Counter2 extends Component { render() { console.log("Counter 2 is calling"); return ( <div> <h2>Counter 2:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter2; Output: With using shouldComponentUpdate() Method: Counter1.jsJavascriptJavascriptimport React, { Component } from "react"; class Counter1 extends Component { shouldComponentUpdate(nextProps) { // Rendering the component only if // passed props value is changed if (nextProps.value !== this.props.value) { return true; } else { return false; } } render() { console.log("Counter 1 is calling"); return ( <div> <h2>Counter 1:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter1; Counter1.js Javascript import React, { Component } from "react"; class Counter1 extends Component { shouldComponentUpdate(nextProps) { // Rendering the component only if // passed props value is changed if (nextProps.value !== this.props.value) { return true; } else { return false; } } render() { console.log("Counter 1 is calling"); return ( <div> <h2>Counter 1:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter1; Counter2.jsJavascriptJavascriptimport React, { Component } from "react"; class Counter2 extends Component { shouldComponentUpdate (nextProps) { // Rendering the component only if // passed props value is changed if (nextProps.value !== this.props.value) { return true; } else { return false; } } render() { console.log("Counter 2 is calling"); return ( <div> <h2>Counter 2:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter2; Counter2.js Javascript import React, { Component } from "react"; class Counter2 extends Component { shouldComponentUpdate (nextProps) { // Rendering the component only if // passed props value is changed if (nextProps.value !== this.props.value) { return true; } else { return false; } } render() { console.log("Counter 2 is calling"); return ( <div> <h2>Counter 2:</h2> <h3>{this.props.value}</h3> <button onClick={this.props.onClick}>Add</button> </div> ); }} export default Counter2; Output: react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript 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) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Nov, 2020" }, { "code": null, "e": 260, "s": 52, "text": "The shouldComponentUpdate method allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. It only updates the component i...
Overlay Density Plots in Base R
17 Jun, 2021 In this article, we will discuss how to overlay density plot using some base functions of the R Programming Language. Overlaying density plots means creating some density plots of the different data over a single plot. Plot() : This is a generic function for plotting R objects. Syntax: plot(x, y, ...) Parameters: x: the coordinates of points in the plot. y: the y coordinates of points in the plot, ...: Arguments to be passed to methods, such as graphical parameters Density(): This is a generic function density that computes kernel density estimates. Its default method does so with the given kernel and bandwidth for uni-variate observations. Syntax: density(x,...) Parameters: x:-the data from which the estimate is to be computed. ...:-further arguments for (non-default) methods. Returns: This function will be returning the density plot of the given data. Lines(): This is a generic function taking coordinates given in various ways and joining the corresponding points with line segments. Syntax: lines(x, ...) Parameters: x:-coordinate vectors of points to join. ...:-Further graphical parameters R creates histogram using hist() function. Syntax: hist(v, main, xlab, xlim, ylim, breaks, col, border) Parameters: v: This parameter contains numerical values used in histogram. main: This parameter main is the title of the chart. col: This parameter is used to set color of the bars. xlab: This parameter is the label for horizontal axis. border: This parameter is used to set border color of each bar. xlim: This parameter is used for plotting values of x-axis. ylim: This parameter is used for plotting values of y-axis. breaks: This parameter is used as width of each bar. Overlaying two density plots may seem complex, but it is as simple as plotting a same density graph. For every other plot you just have to keep calling the function with their respective density and add their required mechanism to functions except the first one to keep drawing them on the same plot. Example 1: R gfg <-rnorm(500) a <- rnorm(200)b <- rnorm(100) plot(density(gfg))lines(density(a), col = "red")lines(density(b), col = "green") legend("topright", c("gfg", "a", "b"), col =c("black","red","green"), lty=1) Output: Example 2: R set.seed(99990) data<-data.frame(a=round(rnorm(1000,50,50)))data2<-data.frame(b=round(rnorm(600,30,30)))data3<-data.frame(c=round(rnorm(300,10,10))) hist(data$a, col="#abf5bf",main="overlaying histogram")hist(data2$b, col="#52d977", add=T)hist(data3$c, col="#669172", add=T) Output: Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? Logistic Regression in R Programming R - if statement Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 247, "s": 28, "text": "In this article, we will discuss how to overlay density plot using some base functions of the R Programming Language. Overlaying density plots means creating some density plot...
Python | Drop-down list in kivy using .kv file
08 Dec, 2021 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy Tutorial – Learn Kivy with Examples. A drop-down list can be used with custom widgets. It allows you to display a list of widgets under a displayed widget. Unlike other toolkits, the list of widgets can contain any type of widget: simple buttons, images etc.The positioning of the drop-down list is fully automatic: we will always try to place the dropdown list in a way that the user can select an item in the list. To work with this widget you must have to import:from kivy.uix.dropdown import DropDown Basic Approach: 1) import kivy 2) import kivyApp 3) import dropdown 4) import Floatlayout(according to need) 5) Set minimum version(optional) 6) Create Layout class 7) Create App class 9) create .kv file (name same as the app class): 1) create Dropdown 2) create callback 3) And many more styling as needed 10) return Layout/widget/Class(according to requirement) 11) Run an instance of the class #.py file Python3 '''Code of How to use drop-down list with.kv file''' # Program to Show how to create a switch # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # drop-down menu is a list of items that# appear whenever a piece of text or a# button is clicked.# To use drop down you must have ti import itfrom kivy.uix.dropdown import DropDown # module consists the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # The Button is a Label with associated actions that# are triggered when the button is pressed (# or released after a click / touch).from kivy. uix . button import Button class CustomDropDown(DropDown): pass class DropdownDemo(FloatLayout): '''The code of the application itself.''' def __init__(self, **kwargs): '''The button at the opening of the window is created here, not in kv ''' super(DropdownDemo, self).__init__(**kwargs) self.dropdown = CustomDropDown() # Creating a self widget button self.mainbutton = Button(text ='Do you in college?', size_hint_x = 0.6, size_hint_y = 0.15) # Added button to FloatLayout so inherits this class self.add_widget(self.mainbutton) # Adding actions # If click self.mainbutton.bind(on_release = self.dropdown.open) # root.select on_select called self.dropdown.bind(on_select = lambda\ instance, x: setattr(self.mainbutton, 'text', x)) self.dropdown.bind(on_select = self.callback) def callback(self, instance, x): '''x is self.mainbutton.text refreshed''' print ( "The chosen mode is: {0}" . format ( x ) ) class MainApp(App): '''The build function returns root, here root = DropdownDemo (). root can only be called in the kv file. ''' def build(self): return DropdownDemo() if __name__ == '__main__': MainApp().run() .kv file: Python3 <CustomDropDown>: Button: text: 'College Name' size_hint_y: None height: 44 on_release: root.select('College is') Label: text: 'Not in college' size_hint_y: None height: 44 Button: text: 'KccItm' size_hint_y: None height: 44 on_release: root.select('Kcc') Output: saurabh1990aror surindertarika1234 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2021" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it doe...
Class and Object in Scala
19 Aug, 2021 Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Or in other words, a class combines the fields and methods(member function which defines actions) into a single unit. Basically, in a class constructor is used for initializing new objects, fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. Declaration of class In Scala, a class declaration contains the class keyword, followed by an identifier(name) of the class. But there are some optional attributes which can be used with class declaration according to the application requirement. In general, class declarations can include these components, in order: Keyword class: A class keyword is used to declare the type class. Class name: The name should begin with a initial letter (capitalized by convention). Superclass(if any):The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. Traits(if any): A comma-separated list of traits implemented by the class, if any, preceded by the keyword extends. A class can implement more than one trait. Body: The class body is surrounded by { } (curly braces). Syntax: class Class_name{ // methods and fields } Note: The default modifier of the class is public. Example: Scala // A Scala program to illustrate// how to create a class // Name of the class is Smartphoneclass Smartphone{ // Class variables var number: Int = 16 var nameofcompany: String = "Apple" // Class method def Display() { println("Name of the company : " + nameofcompany); println("Total number of Smartphone generation: " + number); }}object Main{ // Main method def main(args: Array[String]) { // Class object var obj = new Smartphone(); obj.Display(); }} Output: Name of the company : Apple Total number of Smartphone generation: 16 It is a basic unit of Object Oriented Programming and represents the real-life entities. A typical Scala program creates many objects, which as you know, interact by invoking methods. An object consists of : State: It is represented by attributes of an object. It also reflects the properties of an object. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Consider Dog as an object and see the below diagram for its identity, state, and behavior. Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: Syntax: var obj = new Dog(); Scala also provides a feature named as companion objects in which you are allowed to create an object without using the new keyword. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor. Example: Scala // A Scala program to illustrate the// Initialization of an object // Class with primary constructorclass Dog(name:String, breed:String, age:Int, color:String ){ println("My name is:" + name + " my breed is:" + breed); println("I am: " + age + " and my color is :" + color); }object Main{ // Main method def main(args: Array[String]) { // Class object var obj = new Dog("tuffy", "papillon", 5, "white"); }} Output: My name is:tuffy my breed is:papillon I am: 5 and my color is :white Explanation: This class contains a single constructor. We can recognize a constructor because in Scala the body of a class is the body of the constructor and parameter-list follows the class name. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, ”papillon”, 5, ”white” as values for those arguments: var obj = new Dog("tuffy", "papillon", 5, "white"); The result of executing this statement can be illustrated as : Anonymous objects are the objects that are instantiated but does not contain any reference, you can create an anonymous object when you do not want to reuse it. Example: Scala // Scala program to illustrate how// to create an Anonymous object class GFG{ def display() { println("Welcome! GeeksforGeeks"); }}object Main{ // Main method def main(args: Array[String]) { // Creating Anonymous object of GFG class new GFG().display(); }} Output: Welcome! GeeksforGeeks anikaseth98 sagar0719kumar Scala Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | map() method Scala | flatMap Method String concatenation in Scala Scala | reduce() Function Type Casting in Scala Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example Enumeration in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2021" }, { "code": null, "e": 143, "s": 28, "text": "Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities." }, { "code": null, "e": 565, "s": 143, ...
list reverse function in C++ STL
14 Jun, 2022 The list::reverse() is a built-in function in C++ STL which is used to reverse a list container. It reverses the order of elements in the list container. Syntax: list_name.reverse() Parameters: This function does not accept any parameters. Return Value: This function does not return any value. It just reverses the order of elements in the list container with which it is used. Below program illustrate the list::reverse() function in C++ STL: CPP // CPP program to illustrate the// list::reverse() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Adding elements to the list demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // Initial list: cout << "Initial List: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; // reversing the list demoList.reverse(); // List after reversing the order of elements cout << "\n\nList after reversing: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; return 0;} Initial List: 10 20 30 40 List after reversing: 40 30 20 10 Time Complexity – Linear O(N) utkarshgupta110092 CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Jun, 2022" }, { "code": null, "e": 215, "s": 53, "text": "The list::reverse() is a built-in function in C++ STL which is used to reverse a list container. It reverses the order of elements in the list container. Syntax:" }, { ...
Flutter - Circular & Linear Progress Indicators - GeeksforGeeks
15 Feb, 2021 Progress Indicator in any application displays the time which is needed for some tasks to complete such as downloading, installation, uploading, file transfer, etc. This shows the progress of a task or the time to display the length of the processes. In Flutter, progress can be displayed in two ways: CircularProgressIndicator: A CircularProgressIndicator is a widget that shows progress along a circle. It is a circular progress bar that spins to indicate that the application is busy or on hold.LinearProgressIndicator: A LinearProgressIndicator also known as a progress bar is a widget that shows progress in a linear direction or along a line to indicate that the application is in progress. CircularProgressIndicator: A CircularProgressIndicator is a widget that shows progress along a circle. It is a circular progress bar that spins to indicate that the application is busy or on hold. LinearProgressIndicator: A LinearProgressIndicator also known as a progress bar is a widget that shows progress in a linear direction or along a line to indicate that the application is in progress. There are two types of progress indicators: Indeterminate: Indeterminate progress indicator is an indicator that does not display a specific value at any instance of time and only indicates that progress is being made. It does not indicate how much progress remains to be made. For creating an indeterminate progress bar we set the value property as null.Determinate: Determinate progress indicator is an indicator that has a specific value at each instance of time. It also indicates how much progress is completed. The value in the determinate progress indicator increases monotonically from 0 to 1, where 0 indicates that progress is just started and 1 indicates that the progress is completed. Indeterminate: Indeterminate progress indicator is an indicator that does not display a specific value at any instance of time and only indicates that progress is being made. It does not indicate how much progress remains to be made. For creating an indeterminate progress bar we set the value property as null. Determinate: Determinate progress indicator is an indicator that has a specific value at each instance of time. It also indicates how much progress is completed. The value in the determinate progress indicator increases monotonically from 0 to 1, where 0 indicates that progress is just started and 1 indicates that the progress is completed. Following are the steps to follow in order to implement the Progress Indicators in the Flutter app. Step 1: Import the material.dart package in order to display Flutter Progress Indicator widget implementing Material Design. import 'package:flutter/material.dart'; Step 2: Next, the following code needs to be implemented in the respective main.dart file. Dart import 'package:flutter/material.dart'; void main(){ runApp( MyApp() );} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Loader(), ); }} class Loader extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Color(0xFF4CAF50), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(), SizedBox( height: 15, ), LinearProgressIndicator(), ], ), ), ); }} Output: Default Progress Indicator Step 3: Now in order to improve the user interface of this application we need to implement some significant properties of the progress bar. Dart import 'package:flutter/material.dart'; void main(){ runApp( MyApp() );} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Loader(), ); }} class Loader extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Color(0xFF4CAF50), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator( backgroundColor: Colors.redAccent, valueColor: AlwaysStoppedAnimation(Colors.green), strokeWidth: 10, ), SizedBox( height: 15, ), LinearProgressIndicator( backgroundColor: Colors.redAccent, valueColor: AlwaysStoppedAnimation(Colors.green), minHeight: 20, ) ], ), ), ); }} Output: Improved UI Progress Indicator Explanation: Following is the explanation of above-mentioned code for implementing Progress Indicators in Flutter: backgroundColor: This property is used in order to set the background color of a linear loader and a circular spin loader in the progress bar.strokeWidth: This property specifies the width of the line that is used to draw a circle in a CircularProgressIndicator.minHeight: It is the minimum height of the line that is used to draw the indicator in a LinearProgressIndicator or in other words it is used to define how thick the line in an indicator looks.valueColor: It is used in order to define the progress indicator’s value as an animated value. valueColor property covers the highlights of the completed task valued.AlwaysStoppedAnimation: It is used in order to specify a constant color in the valueColor property.value: Value property is used in order to differentiate between the determinate and indeterminate progress bar. If the value property is set as null, the progress indicator is indeterminate, which means that it will show the predefined animation on the indicator with its motion that does not indicate how much progress is completed. If set as non-null, then it displays how much progress is being made at a particular instant. A value of 0.0 indicates that progress is just started and a value of 1.0 indicates that the progress is completed. backgroundColor: This property is used in order to set the background color of a linear loader and a circular spin loader in the progress bar. strokeWidth: This property specifies the width of the line that is used to draw a circle in a CircularProgressIndicator. minHeight: It is the minimum height of the line that is used to draw the indicator in a LinearProgressIndicator or in other words it is used to define how thick the line in an indicator looks. valueColor: It is used in order to define the progress indicator’s value as an animated value. valueColor property covers the highlights of the completed task valued. AlwaysStoppedAnimation: It is used in order to specify a constant color in the valueColor property. value: Value property is used in order to differentiate between the determinate and indeterminate progress bar. If the value property is set as null, the progress indicator is indeterminate, which means that it will show the predefined animation on the indicator with its motion that does not indicate how much progress is completed. If set as non-null, then it displays how much progress is being made at a particular instant. A value of 0.0 indicates that progress is just started and a value of 1.0 indicates that the progress is completed. android Flutter Flutter UI-components Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. MVVM (Model View ViewModel) Architecture Pattern in Android Bottom Navigation Bar in Android Android Architecture How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Asset Image Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter
[ { "code": null, "e": 25940, "s": 25912, "text": "\n15 Feb, 2021" }, { "code": null, "e": 26191, "s": 25940, "text": "Progress Indicator in any application displays the time which is needed for some tasks to complete such as downloading, installation, uploading, file transfer, etc...
Scrapping Weather prediction Data using Python and BS4 - GeeksforGeeks
29 Dec, 2020 This article revolves around scrapping weather prediction d data using python and bs4 library. Let’s checkout components used in the script – BeautifulSoup– It is a powerful Python library for pulling out data from HTML/XML files. It creates a parse tree for parsed pages that can be used to extract data from HTML/XML files.Requests – It is a Python HTTP library. It makes HTTP requests simpler. we just need to add the URL as an argument and the get() gets all the information from it. Step 1 – Run the following command to get the stored content from the URL into the response object(file): import requests# to get data from websitefile = requests.get("https://weather.com/en-IN/weather/tenday/l/INKA0344:1:IN") Step 2 – Parse HTML content: # import Beautifulsoup for scraping the data from bs4 import BeautifulSoupsoup = BeautifulSoup(file.content, "html.parser") Step 3 – Scraping the data from weather site run the following code: # create empty listlist =[]all = soup.find("div", {"class":"locations-title ten-day-page-title"}).find("h1").text # find all table with class-"twc-table"content = soup.find_all("table", {"class":"twc-table"})for items in content: for i in range(len(items.find_all("tr"))-1): # create empty dictionary dict = {} try: # assign value to given key dict["day"]= items.find_all("span", {"class":"date-time"})[i].text dict["date"]= items.find_all("span", {"class":"day-detail"})[i].text dict["desc"]= items.find_all("td", {"class":"description"})[i].text dict["temp"]= items.find_all("td", {"class":"temp"})[i].text dict["precip"]= items.find_all("td", {"class":"precip"})[i].text dict["wind"]= items.find_all("td", {"class":"wind"})[i].text dict["humidity"]= items.find_all("td", {"class":"humidity"})[i].text except: # assign None values if no items are there with specified class dict["day"]="None" dict["date"]="None" dict["desc"]="None" dict["temp"]="None" dict["precip"]="None" dict["wind"]="None" dict["humidity"]="None" # append dictionary values to the list list.append(dict) find_all: It is used to pick up all the HTML elements of tag passed in as an argument and its descendants.find:It will search for the elements of the tag passed.list.append(dict): This will append all the data to the list of type list. Step 4 – Convert the list file into CSV file to view the organized weather forecast data. Use the following code to convert the list into CSV file and store it into output.csv file: import pandas as pdconvert = pd.DataFrame(list)convert.to_csv("output.csv") . Syntax: pandas.DataFrame(data=None, index: Optional[Collection] = None, columns: Optional[Collection] = None, dtype: Union[str, numpy.dtype, ExtensionDtype, None] = None, copy: bool = False) Parameters: data: Dict can contain Series, arrays, constants, or list-like objects.index : It is used for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided.columns: column labels to use for resulting frame. Will default to RangeIndex (0, 1, 2, ..., n) if no column labels are provided.dtype: It is used to set the Default value.copy: It copy the data from input. default value is false. # read csv file using pandasa = pd.read_csv("output.csv")print(a) Output : Python web-scraping-exercises Python-BS3 Python-pandas Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24522, "s": 24494, "text": "\n29 Dec, 2020" }, { "code": null, "e": 24664, "s": 24522, "text": "This article revolves around scrapping weather prediction d data using python and bs4 library. Let’s checkout components used in the script –" }, { "code":...
How to delete particular data in a document in MongoDB?
You can use $unset. Let us first create a collection with documents − > db.demo20.insertOne( ... { ... ... "ListOfEmployee" : [ ... { ... "EmployeeName1" : "John" ... }, ... { ... "EmployeeName2" : "Carol" ... } ... ], ... "EmployeeName2" : [] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e138c3555d0fc6657d21f12") } Following is the query to display all documents from a collection with the help of find() method − > db.demo20.find(); This will produce the following output − { "_id" : ObjectId("5e138c3555d0fc6657d21f12"), "ListOfEmployee" : [ { "EmployeeName1" : "John" }, { "EmployeeName2" : "Carol" } ], "EmployeeName2" : [ ] } Following is the query to delete particular data in a document − > db.demo20.update({ "EmployeeName2": { "$exists": 1 }},{ "$unset": { "EmployeeName2": "" } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Following is the query to display all documents from a collection with the help of find() method − > db.demo20.find(); This will produce the following output − { "_id" : ObjectId("5e138c3555d0fc6657d21f12"), "ListOfEmployee" : [ { "EmployeeName1" : "John" }, { "EmployeeName2" : "Carol" } ] }
[ { "code": null, "e": 1132, "s": 1062, "text": "You can use $unset. Let us first create a collection with documents −" }, { "code": null, "e": 1488, "s": 1132, "text": "> db.demo20.insertOne(\n... {\n...\n... \"ListOfEmployee\" : [\n... {\n... \"Emplo...
until command in Linux with Examples
27 May, 2019 until command in Linux used to execute a set of commands as long as the final command in the ‘until’ Commands has an exit status which is not zero. It is mostly used where the user needs to execute a set of commands until a condition is true. Syntax: until COMMANDS; do COMMANDS; done Here, if the COMMANDS get evaluated to false then the statements will be executed. If the COMMANDS get evaluated to true then the no statements will be executed and control will go after the done statement. Example: Options: help until : It displays help information. linux-command Linux-Shell-Commands Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2019" }, { "code": null, "e": 295, "s": 52, "text": "until command in Linux used to execute a set of commands as long as the final command in the ‘until’ Commands has an exit status which is not zero. It is mostly used where th...
To find sum of two numbers without using any operator
30 May, 2022 Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used. Solution It’s a trick question. We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in printf() can be used to find the sum of two numbers. We can use ‘*’ which indicates the minimum width of output. For example, in the statement “printf(“%*d”, width, num);”, the specified ‘width’ is substituted in place of *, and ‘num’ is printed within the minimum width specified. If number of digits in ‘num’ is smaller than the specified ‘width’, the output is padded with blank spaces. If number of digits are more, the output is printed as it is (not truncated). In the following program, add() returns sum of x and y. It prints 2 spaces within the width specified using x and y. So total characters printed is equal to sum of x and y. That is why add() returns x+y. C++ C Python3 #include <iostream>using namespace std; int add(int x, int y){ return printf("%*c%*c", x, ' ', y, ' ');} // Driver codeint main(){ printf("Sum = %d", add(3, 4)); return 0;} // This code is contributed by shubhamsingh10 #include <stdio.h> int add(int x, int y){ return printf("%*c%*c", x, ' ', y, ' ');} // Driver codeint main(){ printf("Sum = %d", add(3, 4)); return 0;} # Python code for the above approachdef add(x, y) : return (x + y); # Driver codeif __name__ == "__main__": print("Sum = ", add(3, 4)) # This code is contributed by splvel62. Output: Sum = 7 Time Complexity: O(1) Auxiliary Space: O(1) The output is seven spaces followed by “Sum = 7”. We can avoid the leading spaces by using carriage return. Thanks to krazyCoder and Sandeep for suggesting this. The following program prints output without any leading spaces. C++ C Java Python3 C# Javascript #include <iostream>using namespace std; int add(int x, int y){ return printf("%*c%*c", x, '\r', y, '\r');} // Driver codeint main(){ printf("Sum = %d", add(3, 4)); return 0;} // This code is contributed by shubhamsingh10 #include <stdio.h> int add(int x, int y){ return printf("%*c%*c", x, '\r', y, '\r');} // Driver codeint main(){ printf("Sum = %d", add(3, 4)); return 0;} class GFG { static int add(int x, int y) { return (x + y); } // Driver code public static void main(String[] args) { System.out.printf("Sum = %d", add(3, 4)); }} // This code is contributed by Rajput-Ji # Python program for the above approachdef add(x, y) : return (x + y); # driver codeprint("Sum = ", add(3, 4)); # This code is contributed by sanjoy_62 // C# program for the above approachusing System; public class GFG { static int add(int x, int y) { return (x + y); } // Driver Code public static void Main(String[] args) { Console.WriteLine("Sum = " + add(3, 4)); }} // This code is contributed by code_hunt. <script> // JavaScript code for the above approach function add(x, y) { return (x + y); } // Driver Code document.write("Sum = " + add(3, 4)); // This code is contributed by avijitmondal1998.</script> Output: Sum = 7 Time Complexity: O(1) Auxiliary Space: O(1) Another Method : C++ C Java Python3 C# PHP Javascript #include <iostream>using namespace std; int main(){ int a = 10, b = 5; if (b > 0) { while (b > 0) { a++; b--; } } if (b < 0) { // when 'b' is negative while (b < 0) { a--; b++; } } cout << "Sum = " << a; return 0;} // This code is contributed by SHUBHAMSINGH10// This code is improved & fixed by Abhijeet Soni. #include <stdio.h> int main(){ int a = 10, b = 5; if (b > 0) { while (b > 0) { a++; b--; } } if (b < 0) { // when 'b' is negative while (b < 0) { a--; b++; } } printf("Sum = %d", a); return 0;} // This code is contributed by Abhijeet Soni // Java codeclass GfG { public static void main(String[] args) { int a = 10, b = 5; if (b > 0) { while (b > 0) { a++; b--; } } if (b < 0) { // when 'b' is negative while (b < 0) { a--; b++; } } System.out.println("Sum is: " + a); }} // This code is contributed by Abhijeet Soni # Python 3 Code if __name__ == '__main__': a = 10 b = 5 if b > 0: while b > 0: a = a + 1 b = b - 1 if b < 0: while b < 0: a = a - 1 b = b + 1 print("Sum is: ", a) # This code is contributed by Akanksha Rai# This code is improved & fixed by Abhijeet Soni // C# codeusing System; class GFG { static public void Main() { int a = 10, b = 5; if (b > 0) { while (b > 0) { a++; b--; } } if (b < 0) { // when 'b' is negative while (b < 0) { a--; b++; } } Console.Write("Sum is: " + a); }} // This code is contributed by Tushil// This code is improved & fixed by Abhijeet Soni. <?php// PHP Code$a = 10;$b = 5; if ($b > 0) {while($b > 0){ $a++; $b--;}} if ($b < 0) {while($b < 0){ $a--; $b++;}} echo "Sum is: ", $a; // This code is contributed by Dinesh// This code is improved & fixed by Abhijeet Soni.?> <script> // Javascript program for the above approach // Driver Code let a = 10, b = 5; if (b > 0) { while (b > 0) { a++; b--; } } if (b < 0) { // when 'b' is negative while (b < 0) { a--; b++; } } document.write("Sum = " + a); </script> Output: sum = 15 Time Complexity: O(b) Auxiliary Space: O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above falgunatara prerna saini jit_t Akanksha_Rai SHUBHAMSINGH10 soniabhijeet94 souravghosh0416 subham348 rishavmahato348 subhammahato348 code_hunt GauravRajput1 sanjoy_62 avijitmondal1998 splevel62 C-Operators C Language Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Unordered Sets in C++ Standard Template Library Memory Layout of C Programs Power Function in C/C++ INT_MAX and INT_MIN in C/C++ and Applications Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2022" }, { "code": null, "e": 201, "s": 52, "text": "Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used." }, { "code": nul...
Expression contains redundant bracket or not
16 Jun, 2022 Given a string of balanced expression, find if it contains a redundant parenthesis or not. A set of parenthesis are redundant if the same sub-expression is surrounded by unnecessary or multiple brackets. Print ‘Yes’ if redundant, else ‘No’.Note: Expression may contain ‘+‘, ‘*‘, ‘–‘ and ‘/‘ operators. Given expression is valid and there are no white spaces present.Example: Input: ((a+b)) (a+(b)/c) (a+b*(c-d)) Output: Yes Yes No Explanation: 1. ((a+b)) can reduced to (a+b), this Redundant 2. (a+(b)/c) can reduced to (a+b/c) because b is surrounded by () which is redundant. 3. (a+b*(c-d)) doesn't have any redundant or multiple brackets. The idea is to use stack, which is discussed in this article. For any sub-expression of expression, if we are able to pick any sub-expression of expression surrounded by (), then we again left with () as part of string, we have redundant braces. We iterate through the given expression and for each character in the expression, if the character is an open parenthesis ‘(‘ or any of the operators or operands, we push it to the stack. If the character is close parenthesis ‘)’, then pop characters from the stack till matching open parenthesis ‘(‘ is found. Now for redundancy two condition will arise while popping- If immediate pop hits an open parenthesis ‘(‘, then we have found a duplicate parenthesis. For example, (((a+b))+c) has duplicate brackets around a+b. When we reach the second “)” after a+b, we have “((” in the stack. Since the top of stack is an opening bracket, we conclude that there are duplicate brackets. If immediate pop doesn’t hit any operand(‘*’, ‘+’, ‘/’, ‘-‘) then it indicates the presence of unwanted brackets surrounded by expression. For instance, (a)+b contain unwanted () around a thus it is redundant. If immediate pop hits an open parenthesis ‘(‘, then we have found a duplicate parenthesis. For example, (((a+b))+c) has duplicate brackets around a+b. When we reach the second “)” after a+b, we have “((” in the stack. Since the top of stack is an opening bracket, we conclude that there are duplicate brackets. If immediate pop doesn’t hit any operand(‘*’, ‘+’, ‘/’, ‘-‘) then it indicates the presence of unwanted brackets surrounded by expression. For instance, (a)+b contain unwanted () around a thus it is redundant. C++ Java Python3 C# Javascript /* C++ Program to check whether valid expression is redundant or not*/#include <bits/stdc++.h>using namespace std; // Function to check redundant brackets in a// balanced expressionbool checkRedundancy(string& str){ // create a stack of characters stack<char> st; // Iterate through the given expression for (auto& ch : str) { // if current character is close parenthesis ')' if (ch == ')') { char top = st.top(); st.pop(); // If immediate pop have open parenthesis '(' // duplicate brackets found bool flag = true; while (!st.empty() and top != '(') { // Check for operators in expression if (top == '+' || top == '-' || top == '*' || top == '/') flag = false; // Fetch top element of stack top = st.top(); st.pop(); } // If operators not found if (flag == true) return true; } else st.push(ch); // push open parenthesis '(', // operators and operands to stack } return false;} // Function to check redundant bracketsvoid findRedundant(string& str){ bool ans = checkRedundancy(str); if (ans == true) cout << "Yes\n"; else cout << "No\n";} // Driver codeint main(){ string str = "((a+b))"; findRedundant(str); str = "(a+(b)/c)"; findRedundant(str); str = "(a+b*(c-d))"; findRedundant(str); return 0;} /* Java Program to check whether validexpression is redundant or not*/import java.util.Stack;public class GFG {// Function to check redundant brackets in a// balanced expression static boolean checkRedundancy(String s) { // create a stack of characters Stack<Character> st = new Stack<>(); char[] str = s.toCharArray(); // Iterate through the given expression for (char ch : str) { // if current character is close parenthesis ')' if (ch == ')') { char top = st.peek(); st.pop(); // If immediate pop have open parenthesis '(' // duplicate brackets found boolean flag = true; while (top != '(') { // Check for operators in expression if (top == '+' || top == '-' || top == '*' || top == '/') { flag = false; } // Fetch top element of stack top = st.peek(); st.pop(); } // If operators not found if (flag == true) { return true; } } else { st.push(ch); // push open parenthesis '(', } // operators and operands to stack } return false; } // Function to check redundant brackets static void findRedundant(String str) { boolean ans = checkRedundancy(str); if (ans == true) { System.out.println("Yes"); } else { System.out.println("No"); } } // Driver code public static void main(String[] args) { String str = "((a+b))"; findRedundant(str); str = "(a+(b)/c)"; findRedundant(str); str = "(a+b*(c-d))"; findRedundant(str); }} # Python3 Program to check whether valid# expression is redundant or not # Function to check redundant brackets# in a balanced expressiondef checkRedundancy(Str): # create a stack of characters st = [] # Iterate through the given expression for ch in Str: # if current character is close # parenthesis ')' if (ch == ')'): top = st[-1] st.pop() # If immediate pop have open parenthesis # '(' duplicate brackets found flag = True while (top != '('): # Check for operators in expression if (top == '+' or top == '-' or top == '*' or top == '/'): flag = False # Fetch top element of stack top = st[-1] st.pop() # If operators not found if (flag == True): return True else: st.append(ch) # append open parenthesis '(', # operators and operands to stack return False # Function to check redundant bracketsdef findRedundant(Str): ans = checkRedundancy(Str) if (ans == True): print("Yes") else: print("No") # Driver codeif __name__ == '__main__': Str = "((a+b))" findRedundant(Str) Str = "(a+(b)/c)" findRedundant(Str) Str = "(a+b*(c-d))" findRedundant(Str) # This code is contributed by PranchalK /* C# Program to check whether validexpression is redundant or not*/using System;using System.Collections.Generic; class GFG{ // Function to check redundant brackets in a // balanced expression static bool checkRedundancy(String s) { // create a stack of characters Stack<char> st = new Stack<char>(); char[] str = s.ToCharArray(); // Iterate through the given expression foreach (char ch in str) { // if current character is close parenthesis ')' if (ch == ')') { char top = st.Peek(); st.Pop(); // If immediate pop have open parenthesis '(' // duplicate brackets found bool flag = true; while (top != '(') { // Check for operators in expression if (top == '+' || top == '-' || top == '*' || top == '/') { flag = false; } // Fetch top element of stack top = st.Peek(); st.Pop(); } // If operators not found if (flag == true) { return true; } } else { st.Push(ch); // push open parenthesis '(', } // operators and operands to stack } return false; } // Function to check redundant brackets static void findRedundant(String str) { bool ans = checkRedundancy(str); if (ans == true) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } // Driver code public static void Main(String[] args) { String str = "((a+b))"; findRedundant(str); str = "(a+(b)/c)"; findRedundant(str); str = "(a+b*(c-d))"; findRedundant(str); }} /* This code contributed by PrinciRaj1992 */ <script> /* JavaScript Program to check whether valid expression is redundant or not*/ // Function to check redundant brackets in a// balanced expressionfunction checkRedundancy(str){ // create a stack of characters var st = []; var ans = false; // Iterate through the given expression str.split('').forEach(ch => { // if current character is close parenthesis ')' if (ch == ')') { var top = st[st.length-1]; st.pop(); // If immediate pop have open parenthesis '(' // duplicate brackets found var flag = true; while (st.length!=0 && top != '(') { // Check for operators in expression if (top == '+' || top == '-' || top == '*' || top == '/') flag = false; // Fetch top element of stack top = st[st.length-1]; st.pop(); } // If operators not found if (flag == true) ans = true; } else st.push(ch); // push open parenthesis '(', // operators and operands to stack }); return ans;} // Function to check redundant bracketsfunction findRedundant(str){ var ans = checkRedundancy(str); if (ans == true) document.write( "Yes<br>"); else document.write( "No<br>");} // Driver code var str = "((a+b))";findRedundant(str); str = "(a+(b)/c)";findRedundant(str); str = "(a+b*(c-d))";findRedundant(str); </script> Yes Yes No Time complexity : O(n) Auxiliary Space : O(n) Rajput-Ji PranchalKatiyar princiraj1992 randomuserhere rutvik_56 rishabhdevba 2002sukhdevsuthar pushpendrayadav1057 mahendrabagul569 expression-evaluation Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack in Python Stack Class in Java Check for Balanced Brackets in an expression (well-formedness) using Stack Introduction to Data Structures Stack | Set 2 (Infix to Postfix) Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 431, "s": 54, "text": "Given a string of balanced expression, find if it contains a redundant parenthesis or not. A set of parenthesis are redundant if the same sub-expression is surrounded by unne...
List Interface in Java with Examples
07 Jul, 2022 The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. The List interface is found in java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5. Declaration: The List interface is declared as: public interface List<E> extends Collection<E> ; Let us elaborate on creating objects or instances in a List class. Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List. Just like several other user-defined ‘interfaces’ implemented by user-defined ‘classes’, List is an ‘interface’, implemented by the ArrayList class, pre-defined in the java.util package. Syntax: This type of safelist can be defined as: List<Obj> list = new ArrayList<Obj> (); Note: Obj is the type of the object to be stored in List Example: Java // Java program to Demonstrate List Interface // Importing all utility classesimport java.util.*; // Main class// ListDemo classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List interface // implemented by the ArrayList class List<Integer> l1 = new ArrayList<Integer>(); // Adding elements to object of List interface // Custom inputs l1.add(0, 1); l1.add(1, 2); // Print the elements inside the object System.out.println(l1); // Now creating another object of the List // interface implemented ArrayList class // Declaring object of integer type List<Integer> l2 = new ArrayList<Integer>(); // Again adding elements to object of List interface // Custom inputs l2.add(1); l2.add(2); l2.add(3); // Will add list l2 from 1 index l1.addAll(1, l2); System.out.println(l1); // Removes element from index 1 l1.remove(1); // Printing the updated List 1 System.out.println(l1); // Prints element at index 3 in list 1 // using get() method System.out.println(l1.get(3)); // Replace 0th element with 5 // in List 1 l1.set(0, 5); // Again printing the updated List 1 System.out.println(l1); }} [1, 2] [1, 1, 2, 3, 2] [1, 2, 3, 2] 2 [5, 2, 3, 2] Now let us perform various operations using List Interface to have a better understanding of the same. We will be discussing the following operations listed below and later on implementing via clean java codes. Since List is an interface, it can be used only with a class that implements this interface. Now, let’s see how to perform a few frequently used operations on the List. Operation 1: Adding elements to List class using add() method Operation 2: Updating elements in List class using set() method Operation 3: Removing elements using remove() method Now let us discuss the operations individually and implement the same in the code to grasp a better grip over it. Operation 1: Adding elements to List class using add() method In order to add an element to the list, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. Parameters: It takes 2 parameters, namely: add(Object): This method is used to add an element at the end of the List. add(int index, Object): This method is used to add an element at a specific index in the List Example: Java // Java Program to Add Elements to a List // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an object of List interface, // implemented by ArrayList class List<String> al = new ArrayList<>(); // Adding elements to object of List interface // Custom elements al.add("Geeks"); al.add("Geeks"); al.add(1, "For"); // Print all the elements inside the // List interface object System.out.println(al); }} [Geeks, For, Geeks] Operation 2: Updating elements After adding the elements, if we wish to change the element, it can be done using the set() method. Since List is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. Example: Java // Java Program to Update Elements in a List // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an object of List interface List<String> al = new ArrayList<>(); // Adding elements to object of List class al.add("Geeks"); al.add("Geeks"); al.add(1, "Geeks"); // Display theinitial elements in List System.out.println("Initial ArrayList " + al); // Setting (updating) element at 1st index // using set() method al.set(1, "For"); // Print and display the updated List System.out.println("Updated ArrayList " + al); }} Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks] Operation 3: Removing Elements In order to remove an element from a list, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are: Parameters: remove(Object): This method is used to simply remove an object from the List. If there are multiple such objects, then the first occurrence of the object is removed. remove(int index): Since a List is indexed, this method takes an integer value which simply removes the element present at that specific index in the List. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated. Example: Java // Java Program to Remove Elements from a List // Importing List and ArrayList classes// from java.util packageimport java.util.ArrayList;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating List class object List<String> al = new ArrayList<>(); // Adding elements to the object // Custom inputs al.add("Geeks"); al.add("Geeks"); // Adding For at 1st indexes al.add(1, "For"); // Print the initialArrayList System.out.println("Initial ArrayList " + al); // Now remove element from the above list // present at 1st index al.remove(1); // Print the List after removal of element System.out.println("After the Index Removal " + al); // Now remove the current object from the updated // List al.remove("Geeks"); // Finally print the updated List now System.out.println("After the Object Removal " + al); }} Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks] Till now we are having a very small input size and we are doing operations manually for every entity. Now let us discuss various ways by which we can iterate over the list to get them working for a larger sample set. Methods: There are multiple ways to iterate through the List. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop. Example: Java // Java program to Iterate the Elements// in an ArrayList // Importing java utility classesimport java.util.*; // Main classpublic class GFG { // main driver method public static void main(String args[]) { // Creating an empty Arraylist of string type List<String> al = new ArrayList<>(); // Adding elements to above object of ArrayList al.add("Geeks"); al.add("Geeks"); // Adding element at specified position // inside list object al.add(1, "For"); // Using for loop for iteration for (int i = 0; i < al.size(); i++) { // Using get() method to // access particular element System.out.print(al.get(i) + " "); } // New line for better readability System.out.println(); // Using for-each loop for iteration for (String str : al) // Printing all the elements // which was inside object System.out.print(str + " "); }} Geeks For Geeks Geeks For Geeks Since the main concept behind the different types of the lists is the same, the list interface contains the following methods: Method Description Both the List interface and the Set interface inherits the Collection interface. However, there exists some differences between them. Now let us discuss the classes that implement the List Interface for which first do refer to the pictorial representation below to have a better understanding of the List interface. It is as follows: AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the List interface. A separate functionality is implemented in each of the mentioned classes. They are as follows: AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. We will proceed in this manner. ArrayList Vector Stack LinkedList Let us discuss them sequentially and implement the same to figure out the working of the classes with the List interface. An ArrayList class which is implemented in the collection framework provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. Let’s see how to create a list object using this class. Example: Java // Java program to demonstrate the// creation of list object using the// ArrayList class import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Size of ArrayList int n = 5; // Declaring the List with initial size n List<Integer> arrli = new ArrayList<Integer>(n); // Appending the new elements // at the end of the list for (int i = 1; i <= n; i++) arrli.add(i); // Printing elements System.out.println(arrli); // Remove element at index 3 arrli.remove(3); // Displaying the list after deletion System.out.println(arrli); // Printing elements one by one for (int i = 0; i < arrli.size(); i++) System.out.print(arrli.get(i) + " "); }} [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5 Vector is a class that is implemented in the collection framework implements a growable array of objects. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. Vectors basically fall in legacy classes but now it is fully compatible with collections. Let’s see how to create a list object using this class. Example: Java // Java program to demonstrate the// creation of list object using the// Vector class import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Size of the vector int n = 5; // Declaring the List with initial size n List<Integer> v = new Vector<Integer>(n); // Appending the new elements // at the end of the list for (int i = 1; i <= n; i++) v.add(i); // Printing elements System.out.println(v); // Remove element at index 3 v.remove(3); // Displaying the list after deletion System.out.println(v); // Printing elements one by one for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + " "); }} [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5 Stack is a class that is implemented in the collection framework and extends the vector class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. Let’s see how to create a list object using this class. Example: Java // Java program to demonstrate the// creation of list object using the// Stack class import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Size of the stack int n = 5; // Declaring the List List<Integer> s = new Stack<Integer>(); // Appending the new elements // at the end of the list for (int i = 1; i <= n; i++) s.add(i); // Printing elements System.out.println(s); // Remove element at index 3 s.remove(3); // Displaying the list after deletion System.out.println(s); // Printing elements one by one for (int i = 0; i < s.size(); i++) System.out.print(s.get(i) + " "); }} [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5 LinkedList is a class that is implemented in the collection framework which inherently implements the linked list data structure. It is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. Let’s see how to create a list object using this class. Example: Java // Java program to demonstrate the// creation of list object using the// LinkedList class import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Size of the LinkedList int n = 5; // Declaring the List with initial size n List<Integer> ll = new LinkedList<Integer>(); // Appending the new elements // at the end of the list for (int i = 1; i <= n; i++) ll.add(i); // Printing elements System.out.println(ll); // Remove element at index 3 ll.remove(3); // Displaying the list after deletion System.out.println(ll); // Printing elements one by one for (int i = 0; i < ll.size(); i++) System.out.print(ll.get(i) + " "); }} [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5 Chinmoy Lenka KaashyapMSK aswinpm14 solankimayank simmytarika5 surindertarika1234 surinderdawra388 as360571 casesensitiveunofficial kashishsoda gulshankumarar231 akshaysingh98088 nishkarshgandhi Java - util package Java-Collections java-list Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 344, "s": 52, "text": "The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate va...
Number Theory (Interesting Facts and Algorithms)
Difficulty Level : Hard Questions based on various concepts of number theory and different types of number are quite frequently asked in programming contests. In this article, we discuss some famous facts and algorithms: Interesting Facts : All 4 digit palindromic numbers are divisible by 11.If we repeat a three-digit number twice, to form a six-digit number. The result will be divisible by 7, 11 and 13, and dividing by all three will give your original three-digit number.A number of form 2N has exactly N+1 divisors. For example 4 has 3 divisors, 1, 2 and 4.To calculate sum of factors of a number, we can find the number of prime factors and their exponents. Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). All 4 digit palindromic numbers are divisible by 11. If we repeat a three-digit number twice, to form a six-digit number. The result will be divisible by 7, 11 and 13, and dividing by all three will give your original three-digit number. A number of form 2N has exactly N+1 divisors. For example 4 has 3 divisors, 1, 2 and 4. To calculate sum of factors of a number, we can find the number of prime factors and their exponents. Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). Sum of divisors = (1 + p1 + p12 ... p1a1) * (1 + p2 + p22 ... p2a2) * ............................................. (1 + pk + pk2 ... pkak) We can notice that individual terms of above formula are Geometric Progressions (GP). We can rewrite the formula as. Sum of divisors = (p1a1+1 - 1)/(p1 -1) * (p2a2+1 - 1)/(p2 -1) * .................................. (pkak+1 - 1)/(pk -1) For a product of N numbers, if we have to subtract a constant K such that the product gets its maximum value, then subtract it from a largest value such that largest value-k is greater than 0. If we have to subtract a constant K such that the product gets its minimum value, then subtract it from the smallest value where smallest value-k should be greater than 0Goldbach’s conjecture: Every even integer greater than 2 can be expressed as the sum of 2 primes.Perfect numbers or Amicable numbers: Perfect numbers are those numbers which are equal to the sum of their proper divisors. Example: 6 = 1 + 2 + 3Lychrel numbers: Are those numbers that cannot form a palindrome when repeatedly reversed and added to itself. For example 47 is not a Lychrel Number as 47 + 74 = 121Lemoine’s Conjecture : Any odd integer greater than 5 can be expressed as a sum of an odd prime (all primes other than 2 are odd) and an even semiprime. A semiprime number is a product of two prime numbers. This is called Lemoine’s conjecture.Fermat’s Last Theorem : According to the theorem, no three positive integers a, b, c satisfy the equation, for any integer value of n greater than 2. For n = 1 and n = 2, the equation have infinitely many solutions. For a product of N numbers, if we have to subtract a constant K such that the product gets its maximum value, then subtract it from a largest value such that largest value-k is greater than 0. If we have to subtract a constant K such that the product gets its minimum value, then subtract it from the smallest value where smallest value-k should be greater than 0 Goldbach’s conjecture: Every even integer greater than 2 can be expressed as the sum of 2 primes. Perfect numbers or Amicable numbers: Perfect numbers are those numbers which are equal to the sum of their proper divisors. Example: 6 = 1 + 2 + 3 Lychrel numbers: Are those numbers that cannot form a palindrome when repeatedly reversed and added to itself. For example 47 is not a Lychrel Number as 47 + 74 = 121 Lemoine’s Conjecture : Any odd integer greater than 5 can be expressed as a sum of an odd prime (all primes other than 2 are odd) and an even semiprime. A semiprime number is a product of two prime numbers. This is called Lemoine’s conjecture. Fermat’s Last Theorem : According to the theorem, no three positive integers a, b, c satisfy the equation, for any integer value of n greater than 2. For n = 1 and n = 2, the equation have infinitely many solutions. Number Theory Algorithms GCD and LCM GCD and LCMLCM of arrayGCD of arrayBasic and Extended Euclidean algorithms GCD and LCM LCM of array GCD of array Basic and Extended Euclidean algorithms Recent Articles on GCD and LCM! Prime Factorization and Divisors : Prime factorsPollard’s Rho Algorithm for Prime FactorizationFind all divisors of a natural numberSum of all proper divisors of a natural numberPrime Factorization using Sieve O(log n) for multiple queriesFind politeness of a numberPrint prime numbers in a given range using C++ STLk-th prime factor of a given numberSmith Numbers Prime factors Pollard’s Rho Algorithm for Prime Factorization Find all divisors of a natural number Sum of all proper divisors of a natural number Prime Factorization using Sieve O(log n) for multiple queries Find politeness of a number Print prime numbers in a given range using C++ STL k-th prime factor of a given number Smith Numbers Recent Articles on Prime Factors! Fibonacci Numbers: Fibonacci NumbersInteresting facts about Fibonacci numbersHow to check if a given number is Fibonacci number?Zeckendorf’s Theorem (Non-Neighbouring Fibonacci Representation) Fibonacci Numbers Interesting facts about Fibonacci numbers How to check if a given number is Fibonacci number? Zeckendorf’s Theorem (Non-Neighbouring Fibonacci Representation) Recent Articles on Fibonacci Numbers! Catalan Numbers : Catalan numbersApplications of Catalan Numbers Catalan numbers Applications of Catalan Numbers Recent Articles on Catalan Numbers! Modular Arithmetic : Modular Exponentiation (Power in Modular Arithmetic)Modular multiplicative inverseModular DivisionMultiplicative orderFind Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)Euler’s criterion (Check if square root under modulo p exists)Multiply large integers under large moduloFind sum of modulo K of first N natural numberHow to compute mod of a big number?BigInteger Class in JavaModulo 10^9+7 (1000000007)How to avoid overflow in modular multiplication?RSA Algorithm in CryptographyFind (a^b)%m where ‘a’ is very largeFind power of power under mod of a prime Modular Exponentiation (Power in Modular Arithmetic) Modular multiplicative inverse Modular Division Multiplicative order Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3) Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm) Euler’s criterion (Check if square root under modulo p exists) Multiply large integers under large modulo Find sum of modulo K of first N natural number How to compute mod of a big number? BigInteger Class in Java Modulo 10^9+7 (1000000007) How to avoid overflow in modular multiplication? RSA Algorithm in Cryptography Find (a^b)%m where ‘a’ is very large Find power of power under mod of a prime Recent Articles on Modular Arithmetic! Euler Totient Function: Euler’s Totient FunctionOptimized Euler Totient Function for Multiple EvaluationsEuler’s Totient function for all numbers smaller than or equal to nPrimitive root of a prime number n modulo n Euler’s Totient Function Optimized Euler Totient Function for Multiple Evaluations Euler’s Totient function for all numbers smaller than or equal to n Primitive root of a prime number n modulo n nCr Computations : Binomial CoefficientCompute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)Compute nCr % p | Set 2 (Lucas Theorem)Compute nCr % p | Set 3 (Using Fermat Little Theorem) Binomial Coefficient Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution) Compute nCr % p | Set 2 (Lucas Theorem) Compute nCr % p | Set 3 (Using Fermat Little Theorem) Chinese Remainder Theorem : Set 1 (Introduction)Set 2 (Inverse Modulo based Implementation)Cyclic Redundancy Check and Modulo-2 DivisionUsing Chinese Remainder Theorem to Combine Modular equations Set 1 (Introduction) Set 2 (Inverse Modulo based Implementation) Cyclic Redundancy Check and Modulo-2 Division Using Chinese Remainder Theorem to Combine Modular equations Factorial : FactorialLegendre’s formula (Given p and n, find the largest x such that p^x divides n!)Sum of divisors of factorial of a numberCount Divisors of FactorialCompute n! under modulo pWilson’s TheoremPrimality Test | Set 1 (Introduction and School Method)Primality Test | Set 2 (Fermat Method)Primality Test | Set 3 (Miller–Rabin)Primality Test | Set 4 (Solovay-Strassen)GFact 22 | (2^x + 1 and Prime)Euclid’s LemmaSieve of EratosthenesSegmented SieveSieve of AtkinSieve of Sundaram to print all primes smaller than nSieve of Eratosthenes in 0(n) time complexityCheck if a large number is divisible by 3 or notCheck if a large number is divisible by 11 or notTo check divisibility of any large number by 999Carmichael NumbersGenerators of finite cyclic group under additionMeasure one litre using two vessels and infinite water supplyProgram to find last digit of n’th Fibonacci NumberGCD of two numbers when one of them can be very largeFind Last Digit Of a^b for Large NumbersRemainder with 7 for large numbersCount all sub-arrays having sum divisible by kPartition a number into two divisible partsNumber of substrings divisible by 6 in a string of integers‘Practice Problems’ on Modular Arithmetic‘Practice Problems’ on Number TheoryAsk a Question on Number theoryPadovan, OESIS Factorial Legendre’s formula (Given p and n, find the largest x such that p^x divides n!) Sum of divisors of factorial of a number Count Divisors of Factorial Compute n! under modulo pWilson’s TheoremPrimality Test | Set 1 (Introduction and School Method)Primality Test | Set 2 (Fermat Method)Primality Test | Set 3 (Miller–Rabin)Primality Test | Set 4 (Solovay-Strassen)GFact 22 | (2^x + 1 and Prime)Euclid’s LemmaSieve of EratosthenesSegmented SieveSieve of AtkinSieve of Sundaram to print all primes smaller than nSieve of Eratosthenes in 0(n) time complexityCheck if a large number is divisible by 3 or notCheck if a large number is divisible by 11 or notTo check divisibility of any large number by 999Carmichael NumbersGenerators of finite cyclic group under additionMeasure one litre using two vessels and infinite water supplyProgram to find last digit of n’th Fibonacci NumberGCD of two numbers when one of them can be very largeFind Last Digit Of a^b for Large NumbersRemainder with 7 for large numbersCount all sub-arrays having sum divisible by kPartition a number into two divisible partsNumber of substrings divisible by 6 in a string of integers‘Practice Problems’ on Modular Arithmetic‘Practice Problems’ on Number TheoryAsk a Question on Number theoryPadovan, OESIS Wilson’s TheoremPrimality Test | Set 1 (Introduction and School Method)Primality Test | Set 2 (Fermat Method)Primality Test | Set 3 (Miller–Rabin)Primality Test | Set 4 (Solovay-Strassen)GFact 22 | (2^x + 1 and Prime)Euclid’s LemmaSieve of EratosthenesSegmented SieveSieve of AtkinSieve of Sundaram to print all primes smaller than nSieve of Eratosthenes in 0(n) time complexityCheck if a large number is divisible by 3 or notCheck if a large number is divisible by 11 or notTo check divisibility of any large number by 999Carmichael NumbersGenerators of finite cyclic group under additionMeasure one litre using two vessels and infinite water supplyProgram to find last digit of n’th Fibonacci NumberGCD of two numbers when one of them can be very largeFind Last Digit Of a^b for Large NumbersRemainder with 7 for large numbersCount all sub-arrays having sum divisible by kPartition a number into two divisible partsNumber of substrings divisible by 6 in a string of integers‘Practice Problems’ on Modular Arithmetic‘Practice Problems’ on Number TheoryAsk a Question on Number theoryPadovan, OESIS Wilson’s Theorem Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method) Primality Test | Set 3 (Miller–Rabin) Primality Test | Set 4 (Solovay-Strassen) GFact 22 | (2^x + 1 and Prime) Euclid’s Lemma Sieve of Eratosthenes Segmented Sieve Sieve of Atkin Sieve of Sundaram to print all primes smaller than n Sieve of Eratosthenes in 0(n) time complexity Check if a large number is divisible by 3 or not Check if a large number is divisible by 11 or not To check divisibility of any large number by 999 Carmichael Numbers Generators of finite cyclic group under addition Measure one litre using two vessels and infinite water supply Program to find last digit of n’th Fibonacci Number GCD of two numbers when one of them can be very large Find Last Digit Of a^b for Large Numbers Remainder with 7 for large numbers Count all sub-arrays having sum divisible by k Partition a number into two divisible parts Number of substrings divisible by 6 in a string of integers ‘Practice Problems’ on Modular Arithmetic ‘Practice Problems’ on Number Theory Ask a Question on Number theory Padovan, OESIS chhabradhanvi binomial coefficient number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Median of two sorted arrays of same size Product of Array except itself Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 24, "s": 0, "text": "Difficulty Level :\nHard" }, { "code": null, "e": 221, "s": 24, "text": "Questions based on various concepts of number theory and different types of number are quite frequently asked in programming contests. In this article, we discuss so...
Count ways to distribute m items among n people
06 May, 2021 Given m and n representing number of mangoes and number of people respectively. Task is to calculate number of ways to distribute m mangoes among n people. Considering both variables m and n, we arrive at 4 typical use cases where mangoes and people are considered to be:1) Both identical 2) Unique and identical respectively 3) Identical and unique respectively 4) Both unique Prerequisites: Binomial Coefficient | Permutation and Combination Case 1: Distributing m identical mangoes amongst n identical peopleIf we try to spread m mangoes in a row, our goal is to divide these m mangoes among n people sitting somewhere between arrangement of these mangoes. All we need to do is pool these m mangoes into n sets so that each of these n sets can be allocated to n people respectively. To accomplish above task, we need to partition the initial arrangement of mangoes by using n-1 partitioners to create n sets of mangoes. In this case we need to arrange m mangoes and n-1 partitioners all together. So we need ways to calculate our answer. Illustration given below represents an example(a way) of an arrangement of partitions created after placing 3 partitioners namely P1, P2, P3 which partitioned all 7 mangoes into 4 different partitions so that 4 people can have their own portion of respective partition: As all the mangoes are considered to be identical, we divide by to deduct the duplicate entries. Similarly, we divide the above expression again by because all people are considered to be identical too.The final expression we get is : The above expression is even-actually equal to the binomial coefficient: Example: Input : m = 3, n = 2 Output : 4 There are four ways 3 + 0, 1 + 2, 2 + 1 and 0 + 3 Input : m = 13, n = 6 Output : 8568 Input : m = 11, n = 3 Output : 78 C++ Java Python3 C# PHP Javascript // C++ code for calculating number of ways// to distribute m mangoes amongst n people// where all mangoes and people are identical#include <bits/stdc++.h>using namespace std; // function used to generate binomial coefficient// time complexity O(m)int binomial_coefficient(int n, int m){ int res = 1; if (m > n - m) m = n - m; for (int i = 0; i < m; ++i) { res *= (n - i); res /= (i + 1); } return res;} // helper function for generating no of ways// to distribute m mangoes amongst n peopleint calculate_ways(int m, int n){ // not enough mangoes to be distributed if (m < n) return 0; // ways -> (n+m-1)C(n-1) int ways = binomial_coefficient(n + m - 1, n - 1); return ways;} // Driver functionint main(){ // m represents number of mangoes // n represents number of people int m = 7, n = 5; int result = calculate_ways(m, n); printf("%d\n", result); return 0;} // Java code for calculating number of ways// to distribute m mangoes amongst n people// where all mangoes and people are identical import java.util.*; class GFG { // function used to generate binomial coefficient // time complexity O(m) public static int binomial_coefficient(int n, int m) { int res = 1; if (m > n - m) m = n - m; for (int i = 0; i < m; ++i) { res *= (n - i); res /= (i + 1); } return res; } // helper function for generating no of ways // to distribute m mangoes amongst n people public static int calculate_ways(int m, int n) { // not enough mangoes to be distributed if (m < n) { return 0; } // ways -> (n+m-1)C(n-1) int ways = binomial_coefficient(n + m - 1, n - 1); return ways; } // Driver function public static void main(String[] args) { // m represents number of mangoes // n represents number of people int m = 7, n = 5; int result = calculate_ways(m, n); System.out.println(Integer.toString(result)); System.exit(0); }} # Python code for calculating number of ways# to distribute m mangoes amongst n people# where all mangoes and people are identical # function used to generate binomial coefficient# time complexity O(m)def binomial_coefficient(n, m): res = 1 if m > n - m: m = n - m for i in range(0, m): res *= (n - i) res /= (i + 1) return res # helper function for generating no of ways# to distribute m mangoes amongst n peopledef calculate_ways(m, n): # not enough mangoes to be distributed if m<n: return 0 # ways -> (n + m-1)C(n-1) ways = binomial_coefficient(n + m-1, n-1) return int(ways) # Driver functionif __name__ == '__main__': # m represents number of mangoes # n represents number of people m = 7 ;n = 5 result = calculate_ways(m, n) print(result) // C# code for calculating number// of ways to distribute m mangoes// amongst n people where all mangoes// and people are identicalusing System; class GFG{ // function used to generate// binomial coefficient// time complexity O(m)public static int binomial_coefficient(int n, int m){ int res = 1; if (m > n - m) m = n - m; for (int i = 0; i < m; ++i) { res *= (n - i); res /= (i + 1); } return res;} // helper function for generating// no of ways to distribute m// mangoes amongst n peoplepublic static int calculate_ways(int m, int n){ // not enough mangoes // to be distributed if (m < n) { return 0; } // ways -> (n+m-1)C(n-1) int ways = binomial_coefficient(n + m - 1, n - 1); return ways;} // Driver Codepublic static void Main(){ // m represents number of mangoes // n represents number of people int m = 7, n = 5; int result = calculate_ways(m, n); Console.WriteLine(result.ToString());}} // This code is contributed// by Subhadeep <?php// PHP code for calculating number// of ways to distribute m mangoes// amongst n people where all// mangoes and people are identical // function used to generate// binomial coefficient// time complexity O(m)function binomial_coefficient($n, $m){ $res = 1; if ($m > $n - $m) $m = $n - $m; for ($i = 0; $i < $m; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // Helper function for generating// no of ways to distribute m.// mangoes amongst n peoplefunction calculate_ways($m, $n){ // not enough mangoes to // be distributed if ($m < $n) return 0; // ways -> (n+m-1)C(n-1) $ways = binomial_coefficient($n + $m - 1, $n - 1); return $ways;} // Driver Code // m represents number of mangoes// n represents number of people$m = 7;$n = 5; $result = calculate_ways($m, $n);echo $result; // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript code for calculating number of ways// to distribute m mangoes amongst n people// where all mangoes and people are identical // function used to generate binomial coefficient// time complexity O(m)function binomial_coefficient(n, m){ let res = 1; if (m > n - m) m = n - m; for (let i = 0; i < m; ++i) { res *= (n - i); res /= (i + 1); } return res;} // helper function for generating no of ways// to distribute m mangoes amongst n peoplefunction calculate_ways(m, n){ // not enough mangoes to be distributed if (m < n) return 0; // ways -> (n+m-1)C(n-1) let ways = binomial_coefficient(n + m - 1, n - 1); return ways;} // Driver function // m represents number of mangoes // n represents number of people let m = 7, n = 5; let result = calculate_ways(m, n); document.write(result); // This code is contributed by Mayank Tyagi</script> Output: 330 Time Complexity : O(n) Auxiliary Space : O(1)Case 2: Distributing m unique mangoes amongst n identical people In this case, to calculate the number of ways to distribute m unique mangoes amongst n identical people, we just need to multiply the last expression we calculated in Case 1 by . So our final expression for this case is Proof: In case 1, initially we got the expression without removing duplicate entries. In this case, we only need to divide as all mangoes are considered to be unique in this case. So we get the expression as : Multiplying both numerator and denominator by , we get Where === Time Complexity : O(max(n, m)) Auxiliary Space : O(1)Case 3: Distributing m identical mangoes amongst n unique peopleIn this case, to calculate the number of ways to distribute m identical mangoes amongst n unique people, we just need to multiply the last expression we calculated in Case 1 by . So our final expression for this case is Proof: This Proof is pretty much similar to the proof of last case expression. In case 1, initially we got the expression without removing duplicate entries. In this case, we only need to divide as all people are considered to be unique in this case. So we get the expression as : Multiplying both numerator and denominator by , we get Where === Time Complexity : O(n) Auxiliary Space : O(1)For references on how to calculate refer here factorial of a numberCase 4: Distributing m unique mangoes amongst n unique peopleIn this case we need to multiply the expression obtained in case 1 by both and . The proofs for both of the multiplications are defined in case 2 and case 3.Hence, in this case, our final expression comes out to be Time Complexity : O(n+m) Auxiliary Space : O(1) tufan_gupta2000 Shivi_Aggarwal mayanktyagi1709 Picked Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Combinational Sum Find the K-th Permutation Sequence of first N natural numbers Count ways to reach the nth stair using step 1, 2 or 3 Print all possible strings of length k that can be formed from a set of n characters Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 52, "s": 24, "text": "\n06 May, 2021" }, { "code": null, "e": 497, "s": 52, "text": "Given m and n representing number of mangoes and number of people respectively. Task is to calculate number of ways to distribute m mangoes among n people. Considering both v...
Edge detection using Prewitt, Scharr and Sobel Operator
27 Jan, 2022 The discontinuity in the image brightness is called an edge. Edge detection is the technique used to identify the regions in the image where the brightness of the image changes sharply. This sharp change in the intensity value is observed at the local minima or local maxima in the image histogram, using the first-order derivative. The techniques used here in this article are first-order derivative techniques namely: Prewitt Operator Scharr Operator Sobel Operator The Prewitt operator was developed by Judith M. S. Prewitt. Prewitt operator is used for edge detection in an image. Prewitt operator detects both types of edges, these are: Horizontal edges or along the x-axis, Vertical Edges or along the y-axis. Wherever there is a sudden change in pixel intensities, an edge is detected by the mask. Since the edge is defined as the change in pixel intensities, it can be calculated by using differentiation. Prewitt mask is a first-order derivate mask. In the graph representation of Prewitt-mask’s result, the edge is represented by the local maxima or local minima. Both the first and second derivative masks follow these three properties: More weight means more edge detection. The opposite sign should be present in the mask. (+ and -) The Sum of the mask values must be equal to zero. Prewitt operator provides us two masks one for detecting edges in the horizontal direction and another for detecting edges in a vertical direction. Prewitt Operator [X-axis] = [ -1 0 1; -1 0 1; -1 0 1] Prewitt Operator [Y-axis] = [-1 -1 -1; 0 0 0; 1 1 1] Steps: Read the image. Convert into grayscale if it is colored. Convert into the double format. Define the mask or filter. Detect the edges along X-axis. Detect the edges along Y-axis. Combine the edges detected along the X and Y axes. Display all the images. Imtool() is the inbuilt function in Matlab. It is used to display the image. It takes 2 parameters; the first is the image variable and the second is the range of intensity values. We provide an empty list as the second argument which means the complete range of intensity has to be used while displaying the image. Example: Matlab % MATLAB code for prewitt% operator edge detectionk=imread("logo.png");k=rgb2gray(k);k1=double(k);p_msk=[-1 0 1; -1 0 1; -1 0 1];kx=conv2(k1, p_msk, 'same');ky=conv2(k1, p_msk', 'same');ked=sqrt(kx.^2 + ky.^2); % display the images.imtool(k,[]); % display the edge detection along x-axis.imtool(abs(kx), []); % display the edge detection along y-axis.imtool(abs(ky),[]); % display the full edge detection.imtool(abs(ked),[]); Output: This is a filtering method used to identify and highlight gradient edges/features using the first derivative. Performance is quite similar to the Sobel filter. Scharr Operator [X-axis] = [-3 0 3; -10 0 10; -3 0 3]; Scharr Operator [Y-axis] = [ 3 10 3; 0 0 0; -3 -10 -3]; Example: Matlab %Scharr operator -> edge detection k=imread("logo.png"); k=rgb2gray(k); k1=double(k); s_msk=[-3 0 3; -10 0 10; -3 0 3]; kx=conv2(k1, s_msk, 'same'); ky=conv2(k1, s_msk', 'same'); ked=sqrt(kx.^2 + ky.^2); %display the images. imtool(k,[]); %display the edge detection along x-axis. imtool(abs(kx), []); %display the edge detection along y-axis. imtool(abs(ky),[]); %display the full edge detection. imtool(abs(ked),[]); Output: It is named after Irwin Sobel and Gary Feldman. Like the Prewitt operator Sobel operator is also used to detect two kinds of edges in an image: Vertical direction Horizontal direction The difference between Sobel and Prewitt Operator is that in Sobel operator the coefficients of masks are adjustable according to our requirement provided they follow all properties of derivative masks. Sobel-X Operator = [-1 0 1; -2 0 2; -1 0 1] Sobel-Y Operator = [-1 -2 -1; 0 0 0; 1 2 1] Example: Matlab % MATLAB code for Sobel operator% edge detection k=imread("logo.png"); k=rgb2gray(k); k1=double(k); s_msk=[-1 0 1; -2 0 2; -1 0 1]; kx=conv2(k1, s_msk, 'same'); ky=conv2(k1, s_msk', 'same'); ked=sqrt(kx.^2 + ky.^2); %display the images. imtool(k,[]); %display the edge detection along x-axis. imtool(abs(kx), []); %display the edge detection along y-axis. imtool(abs(ky),[]); %display the full edge detection. imtool(abs(ked),[]); Output: martinjimenez1998 MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB How to Normalize a Histogram in MATLAB? MRI Image Segmentation in MATLAB How to detect duplicate values and its indices within an array in MATLAB? Forward and Inverse Fourier Transform of an Image in MATLAB Double Integral in MATLAB Boundary Extraction of image using MATLAB Classes and Object in MATLAB
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2022" }, { "code": null, "e": 362, "s": 28, "text": "The discontinuity in the image brightness is called an edge. Edge detection is the technique used to identify the regions in the image where the brightness of the image change...
How to validate URL using regular expression in JavaScript?
23 May, 2019 Given a URL, the task is to validate it. Here we are going to declare a URL valid or Invalid by matching it with the RegExp by using JavaScript. We’re going to discuss a few methods. Example 1: This example validates the URL = ‘https://www.geeksforgeeks.org’ by using Regular Expression. <!DOCTYPE HTML><html> <head> <title> JavaScript | Regular expression to match a URL. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi; var regex = new RegExp(expression); var url = 'www.geeksforgeeks.org'; el_up.innerHTML = "URL = '" + url + "'"; function gfg_Run() { var res = ""; if (url.match(regex)) { res = "Valid URL"; } else { res = "Invalid URL"; } el_down.innerHTML = res; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example validates the URL = ‘https://www.geeksforgeeksorg'(Which is wrong) by using different Regular Expression than previous one. <!DOCTYPE HTML><html> <head> <title> JavaScript | Regular expression to match a URL. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi; var regex = new RegExp(expression); var url = 'www.geekforgeeksorg'; el_up.innerHTML = "URL = '" + url + "'"; function gfg_Run() { var res = ""; if (url.match(regex)) { res = "Valid URL"; } else { res = "Invalid URL"; } el_down.innerHTML = res; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-RegExp JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 211, "s": 28, "text": "Given a URL, the task is to validate it. Here we are going to declare a URL valid or Invalid by matching it with the RegExp by using JavaScript. We’re going to discuss a few m...
Java.util.function.IntBinaryOperator interface with Examples
18 Jul, 2019 The IntBinaryOperator interface was introduced in Java 8. It represents an operation on two int values and returns the result as an int value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods applyAsInt(): This function takes two int values, performs the required operation and returns the result as an int.public int applyAsInt(int val1, int val2) applyAsInt(): This function takes two int values, performs the required operation and returns the result as an int.public int applyAsInt(int val1, int val2) public int applyAsInt(int val1, int val2) Example to demonstrate IntBinaryOperator interface as a lambda expression . // Java program to demonstrate IntBinaryOperator import java.util.function.IntBinaryOperator; public class IntBinaryOperatorDemo { public static void main(String[] args) { // Binary operator defined to divide // factorial of two numbers IntBinaryOperator binaryOperator = (x, y) -> { int fact1 = 1; for (int i = 2; i <= x; i++) { fact1 *= i; } int fact2 = 1; for (int i = 2; i <= y; i++) { fact2 *= i; } return fact1 / fact2; }; System.out.println("5! divided by 7! = " + binaryOperator.applyAsInt(5, 7)); System.out.println("7! divided by 5! = " + binaryOperator.applyAsInt(7, 5)); }} 5! divided by 7! = 0 7! divided by 5! = 42 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/function/IntBinaryOperator.html Java - util package Java-Functional-Interfaces Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2019" }, { "code": null, "e": 347, "s": 28, "text": "The IntBinaryOperator interface was introduced in Java 8. It represents an operation on two int values and returns the result as an int value. It is a functional interface and...
numpy.moveaxis() function | Python
22 Apr, 2020 numpy.moveaxis() function move axes of an array to new positions. Other axes remain in their original order. Syntax : numpy.moveaxis(arr, source, destination)Parameters :arr : [ndarray] input array.source : [ int or sequence of int] Original positions of the axes to move. These must be unique.destination : [ int or sequence of int] Destination positions for each of the original axes. These must also be unique.Return : [ndarray] Array with moved axes. This array is a view of the input array. Code #1 : # Python program explaining# numpy.moveaxis() function # importing numpy as geek import numpy as geek arr = geek.zeros((1, 2, 3, 4)) gfg = geek.moveaxis(arr, 0, -1).shape print (gfg) Output : (2, 3, 4, 1) Code #2 : # Python program explaining# numpy.moveaxis() function # importing numpy as geek import numpy as geek arr = geek.zeros((1, 2, 3, 4)) gfg = geek.moveaxis(arr, -1, 0).shape print (gfg) Output : (4, 1, 2, 3) Python numpy-arrayManipulation 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 Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 137, "s": 28, "text": "numpy.moveaxis() function move axes of an array to new positions. Other axes remain in their original order." }, { "code": null, "e": 524, "s": 137, "text"...
How to import variables from another file in Python?
03 Mar, 2021 When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simple import <library_name>. For example, math library. If we want to use the pi variable we use import math and then math.pi. To import variables from another file, we have to import that file from the current program. This will provide access to all the methods and variables available in that file. We can use any Python source file as a module by executing an import statement in some other Python source file. When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module. Python’s from statement lets you import specific attributes from a module. Note: For more information, refer Python Modules Different approaches to import variables from other file import <file_name> and then use <file_name>.<variable_name> to access variable from <file_name> import <variable_names> and use variables from <file_name> import * and then use variables directly. Example: Suppose we have a file named “swaps.py”. We have to import the x and y variable from this file in another file named “calval.py”. Python3 # swaps.py file from which variables to be importedx = 23y = 30 def swapVal(x, y): x,y = y,x return x, y Now create a second python file to call the variable from the above code: Python3 # calval.py file where to import variables# import swaps.py file from which variables # to be imported# swaps.py and calval.py files should be in # same directory.import swaps # Import x and y variables using # file_name.variable_name notationnew_x = swaps.xnew_y = swaps.y print("x value: ", new_x, "y value:", new_y) # Similarly, import swapVal method from swaps filex , y = swaps.swapVal(new_x,new_y) print("x value: ", x, "y value:", y) Output: x value: 23 y value: 30 x value: 30 y value: 23 Picked python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2021" }, { "code": null, "e": 501, "s": 28, "text": "When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working...
Wand polygon() function in Python
10 May, 2020 polygon() function is another drawing function introduced in wand.drawing module. We can draw complex shapes using polygon() function. It takes a list of points in polygons as argument. Stroke line will automatically close between first & last point. Syntax : wand.drawing.polygon(points) Parameters : Example #1 from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: draw.stroke_width = 2 draw.stroke_color = Color('black') draw.fill_color = Color('white') # points list for polygon points = [(25, 25), (175, 100), (25, 175)] # draw polygon using polygon() function draw.polygon(points) with Image(width = 200, height = 200, background = Color('lightgreen')) as image: draw(image) image.save(filename = "polygon.png") Output : Example #2: from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: draw.stroke_width = 2 draw.stroke_color = Color('black') draw.fill_color = Color('white') # points list for polygon points = [(50, 50), (150, 50), (175, 150), (25, 150)] # draw polygon using polygon() function draw.polygon(points) with Image(width = 200, height = 200, background = Color('lightgreen')) as image: draw(image) image.save(filename = "polygon2.png") Output : Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 279, "s": 28, "text": "polygon() function is another drawing function introduced in wand.drawing module. We can draw complex shapes using polygon() function. It takes a list of points in polygons as...
NLP | Flattening Deep Tree
26 Feb, 2019 Some of the corpora that we use are often deep trees of nested phrases. But working on such deep trees is a tedious job for training the chunker. As IOB tag parsing is not designed for nested chunks. So, in order to use these trees for chunker training, we must flatten them.Well, POS (part of Speech) are actually part of the tree structure instead of being in the word. These are used with Tree.pos() method, designed specifically for combining words with preterminal Tree labels such as part-of-speech tags. Code #1 : Class for flattening the deep tree from nltk.tree import Tree def flatten_childtrees(trees): children = [] for t in trees: if t.height() < 3: children.extend(t.pos()) elif t.height() == 3: children.append(Tree(t.label(), t.pos())) else: children.extend( flatten_childtrees()) return children def flatten_deeptree(tree): return Tree(tree.label(), flatten_childtrees()) Code #2 : Evaluating flatten_deeptree() from nltk.corpus import treebankfrom transforms import flatten_deeptree print ("Deep Tree : \n", treebank.parsed_sents()[0]) print ("\nFlattened Tree : \n", flatten_deeptree(treebank.parsed_sents()[0])) Output : Deep Tree : (S (NP-SBJ (NP (NNP Pierre) (NNP Vinken)) (,, ) (ADJP (NP (CD 61) (NNS years)) (JJ old)) (,, )) (VP (MD will) (VP (VB join) (NP (DT the) (NN board)) (PP-CLR (IN as) (NP (DT a) (JJ nonexecutive) (NN director))) (NP-TMP (NNP Nov.) (CD 29)))) (. .)) Flattened Tree : Tree('S', [Tree('NP', [('Pierre', 'NNP'), ('Vinken', 'NNP')]), (', ', ', '), Tree('NP', [('61', 'CD'), ('years', 'NNS')]), ('old', 'JJ'), (', ', ', '), ('will', 'MD'), ('join', 'VB'), Tree('NP', [('the', 'DT'), ('board', 'NN')]), ('as', 'IN'), Tree('NP', [('a', 'DT'), ('nonexecutive', 'JJ'), ('director', 'NN')]), Tree('NP-TMP', [('Nov.', 'NNP'), ('29', 'CD')]), ('.', '.')]) The result is a much flatter Tree that only includes NP phrases. Words that are not part of an NP phrase are separated How it works ? flatten_deeptree() : returns a new Tree from the given tree by calling flatten_childtrees() on each of the given tree’s children. flatten_childtrees() : Recursively drills down into the Tree until it finds child trees whose height() is equal to or less than 3. Code #3 : height() from nltk.corpus import treebankfrom transforms import flatten_deeptree from nltk.tree import Tree print ("Height : ", Tree('NNP', ['Pierre']).height()) print ("\nHeight : ", Tree( 'NP', [Tree('NNP', ['Pierre']), Tree('NNP', ['Vinken'])]). height()) Output : Height : 2 Height : 3 Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2019" }, { "code": null, "e": 539, "s": 28, "text": "Some of the corpora that we use are often deep trees of nested phrases. But working on such deep trees is a tedious job for training the chunker. As IOB tag parsing is not des...
Program to invert bits of a number Efficiently
28 Apr, 2021 Given a non-negative integer N. The task is to invert the bits of the number N and print the decimal equivalent of the number obtained after inverting the bits. Note: Leading 0’s are not being considered.Examples: Input : 11 Output : 4 (11)10 = (1011)2 After inverting the bits, we get: (0100)2 = (4)10. Input : 20 Output : 11 (20)10 = (10100)2. After inverting the bits, we get: (01011)2 = (11)10. A similar problem is already discussed in Invert actual bits of a number.In this article, an efficient approach using bitwise operators is discussed. Below is the step by step algorithm to solve the problem: Calculate the total number of bits in the given number. This can be done by calculating:X = log2NWhere N is the given number and X is the total number of bits of N.The next step is to generate a number with X bits and all bits set. That is, 11111....X-times. This can be done by calculating:Step-1: M = 1 << X Step-2: M = M | (M-1)Where M is the required X-bit number with all bits set.The final step is to calculate the bit-wise XOR of M with N, which will be our answer. Calculate the total number of bits in the given number. This can be done by calculating:X = log2NWhere N is the given number and X is the total number of bits of N. X = log2N Where N is the given number and X is the total number of bits of N. The next step is to generate a number with X bits and all bits set. That is, 11111....X-times. This can be done by calculating:Step-1: M = 1 << X Step-2: M = M | (M-1)Where M is the required X-bit number with all bits set. Step-1: M = 1 << X Step-2: M = M | (M-1) Where M is the required X-bit number with all bits set. The final step is to calculate the bit-wise XOR of M with N, which will be our answer. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to invert actual bits// of a number.#include <bits/stdc++.h> using namespace std; // Function to invert bits of a numberint invertBits(int n){ // Calculate number of bits of N-1; int x = log2(n) ; int m = 1 << x; m = m | m - 1; n = n ^ m; return n;} // Driver codeint main(){ int n = 20; cout << invertBits(n); return 0;} // Java program to invert // actual bits of a number. import java.util.*; class GFG{// Function to invert // bits of a number static int invertBits(int n) { // Calculate number of bits of N-1; int x = (int)(Math.log(n) / Math.log(2)) ; int m = 1 << x; m = m | m - 1; n = n ^ m; return n; } // Driver code public static void main(String[] args) { int n = 20; System.out.print(invertBits(n)); }} // This code is contributed by Smitha # Python3 program to invert actual# bits of a number.import math # Function to invert bits of a numberdef invertBits(n): # Calculate number of bits of N-1 x = int(math.log(n, 2)) m = 1 << x m = m | m - 1 n = n ^ m return n # Driver coden = 20 print(invertBits(n)) # This code is contributed 29AjayKumar // C# program to invert // actual bits of a number. using System; public class GFG{// Function to invert // bits of a number static int invertBits(int n) { // Calculate number of bits of N-1; int x = (int)(Math.Log(n) / Math.Log(2)) ; int m = 1 << x; m = m | m - 1; n = n ^ m; return n; } // Driver code public static void Main() { int n = 20; Console.Write(invertBits(n)); }} // This code is contributed by Subhadeep <?php// PHP program to invert actual // bits of a number. // Function to invert bits // of a numberfunction invertBits($n){ // Calculate number of // bits of N-1; $x = log($n, 2); $m = 1 << $x; $m = $m | $m - 1; $n = $n ^ $m; return $n;} // Driver code$n = 20; echo(invertBits($n)); // This code is contributed // by mits?> <script> // Javascript program to invert actual bits// of a number. // Function to invert bits of a numberfunction invertBits(n){ // Calculate number of bits of N-1; let x = parseInt(Math.log(n) / Math.log(2)) ; let m = 1 << x; m = m | m - 1; n = n ^ m; return n;} // Driver code let n = 20; document.write(invertBits(n)); </script> 11 Time Complexity: O(log2n) Auxiliary Space: O(1) ayushjauhari14 Smitha Dinesh Semwal tufan_gupta2000 Mithun Kumar 29AjayKumar subham348 Algorithms-Bit Algorithms Bitwise-XOR setBitCount Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Apr, 2021" }, { "code": null, "e": 270, "s": 54, "text": "Given a non-negative integer N. The task is to invert the bits of the number N and print the decimal equivalent of the number obtained after inverting the bits. Note: Leading...
Optional or() method in Java with examples
30 Jul, 2019 The or() method of java.util.Optional class in Java is used to get this Optional instance if any value is present. If there is no value present in this Optional instance, then this method returns an Optional instance with the value generated from the specified supplier. Syntax: public Optional<T> or(Supplier<T> supplier) Parameters: This method accepts supplier as a parameter of type T to generate an Optional instance with the value generated from the specified supplier. Return supplier: This method returns this Optional instance, if any value is present. If there is no value present in this Optional instance, then this method returns an Optional instance with the value generated from the specified supplier. Exception: This method throws NullPointerException if the supplying function is null or produces a null result. Below programs illustrate or() method: Note: As this method was added in Java 9, the programs need JDK 9 to execute. Program 1: // Java program to demonstrate// Optional.or() method import java.util.*;import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print supplier System.out.println("Optional: " + op); // or supplier System.out.println("Optional by or(() ->" + " Optional.of(100)) method: " + op.or(() -> Optional.of(100))); }} Output: Optional: Optional[9455] Optional by or(() -> Optional.of(100)) method: Optional[9455] Program 2: // Java program to demonstrate// Optional.or() method import java.util.*;import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print supplier System.out.println("Optional: " + op); try { // or supplier System.out.println("Optional by or(() ->" + " Optional.of(100)) method: " + op.or(() -> Optional.of(100))); } catch (Exception e) { System.out.println(e); } }} Output: Optional: Optional.empty Optional by or(() -> Optional.of(100)) method: Optional[100] Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#or-java.util.function.Supplier- Java - util package Java-Functions Java-Optional Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2019" }, { "code": null, "e": 299, "s": 28, "text": "The or() method of java.util.Optional class in Java is used to get this Optional instance if any value is present. If there is no value present in this Optional instance, then...
How to remove or hide X-axis labels from a Seaborn / Matplotlib plot?
To remove or hide X-axis labels from a Seaborn/Matplotlib plot, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Use sns.set_style() to set an aesthetic style for the Seaborn plot. Use sns.set_style() to set an aesthetic style for the Seaborn plot. Load an example dataset from the online repository (requires Internet). Load an example dataset from the online repository (requires Internet). To hide or remove X-axis labels, use set(xlabel=None). To hide or remove X-axis labels, use set(xlabel=None). To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt import seaborn as sns plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True sns.set_style("whitegrid") tips = sns.load_dataset("tips") ax = sns.boxplot(x="day", y="total_bill", data=tips) ax.set(xlabel=None) plt.show()
[ { "code": null, "e": 1285, "s": 1187, "text": "To remove or hide X-axis labels from a Seaborn/Matplotlib plot, we can take the following steps −" }, { "code": null, "e": 1361, "s": 1285, "text": "Set the figure size and adjust the padding between and around the subplots." }, ...
Second most repeated word in a sequence in Python
07 Jun, 2022 Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word).Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"geeks", "for", "geeks", "for", "geeks", "aaa"} Output : for This problem has existing solution please refer Second most repeated word in a sequence link. We can solve this problem quickly in Python using Counter(iterator) method. Approach is very simple – Create a dictionary using Counter(iterator) method which contains words as keys and it’s frequency as value.Now get a list of all values in dictionary and sort it in descending order. Choose second element from the sorted list because it will be the second largest.Now traverse dictionary again and print key whose value is equal to second largest element. Create a dictionary using Counter(iterator) method which contains words as keys and it’s frequency as value. Now get a list of all values in dictionary and sort it in descending order. Choose second element from the sorted list because it will be the second largest. Now traverse dictionary again and print key whose value is equal to second largest element. Python3 # Python code to print Second most repeated# word in a sequence in Pythonfrom collections import Counter def secondFrequent(input): # Convert given list into dictionary # it's output will be like {'ccc':1,'aaa':3,'bbb':2} dict = Counter(input) # Get the list of all values and sort it in ascending order value = sorted(dict.values(), reverse=True) # Pick second largest element secondLarge = value[1] # Traverse dictionary and print key whose # value is equal to second large element for (key, val) in dict.items(): if val == secondLarge: print(key) return # Driver programif __name__ == "__main__": input = ['aaa', 'bbb', 'ccc', 'bbb', 'aaa', 'aaa'] secondFrequent(input) Output: bbb Time complexity: O(nlogn) where n is the length of the input list Auxiliary space: O(n) where n is the length of the input listAlternate Implementation : Python3 # returns the second most repeated wordfrom collections import Counterclass Solution: def secFrequent(self, arr, n): all_freq = dict(Counter(arr)) store = [] for w in sorted(all_freq, key=all_freq.get): # if add key=all_freq.get will sort according to values # without key=all_freq.get will sort according to keys if w not in store: store.append(w) return store[-2] # driver code or main functionif __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input().strip()) arr = input().strip().split(" ") ob = Solution() ans = ob.secFrequent(arr,n) print(ans) contributed by Pratyush Pratap Singh bbb Time complexity: O(nlogn) Auxiliary space: O(n) Midhilesh pratyushpratapsingh11 hasani python-dict Python Strings python-dict Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jun, 2022" }, { "code": null, "e": 279, "s": 53, "text": "Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeat...
Golang Tutorial – Learn Go Programming Language
03 Feb, 2020 Golang or Go Programming Language is a statically-typed and procedural programming language having syntax similar to C language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google. But they launched it in 2009 as an open-source programming language. It provides a rich standard library, garbage collection, and dynamic-typing capability and also provides support for the environment adopting patterns alike to dynamic languages. The latest version of the Golang is 1.13.1 released on 3rd September 2019. Here, we are providing a complete tutorial of Golang with proper examples. Topics Covered: Why Golang Key Features Installing Golang Hello World! Program Identifiers and Keywords Data Types Variables Constants Operators if-else Statement for loop Loop Control Statements(break, goto, continue) Switch Statement Arrays Slices Functions Structures Packages Defer Keyword Pointers Methods Methods vs Functions Interfaces Concurrency – Goroutines Channels Select Statement The main purpose of designing Golang was to eliminate the problems of existing languages. So let us see the problems that we are facing with Python, Java, C/C++ programming languages: Python: It is easy to use but slow in compare to Golang. Java: It has very complex type system. C/C++: It has slow compilation time as well as complex type system. Also, all these languages were designed when multi-threading applications were rare, so not much effective to highly scalable, concurrent and parallel applications. Threading consumes 1MB whereas Goroutine consumes 2KB of memory, hence at the same time, we can have millions of goroutine triggered. Before we begin with the installation of Go, it is good to check if it might be already installed on your System. To check if your device is preinstalled with Golang or not, just go to the Command line(For Windows, search for cmd in the Run dialog( + R). Now run the following command: go version If Golang is already installed, it will generate a message with all the details of the Golang’s version available, otherwise, if Golang is not installed then an error will arise stating Bad command or file name Before starting with the installation process, you need to download it. For that, all versions of Go for Windows are available on golang.org. Download the Golang according to your system architecture and follow the further instructions for the installation of Golang. Step 1: After downloading, unzip the downloaded archive file. After unzipping you will get a folder named go in the current directory. Step 2: Now copy and paste the extracted folder wherever you want to install this. Here we are installing in C drive. Step 3: Now set the environment variables. Right click on My PC and select Properties. Choose the Advanced System Settings from the left side and click on Environment Variables as shown in the below screenshots. Step 4: Click on Path from the system variables and then click Edit. Then Click New and then add the Path with bin directory where you have pasted the Go folder. Here we are editing the path C:\go\bin and click Ok as shown in the below screenshots. Step 5: Now create a new user variable which tells Go command where Golang libraries are present. For that click on New on User Variables as shown in the below screenshots. Now fill the Variable name as GOROOT and Variable value is the path of your Golang folder. So here Variable Value is C:\go\. After Filling click OK. After that Click Ok on Environment Variables and your setup is completed. Now Let’s check the Golang version by using the command go version on command prompt. After completing the installation process, any IDE or text editor can be used to write Golang Codes and Run them on the IDE or the Command prompt with the use of command: go run filename.go To run a Go program you need a Go compiler. In Go compiler, first you create a program and save your program with extension .go, for example, first.go. // First Go programpackage main import "fmt" // Main functionfunc main() { fmt.Println("!... Hello World ...!")} Output: !... Hello World ...! Now we run this first.go file in the go compiler using the following command, i.e: $ go run first.go For more details about the different terms used in this program, you can visit Hello World! in Golang Identifiers are the user-defined name of the program components. In Go language, an identifier can be a variable name, function name, constant, statement labels, package name, or types. Example: // Valid identifiers: _geeks23 geeks gek23sd Geeks geeKs geeks_geeks // Invalid identifiers: 212geeks if default Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error. There are total 25 keywords present in the Go language as follows: Example: // Go program to illustrate // the use of keywords // Here package keyword is used to // include the main package// in the programpackage main // import keyword is used to // import "fmt" in your packageimport "fmt" // func is used to// create functionfunc main() { // Here, var keyword is used // to create variables // Pname, Lname, and Cname // are the valid identifiers var Pname = "GeeksforGeeks" var Lname = "Go Language" var Cname = "Keywords" fmt.Printf("Portal name: %s", Pname) fmt.Printf("\nLanguage name: %s", Lname) fmt.Printf("\nChapter name: %s", Cname) } Output: Portal name: GeeksforGeeks Language name: Go Language Chapter name: Keywords Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows: Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointers, slices, maps, functions, and channels come under this category.Interface type Basic type: Numbers, strings, and booleans come under this category. Aggregate type: Array and structs come under this category. Reference type: Pointers, slices, maps, functions, and channels come under this category. Interface type Here, we will discuss Basic Data Types in the Go language. The Basic Data Types are further categorized into three subcategories which are: NumbersBooleansStrings Numbers Booleans Strings Numbers: In Go language, numbers are divided into three sub-categories that are: Integers: In Go language, both signed and unsigned integers are available in four different sizes as shown in the below table. The signed int is represented by int and the unsigned integer is represented by uint. Floating-Point Numbers: In Go language, floating-point numbers are divided into two categories as shown in the below table: Complex Numbers: The complex numbers are divided into two parts are shown in the below table. float32 and float64 are also part of these complex numbers. The in-built function creates a complex number from its imaginary and real part and in-built imaginary and real function extract those parts. Example: // Golang program to illustrate// the use of integers, floating// and complex numberspackage main import "fmt" func main() { // Using 8-bit unsigned int var X uint8 = 225 fmt.Println(X+1, X) // Using 16-bit signed int var Y int16 = 32767 fmt.Println(Y+2, Y-2) a := 20.45 b := 34.89 var m complex128 = complex(6, 2) var n complex64 = complex(9, 2) // Subtraction of two // floating-point number c := b - a // Display the result fmt.Printf("Result is: %f\n", c) // Display the type of c variable fmt.Printf("The type of c is : %T\n", c) fmt.Println(m) fmt.Println(n) // Display the type fmt.Printf("The type of m is %T and "+ "the type of n is %T", m, n) } Output: 226 225 -32767 32765 Result is: 14.440000 The type of c is : float64 (6+2i) (9+2i) The type of m is complex128 and the type of n is complex64 Booleans and Strings: The boolean data type represents only one bit of information either true or false. The values of type boolean are not converted implicitly or explicitly to any other type.The string data type represents a sequence of Unicode code points. Or in other words, we can say a string is a sequence of immutable bytes, means once a string is created you cannot change that string. A string may contain arbitrary data, including bytes with zero value in the human-readable form. Example: // Go program to illustrate// the use of booleans and// stringspackage main import "fmt" func main() { // variables str1 := "GeeksforGeeks" str2 := "geeksForgeeks" result1 := str1 == str2 // Display the result fmt.Println(result1) // Display the type of // result1 fmt.Printf("The type of result1 is %T\n", result1) // str variable which stores strings str := "GeeksforGeeks" // Display the length of the string fmt.Printf("Length of the string is: %d", len(str)) // Display the string fmt.Printf("\nString is: %s", str) // Display the type of str variable fmt.Printf("\nType of str is: %T", str) } Output: false The type of result1 is bool Length of the string is: 13 String is: GeeksforGeeks Type of str is: string A Variable is a placeholder of the information which can be changed at runtime. And variables allow to Retrieve and Manipulate the stored information. Rules for Naming Variables: Variable names must begin with a letter or an underscore(_). And the names may contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.Geeks, geeks, _geeks23 // valid variable 123Geeks, 23geeks // invalid variable Geeks, geeks, _geeks23 // valid variable 123Geeks, 23geeks // invalid variable A variable name should not start with a digit.234geeks // illegal variable 234geeks // illegal variable The name of the variable is case sensitive.geeks and Geeks are two different variables geeks and Geeks are two different variables Keywords is not allowed to use as a variable name. There is no limit on the length of the name of the variable, but it is advisable to use an optimum length of 4 – 15 letters only. There are two ways to declare a variable in Golang as follows: 1. Using var Keyword: In Go language, variables are created using var keyword of a particular type, connected with name and provide its initial value. Syntax: var variable_name type = expression Example: // Go program to illustrate // the use of var keywordpackage main import "fmt" func main() { // Variable declared and // initialized without the // explicit typevar myvariable1 = 20 // Display the value and the// type of the variablesfmt.Printf("The value of myvariable1 is : %d\n", myvariable1) fmt.Printf("The type of myvariable1 is : %T\n", myvariable1) } Output: The value of myvariable1 is : 20 The type of myvariable1 is : int To read more about the var keyword, you can refer to the article var keyword in Golang 2. Using short variable declaration: The local variables which are declared and initialize in the functions are declared by using short variable declaration. Syntax: variable_name:= expression Note: Please don’t confuse in between := and = as := is a declaration and = is assignment. Example: // Go program to illustrate the// short variable declaration package mainimport "fmt" func main() { // Using short variable declarationmyvar1 := 39 // Display the value and type of the variablefmt.Printf("The value of myvar1 is : %d\n", myvar1)fmt.Printf("The type of myvar1 is : %T\n", myvar1) } Output: The value of myvar1 is : 39 The type of myvar1 is : int To read more about the short variable declaration keyword, you can refer to the article Short Variable Declaration Operator(:=) in Golang As the name constants suggest means fixed, in programming languages also it is same i.e., once the value of constant is defined it cannot be modified further. There can be any basic data types of constant like an integer constant, a floating constant, a character constant, or a string literal. How to declare?Constant are declared like variables but in using a const keyword as a prefix to declare constant with a specific type. It cannot be declare using := syntax. Example: // Golang program to illustrate // the constantspackage main import "fmt" const PI = 3.14 func main() { const GFG = "GeeksforGeeks" fmt.Println("Hello", GFG) fmt.Println("Happy", PI, "Day") const Correct = true fmt.Println("Go rules?", Correct)} Output: Hello GeeksforGeeks Happy 3.14 Day Go rules? true To read more about Constants in Golang, you can refer to the article Constants in Golang. Operators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In Go language, operators Can be categorized based upon their different functionality: Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators Example: // Golang program to illustrate// the use of operatorspackage main import "fmt" func main() { p := 23 q := 60 // Arithmetic Operator - Addition result1 := p + q fmt.Printf("Result of p + q = %d\n", result1) // Relational Operators - ‘=='(Equal To) result2 := p == q fmt.Println(result2) // Relational Operators - ‘!='(Not Equal To) result3 := p != q fmt.Println(result3) // Logical Operators if p != q && p <= q { fmt.Println("True") } if p != q || p <= q { fmt.Println("True") } if !(p == q) { fmt.Println("True") } // Bitwise Operators - & (bitwise AND) result4 := p & q fmt.Printf("Result of p & q = %d\n", result4) // Assignment Operators - “=”(Simple Assignment) p = q fmt.Println(p) } Output: Result of p + q = 83 false true True True True Result of p & q = 20 60 Decision Making Statements Decision Making in programming is similar to decision making in real life. A piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. if : It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax:if(condition) { // Statements to execute if // condition is true } Flow Chart: Syntax: if(condition) { // Statements to execute if // condition is true } Flow Chart: if-else : if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.Syntax: if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false } Flow Chart: Syntax: if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false } Flow Chart: Nested if : Nested if statements mean an if statement inside an if statement. Yes, Golang allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.Syntax:if (condition1) { // Executes when condition1 is true if (condition2) { // Executes when condition2 is true } } Flow Chart: Syntax: if (condition1) { // Executes when condition1 is true if (condition2) { // Executes when condition2 is true } } Flow Chart: if-else-if Ladder : Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.Important Points:if statement can have zero or one else’s and it must come after any else if’s.if statement can have zero to many else if’s and it must come before the else.None of the remaining else if’s or else’s will be tested if an else if succeeds,Syntax:if(condition_1) { // this block will execute // when condition_1 is true } else if(condition_2) { // this block will execute // when condition2 is true } . . . else { // this block will execute when none // of the condition is true } Flow Chart: Important Points: if statement can have zero or one else’s and it must come after any else if’s. if statement can have zero to many else if’s and it must come before the else. None of the remaining else if’s or else’s will be tested if an else if succeeds, Syntax: if(condition_1) { // this block will execute // when condition_1 is true } else if(condition_2) { // this block will execute // when condition2 is true } . . . else { // this block will execute when none // of the condition is true } Flow Chart: Example 1: To demonstrate the if and if-else statement // Golang program to illustrate// the use of if and if-else// statementpackage main import "fmt" func main() { // taking local variables var a int = 100 var b int = 175 // using if statement for // checking the condition if a%2 == 0 { // print the following if // condition evaluates to true fmt.Printf("Even Number\n") } if b%2 == 0 { fmt.Printf("Even Number") } else { fmt.Printf("Odd Number") }} Output: Even Number Odd Number Example 2: To demonstrate the Nested-if and if-else-if ladder statement // Golang program to illustrate// the use of nested if and// if-else-if ladder statement// statementpackage main import "fmt" func main() { // taking two local variable var v1 int = 400 var v2 int = 700 // ----- Nested if Statement ------- // using if statement if v1 == 400 { // if condition is true then // check the following if v2 == 700 { // if condition is true // then display the following fmt.Printf("Value of v1 is 400 and v2 is 700\n") } } // ----------- if-else-if ladder // checking the condition if v1 == 100 { // if condition is true then // display the following */ fmt.Printf("Value of v1 is 100\n") } else if v1 == 200 { fmt.Printf("Value of a is 20\n") } else if v1 == 300 { fmt.Printf("Value of a is 300\n") } else { // if none of the conditions is true fmt.Printf("None of the values is matching\n") } } Output: Value of v1 is 400 and v2 is 700 None of the values is matching for loop Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. A simple for loop is similar that we use in other programming languages like C, C++, Java, C#, etc.Syntax: for initialization; condition; post{ // statements.... } Here, The initialization statement is optional and executes before for loop starts. The initialization statement is always in a simple statement like variable declarations, increment or assignment statements, or function calls. The condition statement holds a boolean expression, which is evaluated at the starting of each iteration of the loop. If the value of the conditional statement is true, then the loop executes. The post statement is executed after the body of the for-loop. After the post statement, the condition statement evaluates again if the value of the conditional statement is false, then the loop ends. Example: // Go program to illustrate the // use of simple for loop package main import "fmt" // Main functionfunc main() { // for loop // This loop starts when i = 0 // executes till i<4 condition is true // post statement is i++ for i := 0; i < 4; i++{ fmt.Printf("GeeksforGeeks\n") } } Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks Note: This for loop can be used as Infinite loop and while loop. To read more about for loop you can refer to the article Loops in Golang. Loop control statements in the Go language are used to change the execution of the program. When the execution of the given loop left its scope, then the objects that are created within the scope are also demolished. The Go language supports 3 types of loop control statements: breakgotocontinue break goto continue The break statement is used to terminate the loop or statement in which it presents. After that, the control will pass to the statements that present after the break statement, if available. If the break statement present in the nested loop, then it terminates only those loops which contains break statement. Flow Chart: Example: // Go program to illustrate // the use of break statementpackage main import "fmt" // Main functionfunc main() { for i:=0; i<5; i++{ fmt.Println(i) // For loop breaks when the value of i = 3 if i == 3{ break; } } } Output: 0 1 2 3 This statement is used to transfer control to the labeled statement in the program. The label is the valid identifier and placed just before the statement from where the control is transferred. Generally, goto statement is not used by the programmers because it is difficult to trace the control flow of the program. Flow Chart: Example: // Go program to illustrate // the use of goto statementpackage main import "fmt" func main() { var x int = 0 // for loop work as a while loop Lable1: for x < 8 { if x == 5 { // using goto statement x = x + 1; goto Lable1 } fmt.Printf("value is: %d\n", x); x++; } } Output: value is: 0 value is: 1 value is: 2 value is: 3 value is: 4 value is: 6 value is: 7 This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. It skips its following statements and continues with the next iteration of the loop. Flow Chart: Example: // Go program to illustrate // the use of continue statementpackage main import "fmt" func main() { var x int = 0 // for loop work as a while loop for x < 8 { if x == 5 { // skip two iterations x = x + 2; continue; } fmt.Printf("value is: %d\n", x); x++; } } Output: value is: 0 value is: 1 value is: 2 value is: 3 value is: 4 value is: 7 A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value(also called case) of the expression. Even we can add multiple values in the case statement by using a comma. Syntax: switch expression { case value_1: statement......1 case value_2: statement......2 case value_n: statement......n default: statement......default } Example: // Go program to illustrate the // concept of switch statement package main import "fmt" func main() { var value string = "five" // Switch statement without default statement // Multiple values in case statement switch value { case "one": fmt.Println("C#") case "two", "three": fmt.Println("Go") case "four", "five", "six": fmt.Println("Golang") } } Output: Golang To read more about switch statement you can refer to the article Switch Statement in Golang An array is a fixed-length sequence that is used to store homogeneous elements in the memory. Due to their fixed length array are not much popular like Slice in Go language. In an array, you are allowed to store zero or more than zero elements in it. The elements of the array are indexed by using the [] index operator with their zero-based position, means the index of the first element is array[0] and the index of the last element is array[len(array)-1]. There are two ways to create an array in Golang as follows: 1. Using var keyword: In Go language, an array is created using the var keyword of a particular type with name, size, and elements. Syntax: Var array_name[length]Type or var array_name[length]Typle{item1, item2, item3, ...itemN} In Go language, arrays are mutable, so that you can use array[index] syntax to the left-hand side of the assignment to set the elements of the array at the given index. Var array_name[index] = element 2. Using shorthand declaration: In Go language, arrays can also declare using the shorthand declaration. It is more flexible than the above declaration. Syntax: array_name:= [length]Type{item1, item2, item3, ...itemN} Example: // Golang program to illustrate the arrayspackage main import "fmt" func main() { // Creating an array of string type // Using var keyword var myarr [2]string // Elements are assigned using index myarr[0] = "GFG" myarr[1] = "GeeksforGeeks" // Accessing the elements of the array // Using index value fmt.Println("Elements of Array:") fmt.Println("Element 1: ", myarr[0]) fmt.Println("Element 2: ", myarr[1]) // Shorthand declaration of array arr := [4]string{"geek", "gfg", "Geeks1231", "GeeksforGeeks"} // Accessing the elements of // the array Using for loop fmt.Println("\nElements of the array:") for i := 0; i < 3; i++ { fmt.Println(arr[i]) } } Output: Elements of Array: Element 1: GFG Element 2: GeeksforGeeks Elements of the array: geek gfg Geeks1231 To read more about arrays, you can refer to the article Arrays in Golang Slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. Internally, slice and an array are connected, a slice is a reference to an underlying array. It is allowed to store duplicate elements in the slice. The first index position in a slice is always 0 and the last one will be (length of slice – 1). Syntax for Declaration: []T or []T{} or []T{value1, value2, value3, ...value n} Here, T is the type of the elements. For example: var my_slice[]int Pointer, Length, and Capacity are the main three components of the slice. Example: // Golang program to illustrate// the working of the slicepackage main import "fmt" func main() { // Creating an array arr := [7]string{"This", "is", "the", "tutorial", "of", "Go", "language"} // Display array fmt.Println("Array:", arr) // Creating a slice myslice := arr[1:6] // Display slice fmt.Println("Slice:", myslice) // Display length of the slice fmt.Printf("Length of the slice: %d", len(myslice)) // Display the capacity of the slice fmt.Printf("\nCapacity of the slice: %d", cap(myslice))} Output: Array: [This is the tutorial of Go language] Slice: [is the tutorial of Go] Length of the slice: 5 Capacity of the slice: 6 Explanation: In the above example, we create a slice from the given array. Here the pointer of the slice pointed to index 1 because the lower bound of the slice is set to one so it starts accessing elements from index 1. The length of the slice is 5, which means the total number of elements present in the slice is 5 and the capacity of the slice 6 means it can store a maximum of 6 elements in it. To read more about slices you can refer to the article Slices in Golang Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything. Syntax: func function_name(Parameter-list)(Return_type){ // function body..... } You can return multiple values from the function. Also, the parameters and returns types are optional. Example: // Go program to illustrate the// use of functionpackage mainimport "fmt" // area() is used to find the // area of the rectangle// area() function two parameters,// i.e, length and widthfunc area(length, width int)int{ Ar := length* width return Ar} // Main functionfunc main() { // Display the area of the rectangle // with method calling fmt.Printf("Area of rectangle is : %d", area(12, 10))} Output: Area of rectangle is : 120 To read more about the Functions you can refer to the article Functions in Golang. It is a user-defined type that allows to group/combine items of possibly different types into a single type. It can be termed as a lightweight class that does not support inheritance but supports composition. First, you need to declare a structure type using the below syntax: type struct_name struct { variable_1 type_of_variable_1 variable_2 type_of_variable_2 variable_n type_of_variable_3 } Second, you have to create variables of that type to store values. var variable_name struct_name Example: // Golang program to show how to// declare and define the struct package main import "fmt" // Defining a struct typetype Address struct { Name string city string Pincode int} func main() { // Declaring a variable of a `struct` type // All the struct fields are initialized // with their zero value var a Address fmt.Println(a) // Declaring and initializing a // struct using a struct literal a1 := Address{"Akshay", "Dehradun", 3623572} fmt.Println("Address1: ", a1) // Naming fields while // initializing a struct a2 := Address{Name: "Anikaa", city: "Ballia", Pincode: 277001} fmt.Println("Address2: ", a2) // Uninitialized fields are set to // their corresponding zero-value a3 := Address{Name: "Delhi"} fmt.Println("Address3: ", a3)} Output: { 0} Address1: {Akshay Dehradun 3623572} Address2: {Anikaa Ballia 277001} Address3: {Delhi 0} To access individual fields of a struct you have to use dot (.) operator. To read more about structures you can refer to the article Structure in Golang. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. In Go language, every package is defined with a different name and that name is close to their functionality like “strings” package and it contains methods and functions that only related to strings. Example: // Go program to illustrate the// concept of packages// Package declarationpackage main // Importing multiple packagesimport ( "bytes" "fmt" "sort") func main() { // Creating and initializing slice // Using shorthand declaration slice_1 := []byte{'*', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '^', '^'} slice_2 := []string{"Gee", "ks", "for", "Gee", "ks"} // Displaying slices fmt.Println("Original Slice:") fmt.Printf("Slice 1 : %s", slice_1) fmt.Println("\nSlice 2: ", slice_2) // Trimming specified leading // and trailing Unicode points // from the given slice of bytes // Using Trim function res := bytes.Trim(slice_1, "*^") fmt.Printf("\nNew Slice : %s", res) // Sorting slice 2 // Using Strings function sort.Strings(slice_2) fmt.Println("\nSorted slice:", slice_2)} Output: Original Slice: Slice 1 : *GeeksforGeeks^^ Slice 2: [Gee ks for Gee ks] New Slice : GeeksforGeeks Sorted slice: [Gee Gee for ks ks] It is keyword which is delay the execution of the function or method or an anonymous method until the nearby functions returns. Or in other words, defer function or method call arguments evaluate instantly, but they execute until the nearby functions returns. Example: // Go program to illustrate the// concept of the defer statementpackage main import "fmt" // Functionsfunc mul(a1, a2 int) int { res := a1 * a2 fmt.Println("Result: ", res) return 0} func show() { fmt.Println("Hello!, GeeksforGeeks")} // Main functionfunc main() { // Calling mul() function // Here mul function behaves // like a normal function mul(23, 45) // Calling mul()function // Using defer keyword // Here the mul() function // is defer function defer mul(23, 56) // Calling show() function show()} Output: Result: 1035 Hello!, GeeksforGeeks Result: 1288 Explanation: In the above example we have two functions named as mul() and show() function. Where show() function call normally in the main() function, but we call mul() function in two different ways: First, we call mul function like the normal function, i.e, mul(23, 45) and executes when the function called(Output: Result : 1035 ). Second, we call mul() function as a defer function using defer keyword, i.e, defer mul(23, 56) and it executes(Output: Result: 1288 ) when all the surrounding methods return. To read more about this you can refer to the keyword Defer Keyword in Golang. It is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. Before we start there are two important operators which we will use in pointers i.e. * Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address. & operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer. Declaring a pointer: var pointer_name *Data_Type Example: Below is a pointer of type string which can store only the memory addresses of string variables. var s *string Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example: // normal variable declaration var a = 45 // Initialization of pointer s with // memory address of variable a var s *int = &a Example: // Golang program to demonstrate the declaration// and initialization of pointerspackage main import "fmt" func main(){ // taking a normal variable var x int = 5748 // declaration of pointer var p* int // initialization of pointer p = &x // displaying the result fmt.Println("Value stored in x = ", x) fmt.Println("Address of x = ", &x) fmt.Println("Value stored in variable p = ", p)} Output: Value stored in x = 5748 Address of x = 0x414020 Value stored in variable p = 0x414020 To read more about the pointers you can refer to the article Pointers in Golang. Methods are not functions in Golang. The method contains a receiver argument in it that is used to access the properties of the receiver. The receiver can be of struct type or non-struct type. When you create a method in your code the receiver and receiver type must present in the same package. And you are not allowed to create a method in which the receiver type is already defined in another package including inbuilt type like int, string, etc. If you try to do so, then the compiler will give an error. Syntax: func(reciver_name Type) method_name(parameter_list)(return_type){ // Code } Here, the receiver can be accessed within the method. Example: // Go program to illustrate the// methodpackage main import "fmt" // Author structuretype author struct { name string branch string particles int salary int} // Method with a receiver// of author typefunc (a author) show() { fmt.Println("Author's Name: ", a.name) fmt.Println("Branch Name: ", a.branch) fmt.Println("Published articles: ", a.particles) fmt.Println("Salary: ", a.salary)} // Main functionfunc main() { // Initializing the values // of the author structure res := author{ name: "Sona", branch: "CSE", particles: 203, salary: 34000, } // Calling the method res.show()} Output: Author's Name: Sona Branch Name: CSE Published articles: 203 Salary: 34000 Methods vs Functions To read more about methods you can refer to the article Methods in Golang. Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Syntax: type interface_name interface{ // Method signatures } Example: // Golang program illustrates how// to implement an interfacepackage main import "fmt" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} type myvalue struct { radius float64 height float64} // Implementing methods of// the tank interfacefunc (m myvalue) Tarea() float64 { return 2*m.radius*m.height + 2*3.14*m.radius*m.radius} func (m myvalue) Volume() float64 { return 3.14 * m.radius * m.radius * m.height} // Main Methodfunc main() { // Accessing elements of // the tank interface var t tank t = myvalue{10, 14} fmt.Println("Area of tank :", t.Tarea()) fmt.Println("Volume of tank:", t.Volume())} Output: Area of tank : 908 Volume of tank: 4396 To read more, please refer to the article Interfaces in Golang. A Goroutine is a function or method which executes independently and simultaneously in connection with any other Goroutines present in your program. Or in other words, every concurrently executing activity in Go language is known as a Goroutines. You can consider a Goroutine like a light weighted thread. Every program contains at least a single Goroutine and that Goroutine is known as the main Goroutine. All the Goroutines are working under the main Goroutines if the main Goroutine terminated, then all the goroutine present in the program also terminated. Goroutine always works in the background. You can create your own Goroutine simply by using go keyword as a prefixing to the function or method call as shown in the below syntax: Syntax: func name(){ // statements } // using go keyword as the // prefix of your function call go name() Example: // Go program to illustrate// the concept of Goroutinepackage main import "fmt" func display(str string) { for w := 0; w < 6; w++ { fmt.Println(str) }} func main() { // Calling Goroutine go display("Welcome") // Calling normal function display("GeeksforGeeks")} Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks In the above example, we simply create a display() function and then call this function in two different ways first one is a Goroutine, i.e. go display(“Welcome”) and another one is a normal function, i.e. display(“GeeksforGeeks”). But there is a problem, it only displays the result of the normal function that does not display the result of Goroutine because when a new Goroutine executed, the Goroutine call return immediately. The control does not wait for Goroutine to complete their execution just like normal function they always move forward to the next line after the Goroutine call and ignores the value returned by the Goroutine. So, to executes a Goroutine properly, we made some changes in our program as shown in the below code: Modified Example: // Go program to illustrate the concept of Goroutinepackage main import ( "fmt" "time") func display(str string) { for w := 0; w < 6; w++ { time.Sleep(1 * time.Second) fmt.Println(str) }} func main() { // Calling Goroutine go display("Welcome") // Calling normal function display("GeeksforGeeks")} Output: Welcome GeeksforGeeks GeeksforGeeks Welcome Welcome GeeksforGeeks GeeksforGeeks Welcome Welcome GeeksforGeeks GeeksforGeeks We added the Sleep() method in our program which makes the main Goroutine sleeps for 1 second in between 1-second the new Goroutine executes, displays “welcome” on the screen, and then terminate after 1-second main Goroutine re-schedule and perform its operation. This process continues until the value of the z<6 after that the main Goroutine terminates. Here, both Goroutine and the normal function work concurrently. To read more about the Goroutines you can refer to the article Goroutines A channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the goroutines can send or receive data through the same channel as shown in the below image: In Go language, a channel is created using chan keyword and it can only transfer data of the same type, different types of data are not allowed to transport from the same channel. Syntax: var Channel_name chan Type You can also create a channel using make() function using a shorthand declaration. Syntax: channel_name:= make(chan Type) The below statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator. Mychannel <- element The below statement indicates that the element receives data from the channel(Mychannel). element := <-Mychannel If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as: <-Mychannel Example: // Go program to illustrate send// and receive operationpackage main import "fmt" func myfunc(ch chan int) { fmt.Println(234 + <-ch)}func main() { fmt.Println("start Main method") // Creating a channel ch := make(chan int) go myfunc(ch) ch <- 23 fmt.Println("End Main method")} Output: start Main method 257 End Main method To read more, you can refer to the article Channels in Golang. The select statement is just like switch statement, but in the select statement, case statement refers to communication, i.e. sent or receive operation on the channel. Syntax: select{ case SendOrReceive1: // Statement case SendOrReceive2: // Statement case SendOrReceive3: // Statement ....... default: // Statement Example: // Go program to illustrate the// concept of select statementpackage main import("fmt" "time") // function 1 func portal1(channel1 chan string) { time.Sleep(3*time.Second) channel1 <- "Welcome to channel 1" } // function 2 func portal2(channel2 chan string) { time.Sleep(9*time.Second) channel2 <- "Welcome to channel 2" } // main functionfunc main(){ // Creating channels R1:= make(chan string) R2:= make(chan string) // calling function 1 and // function 2 in goroutine go portal1(R1) go portal2(R2) select{ // case 1 for portal 1 case op1:= <- R1: fmt.Println(op1) // case 2 for portal 2 case op2:= <- R2: fmt.Println(op2) } } Output: Welcome to channel 1 Explanation: In the above program, portal 1 sleep for 3 seconds and portal 2 sleep for 9 seconds after their sleep time over they will ready to proceed. Now, select statement waits till their sleep time, when the portal 2 wakes up, it selects case 2 and prints “Welcome to channel 1”. If the portal 1 wakes up before portal 2 then the output is “welcome to channel 2”. Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Feb, 2020" }, { "code": null, "e": 663, "s": 52, "text": "Golang or Go Programming Language is a statically-typed and procedural programming language having syntax similar to C language. It was developed in 2007 by Robert Griesemer,...
Python VLC Instance – Setting Loop on the media
29 Aug, 2020 In this article we will see how we can set loop on the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. Setting loop means that media will get replayed everytime. In order to do this we will use vlm_set_loop method with the Instance object Syntax : instance.vlm_set_loop(name, True) Argument : It takes media name and bool as argument Return : It returns 0 on success, -1 on error Below is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a media player objectmedia_player = player.media_list_player_new() # creating a new mediamedia = player.media_new("death_note.mkv") # adding media to media listmedia_list.add_media(media) # setting media list to the mediaplayermedia_player.set_media_list(media_list) # setting loopplayer.vlm_set_loop("death_note", True) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Another exampleBelow is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a media player objectmedia_player = player.media_list_player_new() # creating a new mediamedia = player.media_new("1.mp4") # adding media to media listmedia_list.add_media(media) # setting media list to the mediaplayermedia_player.set_media_list(media_list) # setting loopplayer.vlm_set_loop("1", True) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Python vlc-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 579, "s": 28, "text": "In this article we will see how we can set loop on the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross...
Python Program that Extract words starting with Vowel From A list
11 Oct, 2020 Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u). Input : test_list = [“all”, “love”, “get”, “educated”, “by”, “gfg”] Output : [‘all’, ‘educated’] Explanation : a, e are vowels, hence words extracted.Input : test_list = [“all”, “love”, “get”, “educated”, “by”, “agfg”] Output : [‘all’, ‘educated’, ‘agfg’] Explanation : a, e, a are vowels, hence words extracted. Method 1 : Using startswith() and loop In this, we check for each word, and check if it starts with a vowel using startswith() on the first alphabet of every word. The iteration part is done using loop. Python3 # initializing listtest_list = ["all", "love", "and", "get", "educated", "by", "gfg"] # printing original listprint("The original list is : " + str(test_list)) res = []vow = "aeiou"for sub in test_list: flag = False # checking for begin char for ele in vow: if sub.startswith(ele): flag = True break if flag: res.append(sub) # printing result print("The extracted words : " + str(res)) Output: The original list is : [‘all’, ‘love’, ‘and’, ‘get’, ‘educated’, ‘by’, ‘gfg’]The extracted words : [‘all’, ‘and’, ‘educated’] Method 2 : Using any(), startswith() and loop In this, we check for vowels using any(), and rest all the functionality is similar to the above method. Python3 # initializing listtest_list = ["all", "love", "and", "get", "educated", "by", "gfg"] # printing original listprint("The original list is : " + str(test_list)) res = []vow = "aeiou"for sub in test_list: # check for vowel beginning flag = any(sub.startswith(ele) for ele in vow) if flag: res.append(sub) # printing result print("The extracted words : " + str(res)) Output: The original list is : [‘all’, ‘love’, ‘and’, ‘get’, ‘educated’, ‘by’, ‘gfg’]The extracted words : [‘all’, ‘and’, ‘educated’] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Oct, 2020" }, { "code": null, "e": 174, "s": 53, "text": "Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u)." }, { "code": null, "e": 488, "s": 17...
How to use Skeleton Component in ReactJS ?
08 Apr, 2021 A Skeleton Component is used whenever the data is not loaded, the placeholder preview is to be shown to the user. This component displays a placeholder preview of our content. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use Skeleton Component. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui module using the following command: npm install @material-ui/core npm install @material-ui/lab Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import Skeleton from "@material-ui/lab/Skeleton"; export default function App() { return ( <div style={{ display: "block", padding: 30 }}> <h4>How to use Skeleton Component in ReactJS?</h4> TEXT VARIANT: <Skeleton variant="text" width={200} /> <br /> RECTANGULAR VARIANT: <Skeleton variant="rect" width={110} height={220} />{" "} <br /> CIRCLE VARIANT: <Skeleton variant="circle" width={50} height={50} />{" "} <br /> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://material-ui.com/components/skeleton/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2021" }, { "code": null, "e": 369, "s": 28, "text": "A Skeleton Component is used whenever the data is not loaded, the placeholder preview is to be shown to the user. This component displays a placeholder preview of our content....
Top 50 Computer Networking Interview questions and answers
08 Sep, 2021 1. Name two technologies by which you would connect two offices in remote locations. Two technologies by which would connect two offices in remote locations are VPN and Cloud computing. 2. What is internetworking? Internetworking is a combination of two words, inter and networking which implies an association between totally different nodes or segments. This connection area unit is established through intercessor devices akin to routers or gateway. The first term for associate degree internetwork was interconnected. This interconnection is often among or between public, private, commercial, industrial, or governmental networks. Thus, associate degree internetwork could be an assortment of individual networks, connected by intermediate networking devices, that function as one giant network. Internetworking refers to the trade, products, and procedures that meet the challenge of making and administering internet works. 3. Name of the software layers or User support layer in OSI model. Application layer Presentation layer Session layer 4. Name of the hardware layers or network support layer in OSI model. Network layer Datalink layer Physical layer 5. Define HTTPS protocol? The full form of HTTPS is Hypertext transfer protocol secure. It is an advanced version of the HTTP protocol. Its port number is 443 by default. It uses SSL/TLS protocol for providingsecurity. 6. Name some services provided by the application layer in the Internet model? Some services provided by the application layer in the Internet model are as follows: Mail services Directory services File transfer Access management Network virtual terminal 7. In which OSI layer is the header and trailer added? At Data link layer trailer is added and at OSI model layer 6,5,4,3 added header. 8. What happens in the OSL model, as a data packet moves from the lower to upper layers? In the OSL model, as a data packet moves from the lower to upper layers, headers get removed. 9. What happens in the OSL model, as a data packet moves from the upper to lower layers? In the OSL model, as a data packet moves from the lower to upper layers, headers are added. This header contains useful information. 10. What is zone-based firewall? A Zone-based firewall is an advanced method of the stateful firewall. In a stateful firewall, a stateful database is maintained in which source IP address, destination IP address, source port number, destination port number are recorded. Due to this, only the replies are allowed i.e if the traffic is Generated from inside the network then only the replies (of inside network traffic) coming from outside the network is allowed. Cisco IOS router can be made firewall through two methods: By using CBAC: create an access list and apply it to the interfaces keeping in mind what traffic should be allowed or denied and in what direction. This has an extra overhead for the administrator.Using a Zone-based firewall. By using CBAC: create an access list and apply it to the interfaces keeping in mind what traffic should be allowed or denied and in what direction. This has an extra overhead for the administrator. Using a Zone-based firewall. For more details please refer Zone-based firewall article. 11. What is a server farm? A server farm is a set of many servers interconnected together and housed within the same physical facility. A server farm provides the combined computing power of many servers by simultaneously executing one or more applications or services. A server farm is generally a part of an enterprise data center or a component of a supercomputer. A server farm is also known as a server cluster or computer ranch. 12. Name the three means of user authentication. There is biometrics (e.g. a thumbprint, iris scan), a token, or a password. There is also two-level authentication, which employs two of those methods. 13. What is Confidentiality, Integrity & Availability? Confidentiality – means information is not disclosed to unauthorized individuals, entities, and processes. For example, if we say I have a password for my Gmail account but someone saw while I was doing a login into Gmail account. In that case, my password has been compromised and Confidentiality has been breached. Integrity – means maintaining accuracy and completeness of data. This means data cannot be edited in an unauthorized way. For example, if an employee leaves an organization then in that case data for that employee in all departments like accounts, should be updated to reflect status to JOB LEFT so that data is complete and accurate and in addition, this is only authorized person should be allowed to edit employee data. Availability – means information must be available when needed. For example, if one needs to access information of a particular employee to check whether an employee has outstood the number of leaves, in that case, it requires collaboration from different organizational teams like network operations, development operations, incident response, and policy/change management.Denial of service attack is one of the factors that can hamper the availability of information. 14. What is VPN? VPN stands for the virtual private network. A virtual private network (VPN) is a technology that creates a safe and encrypted connection over a less secure network, such as the internet. A Virtual Private Network is a way to extend a private network using a public network such as the internet. The name only suggests that it is a Virtual “private network” i.e. user can be part of a local network sitting at a remote location. It makes use of tunneling protocols to establish a secure connection. For more details please refer VPN article 15. What is Symmetric and Asymmetric Encryption? Symmetric Key Encryption:Encryption is a process to change the form of any message in order to protect it from reading by anyone. In Symmetric-key encryption the message is encrypted by using a key and the same key is used to decrypt the message which makes it easy to use but less secure. It also requires a safe method to transfer the key from one party to another. Asymmetric Key Encryption:Asymmetric Key Encryption is based on public and private key encryption techniques. It uses two different keys to encrypt and decrypt the message. It is more secure than the symmetric key encryption technique but is much slower. For more details please refer difference between symmetric and asymmetric encryption articles. 16. At what layer IPsec works? An IPsec works on layer 3 of the OSI model. 17. What is a Tunnel mode? This is a mode of data exchange wherein two communicating computers do not use IPSec themselves. Instead, the gateway that is connecting their LANs to the transit network creates a virtual tunnel that uses the IPSec protocol to secure all communication that passes through it. Tunnel mode is most commonly used between gateways, or at an end-station to a gateway, the gateway acting as a proxy for the hosts behind it. Tunnel mode is most commonly used to encrypt traffic between secure IPSec gateways, such as between the Cisco router and PIX Firewall 18. Define Digital Signatures? As the name sounds are the new alternative to sign a document digitally. It ensures that the message is sent to the intended use without any tampering by any third party (attacker). In simple words, digital signatures are used to verify the authenticity of the message sent electronically. or we can say that – A digital signature is a mathematical technique used to validate the authenticity and integrity of a message, software, or digital document. 19. What is Authorization? Authorization provides capabilities to enforce policies on network resources after the user has gained access to the network resources through authentication. After the authentication is successful, authorization can be used to determine what resources is the user allowed to access and the operations that can be performed. 20. What is the difference between IPS and a firewall? The intrusion Prevention System is also known as Intrusion Detection and Prevention System. It is a network security application that monitors network or system activities for malicious activity. The major functions of intrusion prevention systems are to identify malicious activity, collect information about this activity, report it and attempt to block or stop it. Intrusion prevention systems are contemplated as augmentation of Intrusion Detection Systems (IDS) because both IPS and IDS operate network traffic and system activities for malicious activity. IPS typically records information related to observed events, notifies security administrators of important observed events, and produces reports. Many IPS can also respond to a detected threat by attempting to prevent it from succeeding. They use various response techniques, which involve the IPS stopping the attack itself, changing the security environment, or changing the attack’s content. A firewall is a network security device, either hardware or software-based, which monitors all incoming and outgoing traffic, and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. 21.What is IP Spoofing? IP Spoofing is essentially a technique used by hackers to gain unauthorized access to Computers. Concepts of IP Spoofing were initially discussed in academic circles as early as 1980. IP Spoofing types of attacks had been known to Security experts on the theoretical level. It was primarily theoretical until Robert Morris discovered a security weakness in the TCP protocol known as sequence prediction. Occasionally IP spoofing is done to mask the origins of a Dos attack. In fact, Dos attacks often mask the actual IP addresses from where the attack has originated from. 22. What is the meaning of threat, vulnerability, and risk? Threats are anything that can exploit a vulnerability accidentally or intentionally and destroy or damage an asset. An asset can be anything people, property, or information. The asset is what we are trying to protect and a threat is what we are trying to protect against. Vulnerability means a gap or weakness in our protection efforts. Risk is nothing but an intersection of assets, threats, and vulnerability. A+T+V = R 23. What is the main purpose of a DNS server? DNS stands for Domain Name Server. It translates Internet domain and hostnames to IP addresses and vice versa. DNS technology allows typing names into your Web browsers and our computer to automatically find that address on the Internet. A key element of the DNS is a worldwide collection of DNS servers. It has the responsibility of assigning domain names and mapping those names to Internet resources by designating an authoritative name server for each domain. The Internet maintains two main namespaces like Domain Name hierarchy and Internet protocol addresses space. 24. What is the protocol and port no of DNS? Protocol – TCP/UDP Port number- 53 25. What is the position of the transmission media in the OSI model? In the OSI model, transmission media supports layer-1(Physical layer). 26. What is the importance of twisting in the twisted-pair cable? The twisted-pair cable consists of two insulated copper wires twisted together. The twisting is important for minimizing electromagnetic radiation and external interference. 27. What kind of error is undetectable by the checksum? In checksum, multiple bit errors can not be undetectable. 28. Which multiplexing technique is used in the Fiber-optic links? The wavelength division multiplexing is commonly used in fiber optic links. 29. What are the Advantages of Fiber Optics? Bandwidth is above copper cables Less power loss and allows data transmission for extended distances The optical cable is resistant to electromagnetic interference Fiber cable is sized 4.5 times which is best than copper wires As the cable is lighter, thinner, in order that they use less area as compared to copper wires Installation is extremely easy thanks to less weight. Optical fiber cable is extremely hard to tap because they don’t produce electromagnetic energy. These optical fiber cables are very secure for transmitting data. This cable opposes most acidic elements that hit copper wired also are flexible in nature. Optical fiber cables are often made cheaper than equivalent lengths of copper wire. Light has the fastest speed within the universe, such a lot faster signals Fiber optic cables allow much more cable than copper twisted-pair cables. Fiber optic cables have how more bandwidth than copper twisted-pair cables. 30.Which of the multiplexing techniques are used to combine analog signals? To combine analog signals, commonly FDM(Frequency division multiplexing) and WDM( Wavelength-division multiplexing) are used. 31. Which of the multiplexing techniques is used to combine digital signals? To combine digital signals, time division multiplexing techniques are used. 32. Can IP Multicast be load-balanced? No, The ip multicast multipath command load splits the traffic and does not load balance the traffic. Traffic from a source will use only one path, even if the traffic far outweighs traffic from other sources. 33. What is CGMP(cisco group management protocol)? CGMP is a simple protocol, the routers are the only devices that are producing CGMP messages. The switches only listen to these messages and act upon it. CGMP uses a well-known destination MAC address (0100.0cdd.dddd) for all its messages. When switches receive frames with this destination address, they flood it on all their interfaces which so all switches in the network will receive CGMP messages. Within a CGMP message, the two most important items are: Group Destination Address (GDA) Unicast Source Address (USA) The group destination address is the multicast group MAC address, the unicast source address is the MAC address of the host (receiver). 34. What is Multicast? Multicast is a method of group communication where the sender sends data to multiple receivers or nodes present in the network simultaneously. Multicasting is a type of one-to-many and many-to-many communication as it allows sender or senders to send data packets to multiple receivers at once across LANs or WANs. This process helps in minimizing the data frame of the network. For more details please read Multicasting in computer network article. 35. What is the difference between Bluetooth and wifi? 36. What is a reverse proxy? Reverse Proxy Server: The job of a reverse proxy server to listen to the request made by the client and redirect to the particular web server which is present on different servers. This is also used to restrict the access of the clients to the confidential data residing on the particular servers. For more details please refer what is proxy server article. 37. What is the role of address in packet traveling through a datagram network? The address field in a datagram network is end-to-end addressing. 38. Can a routing table in the datagram network have two entries with the same destination address? No. routing tables in the datagram network have two entries with the same destination address, not possible because the destination address or receiver address is unique in the datagram network. 39. What kind of arithmetic is used to add data items in checksum calculation? To add data items in checksum calculations, one’s complement arithmetic is used. 40. Define piggybacking? A technique called piggybacking is used to improve the efficiency of the bidirectional protocols. When a frame is carrying data from A to B, it can also carry control information about arrived (or lost) frames from B; when a frame is carrying data from B to A, it can also carry control information about the arrived (or lost) frames from A. 41. What are the advantages and disadvantages of piggybacking? The major advantage of piggybacking is better use of available channel bandwidth. The major disadvantage of piggybacking is additional complexity and if the data link layer waits too long before transmitting the acknowledgment, then re-transmission of the frame would take place. 42. Which technique is used in byte-oriented protocols? A byte stuffing is used in byte-oriented protocols. A special byte is added to the data section of the frame when there is a character with the same pattern as the flag. 43. Define the term OFDM? Orthogonal Frequency Division Multiplexing (OFDM):It is also the multiplexing technique that is used in an analog system. In OFDM, the Guard band is not required and the spectral efficiency of OFDM is high which oppose to the FDM. In OFDM, a Single data source attaches all the sub-channels. 44. What is a transparent bridge? Transparent Bridge: A transparent bridge automatically maintains a routing table and updates tables in response to maintain changing topology. The transparent bridge mechanism consists of three mechanisms: Frame forwarding Address Learning Loop Resolution The Transparent bridge is easy to use. Install the bridge and no software changes are needed in hosts. In all the cases, transparent bridges flooded the broadcast and multicast frames. 45. What is the minimum size of the icmpV4 packet what is the maximum size of the icmpv4 packet? Minimum size ICMPv4 packet = 28 bytes Maximum size ICMPv4 packet = 2068 bytes 46. Why do we OSPF a protocol that is faster than our RIP? OSPF stands for Open Shortest Path First which uses a link-state routing algorithm. This protocol is faster than RIP because: Using the link-state information which is available in routers, it constructs the topology in which the topology determines the routing table for routing decisions. It supports both variable-length subnet masking and classless inter-domain routing addressing models. Since it uses Dijkstra’s algorithm, it computes the shortest path tree for each route. OSPF (Open Shortest Path first) is handling the error detection by itself and it uses multicast addressing for routing in a broadcast domain 47. What are the two main categories of DNS messages? The two categories of DNS messages are queries and replies. 48. Why do we need the pop3 protocol for e-mail? Need of POP3: The Post Office Protocol (POP3) is that the most widely used protocol and is being supported by most email clients. It provides a convenient and standard way for users to access mailboxes and download messages. An important advantage of this is that the mail messages get delivered to the client’s PC and they can be read with or without accessing the web. 49. Define the term Jitter? jitter is a “packet delay variance”. It can simply mean that jitter is considered as a problem when different packets of data face different delays in a network and the data at the receiver application is time-sensitive, i.e. audio or video data. Jitter is measured in milliseconds(ms). It is defined as an interference in the normal order of sending data packets. 50. Why Bandwidth is an important to network performance parameter? Bandwidth is characterized as the measure of data or information that can be transmitted in a fixed measure of time. The term can be used in two different contexts with two distinctive estimating values. In the case of digital devices, the bandwidth is measured in bits per second(bps) or bytes per second. In the case of analog devices, the bandwidth is measured in cycles per second, or Hertz (Hz). Bandwidth is only one component of what an individual sees as the speed of a network. True internet speed is actually the amount of data you receive every second and that has a lot to do with latency too. interview-questions Computer Networks Computer Subject Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) SDE SHEET - A Complete Guide for SDE Preparation What is Algorithm | Introduction to Algorithms Software Engineering | Coupling and Cohesion Type Checking in Compiler Design Difference between NP hard and NP complete problem
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Sep, 2021" }, { "code": null, "e": 137, "s": 52, "text": "1. Name two technologies by which you would connect two offices in remote locations." }, { "code": null, "e": 238, "s": 137, "text": "Two technologies by ...
Why copy constructor argument should be const in C++?
05 Jan, 2022 When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, predict the output of following C++ program. Assume that copy elision is not done by compiler. C #include<iostream>using namespace std; class Test{ /* Class data members */public: Test(Test &t) { /* Copy data members from t*/} Test() { /* Initialize data members */ }}; Test fun(){ cout << "fun() Called\n"; Test t; return t;} int main(){ Test t1; Test t2 = fun(); return 0;} Output: Compiler Error in line "Test t2 = fun();" The program looks fine at first look, but it has compiler error. If we add const in copy constructor, the program works fine, i.e., we change copy constructor to following. C Test(const Test &t) { cout << "Copy Constructor Called\n"; } Or if we change the line “Test t2 = fun();” to following two lines, then also the program works fine. C Test t2;t2 = fun(); In above codes, what’s actually happening? It gets executed but copy constructor is not called, instead it calls the default constructor where assignment operator is overloaded. Even if we have an explicit overloaded assignment operator, it is not going to call it. The function fun() returns by value. So the compiler creates a temporary object which is copied to t2 using copy constructor in the original program (The temporary object is passed as an argument to copy constructor). The reason for compiler error is, compiler created temporary objects cannot be bound to non-const references and the original program tries to do that. It doesn’t make sense to modify compiler created temporary objects as they can die any moment. This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above priyanka panda cpp-constructor C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jan, 2022" }, { "code": null, "e": 496, "s": 52, "text": "When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should us...
MYBATIS - Stored Procedures
You can call a stored procedure using MyBatis. First of all, let us understand how to create a stored procedure in MySQL. We have the following EMPLOYEE table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Let us create the following stored procedure in MySQL database − DELIMITER // DROP PROCEDURE IF EXISTS details.read_recordById // CREATE PROCEDURE details.read_recordById (IN emp_id INT) BEGIN SELECT * FROM STUDENT WHERE ID = emp_id; END// DELIMITER ; Assume the table named STUDENT has two records as − mysql> select * from STUDENT; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 900000000 | mohamad123@yahoo.com | | 2 | Shyam | It | 75 | 984800000 | shyam@gmail.com | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec) To use stored procedure, you do not need to modify the Student.java file. Let us keep it as it was in the last chapter. public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.setBranch(branch); this.setPercentage(percentage); this.phone = phone; this.email = email; } public Student() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("Id = ").append(id).append(" - "); sb.append("Name = ").append(name).append(" - "); sb.append("Branch = ").append(branch).append(" - "); sb.append("Percentage = ").append(percentage).append(" - "); sb.append("Phone = ").append(phone).append(" - "); sb.append("Email = ").append(email); return sb.toString(); } } Unlike IBATIS, there is no <procedure> tag in MyBatis. To map the results of the procedures, we have created a resultmap named Student and to call the stored procedure named read_recordById. We have defined a select tag with id callById, and we use the same id in the application to call the procedure. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "callById" resultMap = "result" parameterType = "Student" statementType = "CALLABLE"> {call read_record_byid(#{id, jdbcType = INTEGER, mode = IN})} </select> </mapper> This file has application level logic to read the names of the employees from the Employee table using ResultMap − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class getRecords { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select a particular student by id Student student = (Student) session.selectOne("Student.callById", 3); //Print the student details System.out.println("Details of the student are:: "); System.out.println("Id :"+student.getId()); System.out.println("Name :"+student.getName()); System.out.println("Branch :"+student.getBranch()); System.out.println("Percentage :"+student.getPercentage()); System.out.println("Email :"+student.getEmail()); System.out.println("Phone :"+student.getPhone()); session.commit(); session.close(); } } Here are the steps to compile and run the getRecords program. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.java as shown above and compile it. Create getRecords.java as shown above and compile it. Execute getRecords binary to run the program. You will get the following result − Details of the student are::
[ { "code": null, "e": 2127, "s": 2005, "text": "You can call a stored procedure using MyBatis. First of all, let us understand how to create a stored procedure in MySQL." }, { "code": null, "e": 2175, "s": 2127, "text": "We have the following EMPLOYEE table in MySQL −" }, { ...
std::inner_product in C++
16 Aug, 2021 Compute cumulative inner product of range Returns the result of accumulating init with the inner products of the pairs formed by the elements of two ranges starting at first1 and first2.The two default operations (to add up the result of multiplying the pairs) may be overridden by the arguments binary_op1 and binary_op2.1. Using default inner_product : Syntax: Template : T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); Parameters : first1, last1 Input iterators to the initial and final positions in the first sequence. first2 Input iterator to the initial position in the second sequence. The range starts at first2 and has as many elements as the range above [first1, last1]. init Initial value for the accumulator. Neither operations shall modify any of the elements passed as its arguments. Return Type : The result of accumulating init and the products of all the pairs of elements in the ranges starting at first1 and first2. CPP // CPP program to illustrate// std :: inner_product#include <iostream> // std::cout#include <functional> // std::minus, std::divides#include <numeric> // std::inner_product // Driver codeint main(){ // The value which is added after // finding inner_product b/w elements int init = 100; int series1[] = { 10, 20, 30 }; int series2[] = { 1, 2, 3 }; int n = sizeof(series1) / sizeof(series1[0]); // Elements in series1 std::cout << "First array contains :"; for (int i = 0; i < n; i++) std::cout << " " << series1[i]; std::cout << "\n"; // Elements in series2 std::cout << "Second array contains :"; for (int i = 0; i < n; i++) std::cout << " " << series2[i]; std::cout << "\n\n"; std::cout << "Using default inner_product: "; std::cout << std::inner_product(series1, series1 + n, series2, init); std::cout << '\n'; return 0;} Output: First array contains : 10 20 30 Second array contains : 1 2 3 Using default inner_product: 240 2. Using functional operation : Syntax: Template : T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); Parameters : first1, last1, first2, init are same as above. binary_op1 Binary operation taking two elements of type T as arguments, and returning the result of an accumulation operation. This can either be a function pointer or a function object. binary_op2 Binary operation taking two elements of type T as arguments, and returning the result of the inner product operation. This can either be a function pointer or a function object. Here binary_op1 and binary_op2 are functional operation. Neither operations shall modify any of the elements passed as its arguments. Return Type : The result of accumulating init and the products of all the pairs of elements in the ranges starting at first1 and first2. CPP // CPP program to illustrate// std :: inner_product#include <iostream> // std::cout#include <functional> // std::minus, std::divides#include <numeric> // std::inner_product // Driver codeint main(){ // The value which is added after // finding inner_product b/w elements int init = 100; int series1[] = { 10, 20, 30 }; int series2[] = { 1, 2, 3 }; int n = sizeof(series1) / sizeof(series1[0]); // Elements in series1 std::cout << "First array contains :"; for (int i = 0; i < n; i++) std::cout << " " << series1[i]; std::cout << "\n"; // Elements in series2 std::cout << "Second array contains :"; for (int i = 0; i < n; i++) std::cout << " " << series2[i]; std::cout << "\n\n"; std::cout << "Using functional operations: "; // std :: minus returns the difference b/w // each elements of both array // std :: divides return the quotient of // each elements of both array after performing // divide operation // The operations is performed b/w number of same index // of both array std::cout << std::inner_product(series1, series1 + n, series2, init, std::minus<int>(), std::divides<int>()); std::cout << '\n'; return 0;} Output: First array contains : 10 20 30 Second array contains : 1 2 3 Using functional operations: 70 3. Using custom functions : Syntax: Template : T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); Parameters : first1, last1, first2, init are same as above. binary_op1 Binary operation taking two elements of type T as arguments, and returning the result of an accumulation operation. This can either be a function pointer or a function object. binary_op2 Binary operation taking two elements of type T as arguments, and returning the result of the inner product operation. This can either be a function pointer or a function object. Neither operations shall modify any of the elements passed as its arguments. Return Type : The result of accumulating init and the products of all the pairs of elements in the ranges starting at first1 and first2. CPP // CPP program to illustrate// std :: inner_product#include <iostream> // std::cout#include <functional> // std::minus, std::divides#include <numeric> // std::inner_product // Custom functionsint myaccumulator(int x, int y){ return x - y;}int myproduct(int x, int y){ return x + y;} // Driver codeint main(){ // The value which is added after // finding inner_product b/w elements int init = 100; int series1[] = { 10, 20, 30 }; int series2[] = { 1, 2, 3 }; int n = sizeof(series1) / sizeof(series1[0]); // Elements in series1 std::cout << "First array contains :"; for (int i = 0; i < n; i++) std::cout << " " << series1[i]; std::cout << "\n"; // Elements in series2 std::cout << "Second array contains :"; for (int i = 0; i < n; i++) std::cout << " " << series2[i]; std::cout << "\n\n"; std::cout << "Using custom functions: "; std::cout << std::inner_product(series1, series1 + 3, series2, init, myaccumulator, myproduct); std::cout << '\n'; return 0;} Output: First array contains : 10 20 30 Second array contains : 1 2 3 Using custom functions: 34 NOTE : By using functional value and custom function, we can perform operation by changing the operator ( or using different functional value) in this STL function.Possible Application : It returns the result of accumulating init with the inner products of the pair formed by the elements of two ranges starting at first1 and first2.1. It can be used to find sum of products of i th index of both arrays. For Example: Array 1 : 1 2 3 4 Array 2 : 10 20 30 40Sum of products : 300Explanation : 1 * 10 + 2 * 20 + 3 * 30 + 4 * 40 = 300 CPP // CPP program to illustrate// std :: inner_product#include <iostream> // std::cout#include <functional> // std::minus, std::divides#include <numeric> // std::inner_product // Custom functionsint myaccumulator(int x, int y){ return x + y;}int myproduct(int x, int y){ return x * y;} // Driver codeint main(){ // The value which is added after // finding inner_product b/w elements int init = 0; int series1[] = { 1, 2, 3, 4 }; int series2[] = { 10, 20, 30, 40 }; int n = sizeof(series1) / sizeof(series1[0]); // Elements in series1 std::cout << "Array 1 :"; for (int i = 0; i < n; i++) std::cout << " " << series1[i]; std::cout << "\n"; // Elements in series2 std::cout << "Array 2 :"; for (int i = 0; i < n; i++) std::cout << " " << series2[i]; std::cout << "\n\n"; std::cout << "Sum of products : "; std::cout << std::inner_product(series1, series1 + n, series2, init, myaccumulator, myproduct); std::cout << '\n'; return 0;} OUTPUT : Array 1 : 1 2 3 4 Array 2 : 10 20 30 40 Sum of products : 300 We can also find the difference of products, or sum of division, or difference of division and more all by changing the operator.This article is contributed by Sachin Bisht. 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. varshagumber28 cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Queue in C++ Standard Template Library (STL) std::find in C++ Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) vector insert() function in C++ STL
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 393, "s": 28, "text": "Compute cumulative inner product of range Returns the result of accumulating init with the inner products of the pairs formed by the elements of two ranges starting at first1 ...
How to get the day and month of a year using JavaScript ?
23 Aug, 2019 Given a date and the task is to get the day and month of a year using JavaScript. Approach: First get the current date by using new Date(). Use currentDate.getDay() to get the current day in number format, Map it to the day name. Use currentDate.getMonth() to get the current month in number format, Map it to the month name. Example 1: In this example, the month and date is determined by the above approach. <!DOCTYPE HTML> <html> <head> <title> How to get the day and month of a year using JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get " + "the day and month of the date."; var Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var currentDay = new Date(); // Get the current day name var day = Days[currentDay.getDay()]; // Get the current month name var month = Months[currentDay.getMonth()]; function GFG_Fun() { el_down.innerHTML = "Day - " + day + ",<br> Month - " + month; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This is same example but with a different approach. In this example, the month and date is determined by the above approach. <!DOCTYPE HTML> <html> <head> <title> How to get the day and month of a year using JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the " + "day and month of the date."; var currentDay = new Date(); // Get the current day name var day = currentDay.getDay(); // Getting the current month name var month = currentDay.getMonth(); function GFG_Fun() { el_down.innerHTML = "Day - " + day + " Where, Monday is 1,<br> Month - " + month +" Where, January is 0."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date JavaScript 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2019" }, { "code": null, "e": 110, "s": 28, "text": "Given a date and the task is to get the day and month of a year using JavaScript." }, { "code": null, "e": 120, "s": 110, "text": "Approach:" }, { ...
hdparm command in Linux with Examples
21 May, 2019 “hdparm“(i.e, hard disk parameter) is one of the command line programs for Linux which is used to handle disk devices and hard disks. With the help of this command, you can get statistics about the hard disk, alter writing intervals, acoustic management, and DMA settings. It can also set parameters related to drive caches, sleep mode, power management, acoustic management, and DMA settings. Syntax: hdparm [options] [device] Note: When no flags are specified, –acdgkmnru is presumed. Options: -a : It is used to Get/set enumeration of a section of file system read-ahead which is implemented to enhance the accomplishment of the uninterrupted reads of the files that are enormous in size. -A : It Disables/enable the IDE drive’s read-look-ahead property that is generally functioning by default. -b : It is used to Get/set bus state where, (0 == Off, 1 == On, 2 == tristate). -B : It is used to Set Advanced Power Management (APM) characteristics, but only if the drive can bear it. If its value is low then the APM is violent and if the value is high then it gives finer accomplishment. To disable the APM you need to set the value to 255. -c : It Query/enable (E)IDE 32-bit I/O support. Here, 32-bit alludes to the transmission of inputs over PCI or VLB bus. -C : It is used to inspect the ongoing IDE power mode position. The flags -S, -Y, -y, and -Z are used to control IDE power techniques in a skillful manner. -d : It disables or enables the flag used by “DMA” drive. It operates through the incorporation of drives and PCI. -D : It enables or disables the on-drive defect managing property. -E : It Sets SD/DVD drive speed. In order to make it work you need to assign a speed number succeeding the option. Generally, the number used is two or four. -f : This is used to synchronize and cleanse the buffer cache for the device on its outlet. This performance can be executed as a segment of the -t and -T timings. -g : This is used to unveil the configuration of the drive, the expanse of the drive, and the starting offset of the device from the starting point of the drive. -h : It display the help message and exit. -i : This unveils the recognition data which was acquired from the drive at the boot time. -I : This seeks the recognition data straight from the drive and it shows more features than the -i flag. -k : This helps to get/set the keep_settings_over_reset flag for the drive. -K : This Sets the drive’s keep_features_over_reset flag. This feature is not provided by all the drives. -m : It is used to get/set sector count for multiple sectors I/O on the drive. To disable this feature you need to set the value to zero. -M : This helps to Get/set Automatic Acoustic Management (AAM) setting. This feature is experimental and it is not efficiently tested so, one must use it at their own risk. -n : It is used to get/set “ignore write errors” flag. One should not play with this feature without decoding the source code of the driver first. -r : It is used to get/set the read-only flag for the device. When this option is set then the write operations are not sanctioned on the device. -S : It Set the standby timeout for the drive. When the value is set to zero then it is off. -T : It executes the timing of cache reads for standard and differentiating purposes. It unveils the speed of reading straight from the buffer of the Linux cache in absence of the access to the disk, you need to perform this operation two to three times for better results. -t : This has the same purpose as -T flag except for that it unveils the speed of reading through the buffer cache to the disk in the absence of any prior caching of the inputs. If the -T flag is also defined here then the rectification done on the aftermath of -T will be encompassed into the consequence appeared at the time of -t operation. -u : It is used to get/set the interrupt-unmask flag for the drive when the value is set to one then the driver could unmask other interventions which occur in the processing of disk interrupts. This property can cause enormous file system corruption so, use at your own risk. -v : This unveils all the settings, except -i. -w : It helps in the device reset. -W : It Disables/enable the IDE drive’s write-caching characteristics. -y : It forces an IDE drive to immediately enter the low power consumption standby mode, usually causing it to spin down. The current power mode status can be checked using the -C flag. -Y : This pressurizes an IDE to interrupt into the low power consumption sleep mode, in order to shut down it completely, here the current power mode status can be detected with the help of -C flag. -z : This forces kernel re-read of the partition table for the designated device. -Z : This disables the automatic power-saving function. Examples: Command to display information of the hard drive: It is one of the most significant features as it unveils details of the hard disk drive, you need to use -I option and hard disk drive here.$ hdparm -I /dev/sda $ hdparm -I /dev/sda Command to display all the options:$ hdparm -h $ hdparm -h Command to test hard disk drive speed:$ hdparm -t /dev/vdb $ hdparm -t /dev/vdb Command to measure hard disk cache read speed:$ hdparm -T /dev/vdbOutput: $ hdparm -T /dev/vdb Output: Command to Enable read-ahead:$ hdparm -A 1 /dev/sda $ hdparm -A 1 /dev/sda Command to switch the drive to the lowest degree of power management:$ hdparm -B 254 /dev/sda $ hdparm -B 254 /dev/sda Command to get current settings:$ hdparm -d /dev/sdX $ hdparm -d /dev/sdX Command to set DMA on for a device:$ hdparm -d1 /dev/hda $ hdparm -d1 /dev/hda Command to lower the noise created by some classical hard disk by lowering disk performance:$ hdparm -M 128 /dev/sda $ hdparm -M 128 /dev/sda linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2019" }, { "code": null, "e": 422, "s": 28, "text": "“hdparm“(i.e, hard disk parameter) is one of the command line programs for Linux which is used to handle disk devices and hard disks. With the help of this command, you can ge...
Iterative Merge Sort - GeeksforGeeks
02 Mar, 2022 Following is a typical recursive implementation of Merge Sort C++ C Java Python3 C# Javascript // Recursive C++ program for merge sort#include<bits/stdc++.h>using namespace std; // Function to merge the two haves// arr[l..m] and arr[m+1..r] of array arr[]void merge(int arr[], int l, int m, int r); // l is for left index and r is// right index of the sub-array// of arr to be sortedvoid mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2 but avoids // overflow for large l & h int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} // Function to merge the two haves arr[l..m]// and arr[m+1..r] of array arr[]void merge(int arr[], int l, int m, int r){ int k; int n1 = m - l + 1; int n2 = r - m; // Create temp arrays int L[n1], R[n2]; // Copy data to temp arrays L[] and R[] for(int i = 0; i < n1; i++) L[i] = arr[l + i]; for(int j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; // Merge the temp arrays // back into arr[l..r] int i = 0; int j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy the remaining elements // of L[], if there are any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy the remaining elements // of R[], if there are any while (j < n2) { arr[k] = R[j]; j++; k++; }} // Function to print an arrayvoid printArray(int A[], int size){ for(int i = 0; i < size; i++) printf("%d ", A[i]); cout << "\n";} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); cout << "\nSorted array is \n"; printArray(arr, arr_size); return 0;} // This code is contributed by Mayank Tyagi /* Recursive C program for merge sort */#include<stdlib.h>#include<stdio.h> /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r); /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2 but avoids // overflow for large l & h int m = l+(r-l)/2; mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); }} /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* Function to print an array */void printArray(int A[], int size){ int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf("\n");} /* Driver program to test above functions */int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int arr_size = sizeof(arr)/sizeof(arr[0]); printf("Given array is \n"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0;} // Recursive Java Program for merge sort import java.util.Arrays;public class GFG{ public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length > 1) { int mid = array.length / 2; // Split left part int[] left = new int[mid]; for(int i = 0; i < mid; i++) { left[i] = array[i]; } // Split right part int[] right = new int[array.length - mid]; for(int i = mid; i < array.length; i++) { right[i - mid] = array[i]; } mergeSort(left); mergeSort(right); int i = 0; int j = 0; int k = 0; // Merge left and right arrays while(i < left.length && j < right.length) { if(left[i] < right[j]) { array[k] = left[i]; i++; } else { array[k] = right[j]; j++; } k++; } // Collect remaining elements while(i < left.length) { array[k] = left[i]; i++; k++; } while(j < right.length) { array[k] = right[j]; j++; k++; } } } // Driver program to test above functions. public static void main(String[] args) { int arr[] = {12, 11, 13, 5, 6, 7}; int i=0; System.out.println("Given array is"); for(i=0; i<arr.length; i++) System.out.print(arr[i]+" "); mergeSort(arr); System.out.println("\n"); System.out.println("Sorted array is"); for(i=0; i<arr.length; i++) System.out.print(arr[i]+" "); }} // Code Contributed by Mohit Gupta_OMG # Recursive Python Program for merge sort def merge(left, right): if not len(left) or not len(right): return left or right result = [] i, j = 0, 0 while (len(result) < len(left) + len(right)): if left[i] < right[j]: result.append(left[i]) i+= 1 else: result.append(right[j]) j+= 1 if i == len(left) or j == len(right): result.extend(left[i:] or right[j:]) break return result def mergesort(list): if len(list) < 2: return list middle = int(len(list)/2) left = mergesort(list[:middle]) right = mergesort(list[middle:]) return merge(left, right) seq = [12, 11, 13, 5, 6, 7]print("Given array is")print(seq);print("\n")print("Sorted array is")print(mergesort(seq)) # Code Contributed by Mohit Gupta_OMG /* Iterative C# program for mergesort */using System; class GFG { /* l is for left index and r is right index of the sub-array of arr to be sorted */ static void mergeSort(int[] arr, int l, int r) { if (l < r) { // Same as (l+r)/2 but avoids // overflow for large l & h int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); } } /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */ static void merge(int[] arr, int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int []L = new int[n1]; int []R = new int[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* Function to print an array */ static void printArray(int []A, int size) { int i; for (i=0; i < size; i++) Console.Write(A[i]+" "); Console.Write("\n"); } /* Driver program to test above functions */ public static void Main() { int []arr = {12, 11, 13, 5, 6, 7}; int arr_size = arr.Length; Console.Write("Given array is \n"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); Console.Write("\nSorted array is \n"); printArray(arr, arr_size); }} // This code is contributed by Smitha <script> // Recursive javascript Program for merge sort function mergeSort(array) { if (array == null) { return; } if (array.length > 1) { var mid = parseInt(array.length / 2); // Split left part var left = Array(mid).fill(0); for (i = 0; i < mid; i++) { left[i] = array[i]; } // Split right part var right = Array(array.length - mid).fill(0); for (i = mid; i < array.length; i++) { right[i - mid] = array[i]; } mergeSort(left); mergeSort(right); var i = 0; var j = 0; var k = 0; // Merge left and right arrays while (i < left.length && j < right.length) { if (left[i] < right[j]) { array[k] = left[i]; i++; } else { array[k] = right[j]; j++; } k++; } // Collect remaining elements while (i < left.length) { array[k] = left[i]; i++; k++; } while (j < right.length) { array[k] = right[j]; j++; k++; } } } // Driver program to test above functions. var arr = [ 12, 11, 13, 5, 6, 7 ]; var i = 0; document.write("Given array is<br/>"); for (i = 0; i < arr.length; i++) document.write(arr[i] + " "); mergeSort(arr); document.write("<br/><br/>"); document.write("Sorted array is<br/>"); for (i = 0; i < arr.length; i++) document.write(arr[i] + " "); // This code is contributed by umadevi9616 </script> Output: Given array is 12 11 13 5 6 7 Sorted array is 5 6 7 11 12 13 Iterative Merge Sort: The above function is recursive, so uses function call stack to store intermediate values of l and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls involve overheads like storing activation record of the caller function and then resuming execution. Unlike Iterative QuickSort, the iterative MergeSort doesn’t require explicit auxiliary stack. Note: In iterative merge sort, we do bottom up approach ie, start from 2 element sized array (we know that 1 element sized array is already sorted). Also the key point is that since we don’t know how to divide the array exactly as in top down approach, where the 2 element sized array may be of size sequence 2,1,2,2,1...we in bottom up approach assume the array was divided exactly by powers of 2 (n/2,n/4....etc) for an array size of powers of 2, ex: n=2,4,8,16. So for other input sizes such as 5, 7, 11 we will have remaining sublist that didn’t go into the power of 2 width at each level as we keep on merging and go upwards, this unmerged sublist which is of size that is not exact power of 2, will remain isolated till the final merge. To merge this unmerged list at final merge we need to force the mid to be at the start of unmerged list so that it is a candidate for merge. The unmerged sublist element count that will be isolated until final merge call can be found out using the remainder (n % width). The final merge (when we have uneven lists) can be identified by (width>n/2). Since width grows by powers of 2 when width == n/2 then it means the input was already of size in powers of 2, else if width < n/2 then we haven’t reached final merge yet, so when width > n/2 we must be having pending unmerged uneven list hence we reset mid only in such case. The above function can be easily converted to iterative version. Following is iterative Merge Sort. C++ C Java Python3 C# Javascript /* Iterative C program for merge sort */#include <bits/stdc++.h>using namespace std; /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r); // Utility function to find minimum of two integersint min(int x, int y) { return (x<y)? x :y; } /* Iterative mergesort function to sort arr[0...n-1] */void mergeSort(int arr[], int n){ int curr_size; // For current size of subarrays to be merged // curr_size varies from 1 to n/2 int left_start; // For picking starting index of left subarray // to be merged // Merge subarrays in bottom up manner. First merge subarrays of // size 1 to create sorted subarrays of size 2, then merge subarrays // of size 2 to create sorted subarrays of size 4, and so on. for (curr_size=1; curr_size<=n-1; curr_size = 2*curr_size) { // Pick starting point of different subarrays of current size for (left_start=0; left_start<n-1; left_start += 2*curr_size) { // Find ending point of left subarray. mid+1 is starting // point of right int mid = min(left_start + curr_size - 1, n-1); int right_end = min(left_start + 2*curr_size - 1, n-1); // Merge Subarrays arr[left_start...mid] & arr[mid+1...right_end] merge(arr, left_start, mid, right_end); } }} /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* Function to print an array */void printArray(int A[], int size){ int i; for (i=0; i < size; i++) cout <<" "<< A[i]; cout <<"\n";} /* Driver program to test above functions */int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); cout <<"Given array is \n "; printArray(arr, n); mergeSort(arr, n); cout <<"\nSorted array is \n "; printArray(arr, n); return 0;}// This code is contributed shivanisinghss2110 /* Iterative C program for merge sort */#include<stdlib.h>#include<stdio.h> /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r); // Utility function to find minimum of two integersint min(int x, int y) { return (x<y)? x :y; } /* Iterative mergesort function to sort arr[0...n-1] */void mergeSort(int arr[], int n){ int curr_size; // For current size of subarrays to be merged // curr_size varies from 1 to n/2 int left_start; // For picking starting index of left subarray // to be merged // Merge subarrays in bottom up manner. First merge subarrays of // size 1 to create sorted subarrays of size 2, then merge subarrays // of size 2 to create sorted subarrays of size 4, and so on. for (curr_size=1; curr_size<=n-1; curr_size = 2*curr_size) { // Pick starting point of different subarrays of current size for (left_start=0; left_start<n-1; left_start += 2*curr_size) { // Find ending point of left subarray. mid+1 is starting // point of right int mid = min(left_start + curr_size - 1, n-1); int right_end = min(left_start + 2*curr_size - 1, n-1); // Merge Subarrays arr[left_start...mid] & arr[mid+1...right_end] merge(arr, left_start, mid, right_end); } }} /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* Function to print an array */void printArray(int A[], int size){ int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf("\n");} /* Driver program to test above functions */int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); printf("Given array is \n"); printArray(arr, n); mergeSort(arr, n); printf("\nSorted array is \n"); printArray(arr, n); return 0;} /* Iterative Java program for merge sort */import java.lang.Math.*; class GFG { /* Iterative mergesort function to sor t arr[0...n-1] */ static void mergeSort(int arr[], int n) { // For current size of subarrays to // be merged curr_size varies from // 1 to n/2 int curr_size; // For picking starting index of // left subarray to be merged int left_start; // Merge subarrays in bottom up // manner. First merge subarrays // of size 1 to create sorted // subarrays of size 2, then merge // subarrays of size 2 to create // sorted subarrays of size 4, and // so on. for (curr_size = 1; curr_size <= n-1; curr_size = 2*curr_size) { // Pick starting point of different // subarrays of current size for (left_start = 0; left_start < n-1; left_start += 2*curr_size) { // Find ending point of left // subarray. mid+1 is starting // point of right int mid = Math.min(left_start + curr_size - 1, n-1); int right_end = Math.min(left_start + 2*curr_size - 1, n-1); // Merge Subarrays arr[left_start...mid] // & arr[mid+1...right_end] merge(arr, left_start, mid, right_end); } } } /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */ static void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* Function to print an array */ static void printArray(int A[], int size) { int i; for (i=0; i < size; i++) System.out.printf("%d ", A[i]); System.out.printf("\n"); } /* Driver program to test above functions */ public static void main(String[] args) { int arr[] = {12, 11, 13, 5, 6, 7}; int n = arr.length; System.out.printf("Given array is \n"); printArray(arr, n); mergeSort(arr, n); System.out.printf("\nSorted array is \n"); printArray(arr, n); }} // This code is contributed by Smitha # Iterative Merge sort (Bottom Up) # Iterative mergesort function to# sort arr[0...n-1] # perform bottom up mergedef mergeSort(a): # start with least partition size of 2^0 = 1 width = 1 n = len(a) # subarray size grows by powers of 2 # since growth of loop condition is exponential, # time consumed is logarithmic (log2n) while (width < n): # always start from leftmost l=0; while (l < n): r = min(l+(width*2-1), n-1) m = min(l+width-1,n-1) # final merge should consider # unmerged sublist if input arr # size is not power of 2 merge(a, l, m, r) l += width*2 # Increasing sub array size by powers of 2 width *= 2 return a # Merge Functiondef merge(a, l, m, r): n1 = m - l + 1 n2 = r - m L = [0] * n1 R = [0] * n2 for i in range(0, n1): L[i] = a[l + i] for i in range(0, n2): R[i] = a[m + i + 1] i, j, k = 0, 0, l while i < n1 and j < n2: if L[i] <= R[j]: a[k] = L[i] i += 1 else: a[k] = R[j] j += 1 k += 1 while i < n1: a[k] = L[i] i += 1 k += 1 while j < n2: a[k] = R[j] j += 1 k += 1 # Driver codea = [-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39]print("Given array is ")print(a)mergeSort(a) print("Sorted array is ")print(a) # Contributed by Madhur Chhangani [RCOEM]# corrected and improved by @mahee96 /* Iterative C# program for merge sort */using System;public class GFG { /* Iterative mergesort function to sor t arr[0...n-1] */ static void mergeSort(int []arr, int n) { // For current size of subarrays to // be merged curr_size varies from // 1 to n/2 int curr_size; // For picking starting index of // left subarray to be merged int left_start; // Merge subarrays in bottom up // manner. First merge subarrays // of size 1 to create sorted // subarrays of size 2, then merge // subarrays of size 2 to create // sorted subarrays of size 4, and // so on. for (curr_size = 1; curr_size <= n-1; curr_size = 2*curr_size) { // Pick starting point of different // subarrays of current size for (left_start = 0; left_start < n-1; left_start += 2*curr_size) { // Find ending point of left // subarray. mid+1 is starting // point of right int mid = Math.Min(left_start + curr_size - 1,n-1); int right_end = Math.Min(left_start + 2*curr_size - 1, n-1); // Merge Subarrays arr[left_start...mid] // & arr[mid+1...right_end] merge(arr, left_start, mid, right_end); } } } /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */ static void merge(int []arr, int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int []L = new int[n1]; int []R = new int[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* Function to print an array */ static void printArray(int []A, int size) { int i; for (i=0; i < size; i++) Console.Write(A[i]+" "); Console.WriteLine(""); } /* Driver program to test above functions */ public static void Main() { int []arr = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39}; int n = arr.Length; Console.Write("Given array is \n"); printArray(arr, n); mergeSort(arr, n); Console.Write("\nSorted array is \n"); printArray(arr, n); }}// This code is contributed by Rajput-Ji <script>/* Iterative javascript program for merge sort */ /* * Iterative mergesort function to sor t arr[0...n-1] */ function mergeSort(arr , n) { // For current size of subarrays to // be merged curr_size varies from // 1 to n/2 var curr_size; // For picking starting index of // left subarray to be merged var left_start; // Merge subarrays in bottom up // manner. First merge subarrays // of size 1 to create sorted // subarrays of size 2, then merge // subarrays of size 2 to create // sorted subarrays of size 4, and // so on. for (curr_size = 1; curr_size <= n - 1; curr_size = 2 * curr_size) { // Pick starting point of different // subarrays of current size for (left_start = 0; left_start < n - 1; left_start += 2 * curr_size) { // Find ending point of left // subarray. mid+1 is starting // point of right var mid = Math.min(left_start + curr_size - 1, n - 1); var right_end = Math.min(left_start + 2 * curr_size - 1, n - 1); // Merge Subarrays arr[left_start...mid] // & arr[mid+1...right_end] merge(arr, left_start, mid, right_end); } } } /* * Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr */ function merge(arr , l , m , r) { var i, j, k; var n1 = m - l + 1; var n2 = r - m; /* create temp arrays */ var L = Array(n1).fill(0); var R = Array(n2).fill(0); /* * Copy data to temp arrays L and R */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* * Merge the temp arrays back into arr[l..r] */ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* * Copy the remaining elements of L, if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* * Copy the remaining elements of R, if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* Function to print an array */ function printArray(A , size) { var i; for (i = 0; i < size; i++) document.write( A[i]+" "); document.write("<br/>"); } /* Driver program to test above functions */ var arr = [-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39]; var n = arr.length; document.write("Given array is <br/>"); printArray(arr, n); mergeSort(arr, n); document.write("<br/>Sorted array is <br/>"); printArray(arr, n); // This code contributed by umadevi9616</script> Output: Given array is 12 11 13 5 6 7 Sorted array is 5 6 7 11 12 13 Time complexity of above iterative function is same as recursive, i.e., Θ(nLogn). References: http://csg.sph.umich.edu/abecasis/class/2006/615.09.pdfThis article is contributed by Shivam Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above MADHURCHHANGANI Smitha Dinesh Semwal parv Rajput-Ji pravinshankar1 rishiraj1996 mayanktyagi1709 umadevi9616 shivanisinghss2110 mahee96 skyber71 surindertarika1234 simmytarika5 nehakumariintern Merge Sort Sorting Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Chocolate Distribution Problem Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array Python Program for Bubble Sort
[ { "code": null, "e": 25233, "s": 25205, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25296, "s": 25233, "text": "Following is a typical recursive implementation of Merge Sort " }, { "code": null, "e": 25300, "s": 25296, "text": "C++" }, { "code": n...
Auto-Hide or Auto-Extend Floating Action Button in RecyclerView in Android - GeeksforGeeks
27 Sep, 2021 In the article Auto-Hide or Auto-Extend Floating Action Button for NestedScrollView in Android it’s been discussed and demonstrated how to auto-extend or hide the Floating Action Button in the Nested Scroll View. In this article, it’s discussed how to Hide or Extend the Floating Action Button in Android. Look at the following image to get an overview of the discussion. Create an empty activity project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Add Required Dependency Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner. implementation “androidx.recyclerview:recyclerview:1.2.1” Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below. Step 1: Working with activity_main.xml file The main layout of the project contains one RecyclerView and one Normal Floating Action Button. To implement the same layout invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/normalFAB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:src="@drawable/ic_add" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Before going to the output we need to populate the RecyclerView with the data. So we need to now work with RecyclerView Adapter and a custom view for the RecyclerView. Step 2: Create a custom view for RecyclerView The custom view for the RecyclerView contains one simple icon at the left and two TextViews. To implement the same create a file named recycler_data_view.xml inside the layout folder and invoke the following code. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp"> <ImageView android:id="@+id/imageView" android:layout_width="54dp" android:layout_height="54dp" android:src="@drawable/ic_android" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/tvNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:textSize="24sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@+id/tvNumbersInText" app:layout_constraintStart_toEndOf="@+id/imageView" app:layout_constraintTop_toTopOf="parent" tools:text="1" /> <TextView android:id="@+id/tvNumbersInText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="@+id/tvNumber" app:layout_constraintTop_toBottomOf="@+id/tvNumber" tools:text="One" /> </androidx.constraintlayout.widget.ConstraintLayout> The above custom view produces the following output for each item in the list: Step 3: Creating Data Class for RecyclerView Now creating the data for the above custom view by creating a Data Class, using the following code. Kotlin data class RecyclerViewData( val text1: String, val text2: String) Step 4: Creating the RecyclerView Adapter The following code needs to invoke in a separate class by creating the class named as MyRecyclerAdapter. Kotlin import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerView class MyRecyclerViewAdapter(private val items: List<RecyclerViewData>) : RecyclerView.Adapter<MyRecyclerViewAdapter.MyRecyclerViewDataHolder>() { inner class MyRecyclerViewDataHolder(itemView: View) : RecyclerView.ViewHolder(itemView) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewDataHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.recycler_data_view, parent, false) return MyRecyclerViewDataHolder(view) } override fun onBindViewHolder(holder: MyRecyclerViewDataHolder, position: Int) { val currentItem: RecyclerViewData = items[position] val tvNumber: TextView = holder.itemView.findViewById(R.id.tvNumber) tvNumber.text = currentItem.text1 val tvNumbersInText: TextView = holder.itemView.findViewById(R.id.tvNumbersInText) tvNumbersInText.text = currentItem.text2 } override fun getItemCount(): Int { return items.size }} Step 5: Working with the MainActivity.kt file In this class, we have to create some sample data for the RecyclervView in the form of a list and handle the scroll listener for the recycler view when it is scrolled up and down. When it scrolled up we have to hide the FAB and show the FAB when scrolled down. To implement the same invoke the following code inside the MainActivity.kt file (comments are added for better understanding). Kotlin import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerViewimport com.google.android.material.floatingactionbutton.FloatingActionButton class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create an instance of the Normal Floating Action Button // and register with the appropriate ID val fab: FloatingActionButton = findViewById(R.id.normalFAB) // create instance of RecyclerView and // register with the appropriate ID val recyclerView: RecyclerView = findViewById(R.id.recyclerView) // create list of RecyclerViewData var recyclerViewData = listOf<RecyclerViewData>() recyclerViewData = recyclerViewData + RecyclerViewData("1", "One") recyclerViewData = recyclerViewData + RecyclerViewData("2", "Two") recyclerViewData = recyclerViewData + RecyclerViewData("3", "Three") recyclerViewData = recyclerViewData + RecyclerViewData("4", "Four") recyclerViewData = recyclerViewData + RecyclerViewData("5", "Five") recyclerViewData = recyclerViewData + RecyclerViewData("6", "Six") recyclerViewData = recyclerViewData + RecyclerViewData("7", "Seven") recyclerViewData = recyclerViewData + RecyclerViewData("8", "Eight") recyclerViewData = recyclerViewData + RecyclerViewData("9", "Nine") recyclerViewData = recyclerViewData + RecyclerViewData("10", "Ten") recyclerViewData = recyclerViewData + RecyclerViewData("11", "Eleven") recyclerViewData = recyclerViewData + RecyclerViewData("12", "Twelve") recyclerViewData = recyclerViewData + RecyclerViewData("13", "Thirteen") recyclerViewData = recyclerViewData + RecyclerViewData("14", "Fourteen") recyclerViewData = recyclerViewData + RecyclerViewData("15", "Fifteen") // create a vertical layout manager val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) // create instance of MyRecyclerViewAdapter val myRecyclerViewAdapter = MyRecyclerViewAdapter(recyclerViewData) // attach the adapter to the recycler view recyclerView.adapter = myRecyclerViewAdapter // also attach the layout manager recyclerView.layoutManager = layoutManager // make the adapter the data set changed for the recycler view myRecyclerViewAdapter.notifyDataSetChanged() // now creating the scroll listener for the recycler view recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) // if the recycler view is scrolled // above hide the FAB if (dy > 10 && fab.isShown) { fab.hide() } // if the recycler view is // scrolled above show the FAB if (dy < -10 && !fab.isShown) { fab.show() } // of the recycler view is at the first // item always show the FAB if (!recyclerView.canScrollVertically(-1)) { fab.show() } } }) }} Output: For Extended Floating Action Button Make changes to the activity_main.xml file by invoking the following code. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton android:id="@+id/extendedFAB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:text="ADD ITEM" app:icon="@drawable/ic_add" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Make changes inside the MainActivity.kt file by invoking the following code. Kotlin import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerViewimport com.google.android.material.floatingactionbutton.ExtendedFloatingActionButtonimport com.google.android.material.floatingactionbutton.FloatingActionButton class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create an instance of the Normal Floating Action Button // and register with the appropriate ID val fab: ExtendedFloatingActionButton = findViewById(R.id.extendedFAB) // create instance of RecyclerView and register with the appropriate ID val recyclerView: RecyclerView = findViewById(R.id.recyclerView) // create list of RecyclerViewData var recyclerViewData = listOf<RecyclerViewData>() recyclerViewData = recyclerViewData + RecyclerViewData("1", "One") recyclerViewData = recyclerViewData + RecyclerViewData("2", "Two") recyclerViewData = recyclerViewData + RecyclerViewData("3", "Three") recyclerViewData = recyclerViewData + RecyclerViewData("4", "Four") recyclerViewData = recyclerViewData + RecyclerViewData("5", "Five") recyclerViewData = recyclerViewData + RecyclerViewData("6", "Six") recyclerViewData = recyclerViewData + RecyclerViewData("7", "Seven") recyclerViewData = recyclerViewData + RecyclerViewData("8", "Eight") recyclerViewData = recyclerViewData + RecyclerViewData("9", "Nine") recyclerViewData = recyclerViewData + RecyclerViewData("10", "Ten") recyclerViewData = recyclerViewData + RecyclerViewData("11", "Eleven") recyclerViewData = recyclerViewData + RecyclerViewData("12", "Twelve") recyclerViewData = recyclerViewData + RecyclerViewData("13", "Thirteen") recyclerViewData = recyclerViewData + RecyclerViewData("14", "Fourteen") recyclerViewData = recyclerViewData + RecyclerViewData("15", "Fifteen") // create a vertical layout manager val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) // create instance of MyRecyclerViewAdapter val myRecyclerViewAdapter = MyRecyclerViewAdapter(recyclerViewData) // attach the adapter to the recycler view recyclerView.adapter = myRecyclerViewAdapter // also attach the layout manager recyclerView.layoutManager = layoutManager // make the adapter the data set // changed for the recycler view myRecyclerViewAdapter.notifyDataSetChanged() // now creating the scroll listener // for the recycler view recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) // if the recycler view is scrolled // above shrink the FAB if (dy > 10 && fab.isExtended) { fab.shrink() } // if the recycler view is scrolled // above extend the FAB if (dy < -10 && !fab.isExtended) { fab.extend() } // of the recycler view is at the first // item always extend the FAB if (!recyclerView.canScrollVertically(-1)) { fab.extend() } } }) }} Output: Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters Kotlin when expression
[ { "code": null, "e": 26491, "s": 26463, "text": "\n27 Sep, 2021" }, { "code": null, "e": 26863, "s": 26491, "text": "In the article Auto-Hide or Auto-Extend Floating Action Button for NestedScrollView in Android it’s been discussed and demonstrated how to auto-extend or hide the ...
Gas Station in C++
Suppose there is a circle, and there are n gas stations on the circle. We have two sets of data like − The amount of gas that every gas stations has Distance from one gas stations to another. Calculate the first point, from where a car will be able to complete the circle. Assume for 1 unit of gas, the car can go 1 unit of distance. Suppose there are four gas stations, and the amount of gas, and distance from the next gas stations is as like [(4, 6), (6, 5), (7, 3), (4, 5)], the first point from where car can make a circular tour is 2nd gas stations. Output should be start = 1 (index of second gas stations) This problem can be solved efficiently using queue. Queue will be used to store the current tour. We will insert the first gas stations into the queue, we will insert gas stations till, we either complete the tour, or current amount of gas becomes negative. If the amount becomes negative, then we keep deleting gas stations until it becomes empty. Let us see the following implementation to get a better understanding − Live Demo #include <iostream> using namespace std; class gas { public: int gas; int distance; }; int findStartIndex(gas stationQueue[], int n) { int start_point = 0; int end_point = 1; int curr_gas = stationQueue [start_point].gas - stationQueue [start_point].distance; while (end_point != start_point || curr_gas < 0) { while (curr_gas < 0 && start_point != end_point) { curr_gas -= stationQueue[start_point].gas - stationQueue [start_point].distance; start_point = (start_point + 1) % n; if (start_point == 0) return -1; } curr_gas += stationQueue[end_point].gas - stationQueue [end_point].distance; end_point = (end_point + 1) % n; } return start_point; } int main() { gas gasArray[] = {{4, 6}, {6, 5}, {7, 3}, {4, 5}}; int n = sizeof(gasArray)/sizeof(gasArray [0]); int start = findStartIndex(gasArray, n); if(start == -1) cout<<"No solution"; else cout<<"Index of first gas station : "<<start; } [[4, 6], [6, 5], [7, 3], [4, 5]] Index of first gas station : 1
[ { "code": null, "e": 1165, "s": 1062, "text": "Suppose there is a circle, and there are n gas stations on the circle. We have two sets of data like −" }, { "code": null, "e": 1211, "s": 1165, "text": "The amount of gas that every gas stations has" }, { "code": null, "...
How to Install and Run UserRecon Tool? - GeeksforGeeks
05 Oct, 2021 UserRecon tool is used to find usernames across over 75 social networks. It is very useful when you are running an investigation to determine the usage of the same username across different social media platforms such as Twitter, Instagram, MySpace, Youtube, Reddit, WordPress, GitHub, and many more. With the push of a button, an OSINT investigator will be able to find whether the same username exists on different social media networks. It is a very convenient and easy-to-use tool. Step 1: Open your terminal and type the following command. git clone https://github.com/issamelferkh/userrecon.git Step 2: After cloning the tool, change the directory to UserRecon. cd userrecon Fig 1: UserRecon cloned and directory changed to UserRecon. Step 3: Now list all hidden files using ls -la command in your terminal. ls -la Step 4: Change the permission of userrecon.sh. chmod +x userrecon.sh Step 5: After changing the permission of userrecon.sh, run the tool by the following command. ./userrecon.sh Fig 2: UserRecon up and running. After running the tool by the command, ./userrecon.sh, you will see a screen similar to the one shown above. Now just type in the username you want to search and see the magic happens. Fig 3: Searching username ‘Talha’. As we can see, UserRecon is searching the username ‘Talha’ on all 75 sites and returning the link if it exists. All this data gets stored in Talha.txt file. It can be accessed in any text editor. Suppose, we want to open it in vi editors, the command will be: vi Talha.txt Fig 4: Talha.txt file opened in vi editor. We can open any of the links to see the profile on that social media network. To exit from vi editors, press shift + ZQ. As we can see from the above operations UserRecon can be a very useful and time-saving tool if someone wants to search for a username on social medial networks. how-to-install Linux-Tools How To Installation Guide Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Check the OS Version in Linux? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 24976, "s": 24948, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25462, "s": 24976, "text": "UserRecon tool is used to find usernames across over 75 social networks. It is very useful when you are running an investigation to determine the usage of the same...
How to Install Zip and Unzip in Linux? - GeeksforGeeks
06 Oct, 2021 Zip is a command-line compression utility for files and directories. File and folder compression allows for quicker and more reliable file and folder transfer, storage, and email. Unzip, on the other hand, is a program that allows you to decompress files and directories. zip is used to compress the files to reduce file size and also used as a file package utility. zip is available in many operating systems like Unix, Linux, windows, etc. If you have limited bandwidth between two servers and want to transfer the files faster, then zip the files and transfer. The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command. The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command. Compression ratios of 2:1 to 3:1 are common for text files. zip has one compression method (deflation) and can also store files without compression. zip automatically chooses the better of the two for each file to be compressed. The program is useful for packaging a set of files for distribution; for archiving files; and for saving disk space by temporarily compressing unused files or directories. You can install Zip by running the below command: $ sudo apt-get install zip Installing Zip After installation, use the command to verify that the zip was installed correctly or not. $ zip Verify Zip installed properly Similarly, you can install Unzip by running the below command: $ sudo apt install unzip Installing Unzip After installation, use the command to verify the unzip was installed correctly or not. $ unzip Verify Unzip installed properly The zip and unzip utilities are already pre-installed in newer Linux distros like Ubuntu 20.04 and CentOS 8, so you’re good to go. how-to-install How To Installation Guide Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 25076, "s": 25048, "text": "\n06 Oct, 2021" }, { "code": null, "e": 25348, "s": 25076, "text": "Zip is a command-line compression utility for files and directories. File and folder compression allows for quicker and more reliable file and folder transfer, sto...
C program to insert a node at any position using double linked list
Linked lists use dynamic memory allocation and are collection of nodes. Nodes have two parts which are data and link. The types of linked lists in C programming language are as follows − Single / Singly linked lists. Double / Doubly linked lists. Circular single linked list. Circular double linked list. The diagram given below depicts the representation of double linked list. Following is the C program to insert a node at any position using double linked list − Live Demo #include <stdio.h> #include <stdlib.h> struct node { int num; struct node * preptr; struct node * nextptr; }*stnode, *ennode; void DlListcreation(int n); void DlLinsertNodeAtBeginning(int num); void DlLinsertNodeAtEnd(int num); void DlLinsertNodeAtAny(int num, int pos); void displayDlList(int a); int main(){ int n,num1,a,insPlc; stnode = NULL; ennode = NULL; printf("\n\n Doubly Linked List : Insert a node at any position :\n"); printf("-----------------------------------------------------------------------------------\n"); printf(" Input the number of nodes : "); scanf("%d", &n); DlListcreation(n); a=1; displayDlList(a); printf(" Input the position ( 1 to %d ) to insert a new node : ",n+1); scanf("%d", &insPlc); printf(" Input data for the position %d : ", insPlc); scanf("%d", &num1); DlLinsertNodeAtAny(num1,insPlc); a=2; displayDlList(a); return 0; } void DlListcreation(int n){ int i, num; struct node *fnNode; if(n >= 1){ stnode = (struct node *)malloc(sizeof(struct node)); if(stnode != NULL){ printf(" Input data for node 1 : "); // assigning data in the first node scanf("%d", &num); stnode->num = num; stnode->preptr = NULL; stnode->nextptr = NULL; ennode = stnode; for(i=2; i<=n; i++){ fnNode = (struct node *)malloc(sizeof(struct node)); if(fnNode != NULL){ printf(" Input data for node %d : ", i); scanf("%d", &num); fnNode->num = num; fnNode->preptr = ennode; fnNode->nextptr = NULL; ennode->nextptr = fnNode; ennode = fnNode; } else{ printf(" Memory can not be allocated."); break; } } } else{ printf(" Memory can not be allocated."); } } } void DlLinsertNodeAtAny(int num, int pos){ int i; struct node * newnode, *tmp; if(ennode == NULL){ printf(" No data found in the list!\n"); } else{ tmp = stnode; i=1; while(i<pos-1 && tmp!=NULL){ tmp = tmp->nextptr; i++; } if(pos == 1){ DlLinsertNodeAtBeginning(num); } else if(tmp == ennode){ DlLinsertNodeAtEnd(num); } else if(tmp!=NULL){ newnode = (struct node *)malloc(sizeof(struct node)); newnode->num = num; newnode->nextptr = tmp->nextptr; newnode->preptr = tmp; if(tmp->nextptr != NULL){ tmp->nextptr->preptr = newnode; // n+1th node is linking with new node } tmp->nextptr = newnode; // n-1th node is linking with new node } else{ printf(" The position you entered, is invalid.\n"); } } } void DlLinsertNodeAtBeginning(int num){ struct node * newnode; if(stnode == NULL){ printf(" No data found in the list!\n"); } else{ newnode = (struct node *)malloc(sizeof(struct node)); newnode->num = num; newnode->nextptr = stnode; newnode->preptr = NULL; stnode->preptr = newnode; stnode = newnode; } } void DlLinsertNodeAtEnd(int num){ struct node * newnode; if(ennode == NULL){ printf(" No data found in the list!\n"); } else{ newnode = (struct node *)malloc(sizeof(struct node)); newnode->num = num; newnode->nextptr = NULL; newnode->preptr = ennode; ennode->nextptr = newnode; ennode = newnode; } } void displayDlList(int m){ struct node * tmp; int n = 1; if(stnode == NULL) { printf(" No data found in the List yet."); } else{ tmp = stnode; if (m==1) { printf("\n Data entered in the list are :\n"); } else{ printf("\n After insertion the new list are :\n"); } while(tmp != NULL){ printf(" node %d : %d\n", n, tmp->num); n++; tmp = tmp->nextptr; // current pointer moves to the next node } } } When the above program is executed, it produces the following result − Doubly Linked List : Insert node at any position: ----------------------------------------------------------------------------------- Input the number of nodes : 5 Input data for node 1 : 23 Input data for node 2 : 12 Input data for node 3 : 11 Input data for node 4 : 34 Input data for node 5 : 10 Data entered in the list are : node 1 : 23 node 2 : 12 node 3 : 11 node 4 : 34 node 5 : 10 Input the position ( 1 to 6 ) to insert a new node : 5 Input data for the position 5 : 78 After insertion the new list are : node 1 : 23 node 2 : 12 node 3 : 11 node 4 : 34 node 5 : 78 node 6 : 10
[ { "code": null, "e": 1134, "s": 1062, "text": "Linked lists use dynamic memory allocation and are collection of nodes." }, { "code": null, "e": 1180, "s": 1134, "text": "Nodes have two parts which are data and link." }, { "code": null, "e": 1249, "s": 1180, "t...
Can we override a private or static method in Java
No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared. Let us see what happens when we try to override a private method − Live Demo class Parent { private void display() { System.out.println("Super class"); } } public class Example extends Parent { void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } } The output is as follows − Example.java:17: error: display() has private access in Parent obj.method(); ^ 1 error The program gives a compile time error showing that display() has private access in Parent class and hence cannot be overridden in the subclass Example. If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class. Let us see what happens when we try to override a static method in a subclass Live Demo class Parent { static void display() { System.out.println("Super class"); } } public class Example extends Parent { void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } } This generates a compile-time error. The output is as follows − Example.java:10: error: display() in Example cannot override display() in Parent void display() // trying to override display() ^ overridden method is static 1 error
[ { "code": null, "e": 1120, "s": 1062, "text": "No, we cannot override private or static methods in Java." }, { "code": null, "e": 1245, "s": 1120, "text": "Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared....
WebCam Motion Detector in Python - GeeksforGeeks
10 Nov, 2021 This python program will allow you to detect motion and also store the time interval of the motion. Requirement: Python3OpenCV(libraries)Pandas(libraries) Python3 OpenCV(libraries) Pandas(libraries) Install Requirements : Install Python3, install Pandas and OpenCV libraries. Main Logic : Videos can be treated as stack of pictures called frames. Here I am comparing different frames(pictures) to the first frame which should be static(No movements initially). We compare two images by comparing the intensity value of each pixels. In python we can do it easily as you can see in following code: Python3 # Python program to implement# Webcam Motion Detector # importing OpenCV, time and Pandas libraryimport cv2, time, pandas# importing datetime class from datetime libraryfrom datetime import datetime # Assigning our static_back to Nonestatic_back = None # List when any moving object appearmotion_list = [ None, None ] # Time of movementtime = [] # Initializing DataFrame, one column is start# time and other column is end timedf = pandas.DataFrame(columns = ["Start", "End"]) # Capturing videovideo = cv2.VideoCapture(0) # Infinite while loop to treat stack of image as videowhile True: # Reading frame(image) from video check, frame = video.read() # Initializing motion = 0(no motion) motion = 0 # Converting color image to gray_scale image gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Converting gray scale image to GaussianBlur # so that change can be find easily gray = cv2.GaussianBlur(gray, (21, 21), 0) # In first iteration we assign the value # of static_back to our first frame if static_back is None: static_back = gray continue # Difference between static background # and current frame(which is GaussianBlur) diff_frame = cv2.absdiff(static_back, gray) # If change in between static background and # current frame is greater than 30 it will show white color(255) thresh_frame = cv2.threshold(diff_frame, 30, 255, cv2.THRESH_BINARY)[1] thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2) # Finding contour of moving object cnts,_ = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in cnts: if cv2.contourArea(contour) < 10000: continue motion = 1 (x, y, w, h) = cv2.boundingRect(contour) # making green rectangle around the moving object cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) # Appending status of motion motion_list.append(motion) motion_list = motion_list[-2:] # Appending Start time of motion if motion_list[-1] == 1 and motion_list[-2] == 0: time.append(datetime.now()) # Appending End time of motion if motion_list[-1] == 0 and motion_list[-2] == 1: time.append(datetime.now()) # Displaying image in gray_scale cv2.imshow("Gray Frame", gray) # Displaying the difference in currentframe to # the staticframe(very first_frame) cv2.imshow("Difference Frame", diff_frame) # Displaying the black and white image in which if # intensity difference greater than 30 it will appear white cv2.imshow("Threshold Frame", thresh_frame) # Displaying color frame with contour of motion of object cv2.imshow("Color Frame", frame) key = cv2.waitKey(1) # if q entered whole process will stop if key == ord('q'): # if something is movingthen it append the end time of movement if motion == 1: time.append(datetime.now()) break # Appending time of motion in DataFramefor i in range(0, len(time), 2): df = df.append({"Start":time[i], "End":time[i + 1]}, ignore_index = True) # Creating a CSV file in which time of movements will be saveddf.to_csv("Time_of_movements.csv") video.release() # Destroying all the windowscv2.destroyAllWindows() Analysis of all windows After running the code there 4 new window will appear on screen. Let’s analyze it one by one: 1. Gray Frame : In Gray frame the image is a bit blur and in grayscale we did so because, In gray pictures there is only one intensity value whereas in RGB(Red, Green and Blue) image there are three intensity values. So it would be easy to calculate the intensity difference in grayscale. 2. Difference Frame : Difference frame shows the difference of intensities of first frame to the current frame. 3. Threshold Frame : If the intensity difference for a particular pixel is more than 30(in my case) then that pixel will be white and if the difference is less than 30 that pixel will be black 4. Color Frame : In this frame, you can see the color images in color frame along with green contour around the moving objects Time Record of movements The Time_of_movements file will be stored in the folder where your code file is stored. This file will be in csv extension. In this file the start time of motion and the end time of motion will be recorded. As you can see in picture: Video Demonstration nidhi_biet vineetkumargupta gabaa406 adnanirshad158 sagar0719kumar Image-Processing GBlog Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? 12 pip Commands For Python Developers What is web socket and how it is different from the HTTP? ML | Underfitting and Overfitting Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26407, "s": 26379, "text": "\n10 Nov, 2021" }, { "code": null, "e": 26507, "s": 26407, "text": "This python program will allow you to detect motion and also store the time interval of the motion." }, { "code": null, "e": 26521, "s": 26507, ...
Handling Big Volume of Petroleum Well Log Data with a Boosted Time-Efficiency on Python | by Yohanes Nuwara | Towards Data Science
This is a story of a geophysicist who has been already getting tired of handling the big volume of well log data with manual input in most commercial software out there. Who feels the same I feel? However, I successfully developed a way to get out of this tiring routine of manual input barely using programming skills with Python. Here I would like to share a tutorial with you. I will assume you are familiar with geology, geophysics, petroleum engineering, and all things related to geoscience. However, if you’re not familiar with it, it’s very OK, I’m very glad to introduce you to the daily activities we are working with. Python is, to be honest, a very flexible yet very powerful language for open-source computation. In the petroleum industry, well log data is a very valuable source of data to interpret the image of the subsurface deep down the earth and get more information about what is inside the rocks: if you’re lucky enough, you will find oil. Kidding anyway! The business of finding oil took so many years. The key is, time-efficiency. Being time-efficient, mainly during the stage of exploration, means a lot to the future of the business. When a field has been already producing for decades, well log data never comes in a single or little volume. It can be 50, 100, or even 500 oil and gas wells. It’s surely very huge because lots of wells have been drilled. One well log data contains measurement data of the rocks, for instance, density, sonic velocity, gamma-ray, resistivity, and countless more. Thus, in total, a big volume of 46 well data may take up about 120 MB! Well log data commonly comes in LAS format (the format which I will entirely use in this tutorial). To me personally, most commercial software that I knew so far has a time-efficiency limitation in the way we have to repeatedly and manually input all the detailed information about each well log data that we input. This can be tedious and cumbersome if we have a big volume of data. Imagine how much time we will spend just for manually input and check for the units of the data! Then I found using Python very engaging! Open your Python and firstly import the “three musketeers” of Python libraries; numpy, matplotlib, and pandas. The reason why I name them the “three musketeers” is that they just can’t stand alone since any basic computation in Python needs numpy and matplotlib, and data needs pandas. import numpy as npimport matplotlib.pyplot as pltimport pandas as pd Now go to your folder that contains your multiple well log data in LAS format. Copy the path of the folder, specify the path in Python, and paste the path on it. import syssys.path.append('...') Now is the fun part! You will read all the files. Import glob and import the files. import globimport osfile_path = "/content/drive/My Drive/Colab Notebooks/well_logs"read_files = glob.glob(os.path.join(file_path, "*.las"))read_files If it is successful, the path and file name of your multiple well log data will appear. If you read 100 well log data, it will appear as a very long list! Since you will be interested only the filenames (without the folder path) which is the well names, for instance from the example above, only 660810-B-1BH and not the entire /content/drive/My Drive/Colab Notebooks/well_logs/660810-B-1BH.las, you can sort the unwanted file path names out and you will get only the well names. well_names = []for files in read_files: files = os.path.splitext(os.path.basename(files))[0] well_names.append(files)print(well_names) This will give you the well names Investigate how much data you have. print(len(well_names)) For instance, you have 45 well data. Since Python starts indexing from 0, not from 1, it means the first well name 660810-B-1BH and the last well, are respectively called by: print(well_names[0])print(well_names[44]) # 45 wells minus one In Python and any programming language, you almost always call something by index. The formula of Python indexing is always: starts from zero, something minus one. Now you already have the well names, it’s time read all the LAS data. You will use a very specific library dedicated to read LAS files, called lasio. Lasio is one of the available brilliant libraries to read LAS files, in fact you may also build a program from scratch yourself! However, lasio is enough for time-efficiency. This is the most important point that I would like to highlight, that you are able to import all the files simultaneously, even 100 files at a click, an action that you can barely do using some commercial software. During the import process, you don’t need to focus on manually check and input the appropriate units. Time for acting! Install lasio first. I assume you may have been already very familiar with how to install a library. You may code a bit pip install, or a lot easier you may browse the libraries and import it in one of Python IDE called PyCharm. pip install lasio After being successfully installed, import it and write only 4 lines of code to read LAS files using lasio. But you have to be patient since it takes a relatively long time. The time it takes depends on how much well log data you import, however for estimation reading 50 well log will take no more than 30 seconds. lases = []for files in read_files: las = lasio.read(files) lases.append(las) The process of importing is in the same order as it reads the well names from start to end. During the process of importing, you may encounter a warning that says: In my experience, it is normal, so everything is OK. Congratulations! You have imported a very big volume of well log data in just no more than 5 minutes in total. It’s time to see what your data looks like. Please remember that in our previous discussion, well names can be called by index. For instance, we call the index 19. # type the numbers from 0 to max number of wells in the wellnames[...]find = well_names[19]# print the name of the searched wellprint("Well name:", find) If index 19 is called, it will print the name of the 20th well name. Please again remember the rule of thumb above: index is something minus one. The above code works just like a catalog. Now write the following code to see what’s inside the 20th well log data. id_ = np.int64(np.where(wellnames==find)).item()print("Data available:", lases[id_].keys())# check more detailsprint("Detail about data:")print(lases[id_].curves) It will print two things: the available measurement data in the well log, and the details (acronyms, units) of the well log data. It tells you what data is available. Here the data available are: DEPTH, TVD, TVDSS, GR, KLOGH, NPHI, PHIF, RHOB, SW, and VSH. What are these? These are the acronyms (or so-called mnemonic) for rock measurement types, for instance GR stands for Gamma Ray, KLOGH for permeability, NPHI for neutron porosity, RHOB for density, and SW for water saturation. Each of these measurements has specific units that you have to notice. This piece of information is very important, a lot more important than the content itself. This piece of information is what we see in the file header. Now finally comes the last part of our tutorial. We will be very desired to visualize the well log. Input the desired measurement type in the data_view variable. For instance, we are interested to see the density log or RHOB data. Input RHOB. We will use matplotlib. # peek or overviewing the well log# which data you want to see???data_view = 'RHOB' # input the measurement type which data you want # to seeprint("Data", data_view, "of well:", find)plt.figure(figsize=(5,10))plt.plot((lases[id_][data_view]), (lases[id_]['DEPTH']))plt.xlabel(data_view); plt.ylabel("Depth (m)")plt.grid(True)plt.gca().invert_yaxis() The visualization just prints out the following: Congratulations, this is the end of our tutorial! If you still crave for more beautiful visualization of the above well log data, I have a wonderful recipe! But since this tutorial does not cover on this matter, I will save it for later and write another tutorial if you are craving this. First of all, you have learned how to import multiple well log data files; 50, 100, 200 files, or more, in no more than 5 minutes. You have already beaten the average time you take to manually input in commercial software. Secondly, you have learned how to catalog the files by indexing the data. There are 50, 100, 200 well names that you surely don’t want to call name by name, therefore indexing is a better way. Last but not least, you have learned how to print out the details of the data (header) and visualize the data. In the long run, all I can say is that Python is very amazing for handling big data that beat the average time it takes to handle the same amount of data in common software. If you feel you can beat me in time by writing a more efficient code, contact me and please let me know! Reach my GitHub: github.com/yohanesnuwara Reach my email: ign.nuwara97@gmail.com Reach my LinkedIn: https://www.linkedin.com/in/yohanes-nuwara-5492b4118/
[ { "code": null, "e": 898, "s": 172, "text": "This is a story of a geophysicist who has been already getting tired of handling the big volume of well log data with manual input in most commercial software out there. Who feels the same I feel? However, I successfully developed a way to get out of this...
Convert tuple to float value in Python
When it is required to convert a tuple to a float value, the 'join' method, 'float' method, 'str' method and generator expression can be used. Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned. The 'float' method converts a given element to float data type. The 'str' method converts the given element into string data type. Below is a demonstration of the same − Live Demo my_tuple_1 = ( 7, 8) print ("The first tuple is : " ) print(my_tuple_1) my_result = float('.'.join(str(elem) for elem in my_tuple_1)) print("After converting the tuple to float, the tuple is : ") print(my_result) The first tuple is : (7, 8) After converting the tuple to float, the tuple is : 7.8 A tuple is defined and is displayed on the console. The '.' operator and 'join' method is used to join the two elements in the tuple as a decimal number. This result is assigned to a variable. It is displayed as output on the console.
[ { "code": null, "e": 1205, "s": 1062, "text": "When it is required to convert a tuple to a float value, the 'join' method, 'float' method, 'str' method and generator expression can be used." }, { "code": null, "e": 1468, "s": 1205, "text": "Generator is a simple way of creating i...
What is method overloading in C#?
Two or more than two methods having the same name but different parameters is what we call method overloading in C#. Method overloading in C# can be performed by changing the number of arguments and the data type of the arguments. Let’s say you have a function that prints multiplication of numbers, then our overloaded methods will have the same name but different number of arguments − public static int mulDisplay(int one, int two) { } public static int mulDisplay(int one, int two, int three) { } public static int mulDisplay(int one, int two, int three, int four) { } The following is an example showing how to implement method overloading − Live Demo using System; public class Demo { public static int mulDisplay(int one, int two) { return one * two; } public static int mulDisplay(int one, int two, int three) { return one * two * three; } public static int mulDisplay(int one, int two, int three, int four) { return one * two * three * four; } } public class Program { public static void Main() { Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15)); Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20)); Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7)); } } Multiplication of two numbers: 150 Multiplication of three numbers: 2080 Multiplication of four numbers: 1470
[ { "code": null, "e": 1179, "s": 1062, "text": "Two or more than two methods having the same name but different parameters is what we call method overloading in C#." }, { "code": null, "e": 1293, "s": 1179, "text": "Method overloading in C# can be performed by changing the number ...
Bootstrap - List Group
The purpose of list group component is to render complex and customized content in lists. To get a basic list group − Add the class .list-group to element <ul>. Add the class .list-group to element <ul>. Add class .list-group-item to <li>. Add class .list-group-item to <li>. The following example demonstrates this − <ul class = "list-group"> <li class = "list-group-item">Free Domain Name Registration</li> <li class = "list-group-item">Free Window Space hosting</li> <li class = "list-group-item">Number of Images</li> <li class = "list-group-item">24*7 support</li> <li class = "list-group-item">Renewal cost per year</li> </ul> Free Domain Name Registration Free Window Space hosting Number of Images 24*7 support Renewal cost per year We can add the badges component to any list group item and it will automatically be positioned on the right. Just add <span class = "badge"> within the <li> element. The following example demonstrates this − <ul class = "list-group"> <li class = "list-group-item">Free Domain Name Registration</li> <li class = "list-group-item">Free Window Space hosting</li> <li class = "list-group-item">Number of Images</li> <li class = "list-group-item"> <span class = "badge">New</span> 24*7 support </li> <li class = "list-group-item">Renewal cost per year</li> <li class = "list-group-item"> <span class = "badge">New</span> Disocunt Offer </li> </ul> Free Domain Name Registration Free Window Space hosting Number of Images New 24*7 support Renewal cost per year New Disocunt Offer By using the anchor tags instead of list items, we can link the list groups. We need to use <div> instead of <ul> element. The following example demonstrates this − <a href = "#" class = "list-group-item active"> Free Domain Name Registration </a> <a href = "#" class = "list-group-item">24*7 support</a> <a href = "#" class = "list-group-item">Free Window Space hosting</a> <a href = "#" class = "list-group-item">Number of Images</a> <a href = "#" class = "list-group-item">Renewal cost per year</a> We can add any HTML content to the above linked list groups. The following example demonstrates this − <div class = "list-group"> <a href = "#" class = "list-group-item active"> <h4 class = "list-group-item-heading"> Starter Website Package </h4> </a> <a href = "#" class = "list-group-item"> <h4 class = "list-group-item-heading"> Free Domain Name Registration </h4> <p class = "list-group-item-text"> You will get a free domain registration with website pages. </p> </a> <a href = "#" class = "list-group-item"> <h4 class = "list-group-item-heading"> 24*7 support </h4> <p class = "list-group-item-text"> We provide 24*7 support. </p> </a> </div> <div class = "list-group"> <a href = "#" class = "list-group-item active"> <h4 class = "list-group-item-heading"> Business Website Package </h4> </a> <a href = "#" class="list-group-item"> <h4 class = "list-group-item-heading"> Free Domain Name Registration </h4> <p class = "list-group-item-text"> You will get a free domain registration with website pages. </p> </a> <a href = "#" class = "list-group-item"> <h4 class = "list-group-item-heading">24*7 support</h4> <p class = "list-group-item-text">We provide 24*7 support.</p> </a> </div> You will get a free domain registration with website pages. We provide 24*7 support. You will get a free domain registration with website pages. We provide 24*7 support. 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": 3449, "s": 3331, "text": "The purpose of list group component is to render complex and customized content in lists. To get a basic list group −" }, { "code": null, "e": 3492, "s": 3449, "text": "Add the class .list-group to element <ul>." }, { "code":...
Which Of Your Features Are Overfitting? | by Samuele Mazzanti | Towards Data Science
What matters most in machine learning is making good predictions on new data. When predictions are good on training data but bad on test data, it is said that the model is “overfitting”. It means that the model has learnt too many noisy patterns from training data, and so it’s unable to generalize well to data it has not seen before. Who’s to blame for overfitting? In other words, Which are the features (dataset’s columns) that prevent the model from generalizing well on new data? In this article — with the aid of a real-world dataset — we will see an advanced method to answer this question. If your answer to the question above was “I would look at feature importance”, try harder. Feature importance says nothing about how the features will perform on new data. In fact, it is just a proxy of what the model has learnt during the training phase. If the model has learnt many patterns about feature ‘Age’, then this feature will rank high in feature importance. This doesn’t say anything about whether those patterns are correct or not (by “correct”, I mean a pattern that is general enough to hold true also on new data). So, we will need a different approach to solve the problem. In order to explain the approach, I will use a dataset containing records from the German health registry from 1984 to 1988 (the dataset is accessible from the library Pydataset, under the MIT license). Downloading the data is as simple as: import pydatasetX = pydataset.data('rwm5yr')y = (X['hospvis'] > 1).astype(int)X = X.drop('hospvis', axis = 1) This dataset consists of 19,609 rows, where each row contains some information about a patient for a given year. Note that patients are observed across different years, so the same patient may be found in different rows of the dataframe. The target variable is: `hospvis`: whether the patient has been more than 1 day in hospital during the corresponding year. We dispose of 16 columns: `id`: patient ID (1-7028);`docvis`: number of visits to doctor during year (0-121);`year`: year (1984-1988);`edlevel`: educational level (1-4);`age`: age (25-64);`outwork`: 1 if out of work, 0 else;`female`: 1 if female, 0 else;`married`: 1 if married, 0 else;`kids`: 1 if has children, 0 else;`hhninc`: household yearly income in marks (in Marks);`educ`: years of formal education (7-18);`self`: 1 if self-employed, 0 else;`edlevel1`: 1 if less than high school graduate, 0 else;`edlevel2`: 1 if high school graduate, 0 else;`edlevel3`: 1 if university/college, 0 else;`edlevel4`: 1 if graduate school, 0 else. `id`: patient ID (1-7028); `docvis`: number of visits to doctor during year (0-121); `year`: year (1984-1988); `edlevel`: educational level (1-4); `age`: age (25-64); `outwork`: 1 if out of work, 0 else; `female`: 1 if female, 0 else; `married`: 1 if married, 0 else; `kids`: 1 if has children, 0 else; `hhninc`: household yearly income in marks (in Marks); `educ`: years of formal education (7-18); `self`: 1 if self-employed, 0 else; `edlevel1`: 1 if less than high school graduate, 0 else; `edlevel2`: 1 if high school graduate, 0 else; `edlevel3`: 1 if university/college, 0 else; `edlevel4`: 1 if graduate school, 0 else. Let’s split the data into a training and a test set. There are more sophisticated ways to do that, such as cross-validation, but let’s keep things simple. Since this is an experiment, we will (naively) treat all of the columns as numeric features. from sklearn.model_selection import train_test_splitfrom catboost import CatBoostClassifierX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = .2, stratify = y)cat = CatBoostClassifier(silent = True).fit(X_train, y_train) Once the model is trained, let’s give a look at feature importance: import pandas as pdfimpo = pd.Series(cat.feature_importances_, index = X_train.columns) Not surprisingly, `docvis` — the number of visits to a doctor — is important in predicting whether the patient has spent more than 1 day in hospital. Also `age` and `hhninc` (income) are somewhat obvious. But the fact that the patient’s id ranks 2nd in importance should make us suspicious, especially because we have treated it as a numeric feature. Now, let’s calculate the model performance (area under ROC) both on the training set and on the test set. from sklearn.metrics import roc_auc_scoreroc_train = roc_auc_score(y_train, cat.predict_proba(X_train)[:, 1])roc_test = roc_auc_score(y_test, cat.predict_proba(X_test)[:, 1]) It’s a huge difference! This is an indication of strong overfitting. But which features are “responsible” for that? We have many metrics to measure how a model performs on some data. But how do we measure how a feature performs on some data? The most powerful tool to do that is called “SHAP values”. In general, to efficiently compute SHAP values for any predictive model, you can use the dedicated Python library. In this example, however, we will take advantage of Catboost’s native method: from catboost import Poolshap_train = pd.DataFrame( data = cat.get_feature_importance( data = Pool(X_train), type = 'ShapValues')[:, :-1], index = X_train.index, columns = X_train.columns)shap_test = pd.DataFrame( data = cat.get_feature_importance( data = Pool(X_test), type = 'ShapValues')[:, :-1], index = X_test.index, columns = X_test.columns) If you take a look at shap_train and shap_test, you will notice that they are the same shape of the respective datasets. If you want to know more about SHAP values and how they work, you can start from here and here. But — for our purpose — all you need to know is that SHAP values give you an idea of the impact of each single feature on the final prediction made by a model, on one or more observations. Let’s see a couple of examples: Patient at row 12071 has had 0 visits. The corresponding SHAP value (-0.753) tells us that this piece of information lowers by -0.753 the probability (actually the log-odds) that he has been more than 1 day in hospital. On the contrary, patient at row 18650 has been 4 times to a doctor, this raises by 0.918 the log-odds that she has been more than 1 day in hospital. Intuitively, a good proxy of the performance of a feature on a dataset is the correlation between the SHAP values of the feature and the target variable. In fact, if the model has found good patterns on a feature, the SHAP values of that feature must be highly positively correlated with the target variable. For example, if we wish to calculate the correlation between the feature `docvis` and the target variable on the observations contained in the test set: np.corrcoef(shap_test['docvis'], y_test) However, SHAP values are additive, meaning that the final prediction is the sum of the SHAPs of all the features. So it makes more sense if we remove the effect of other features before calculating the correlation. This is exactly the definition of “partial correlation”. A convenient implementation of partial correlation is contained in the Python library Pingouin: import pingouinpingouin.partial_corr( data = pd.concat([shap_test, y_test], axis = 1).astype(float), x = 'docvis', y = y_test.name, x_covar = [feature for feature in shap_test.columns if feature != 'docvis'] ) This snippet of code means “calculate the correlation between SHAP values of feature `docvis` and the target variable on the observations of the test set, after removing the effect of all the other features”. Since everybody needs a name, I will call this formula “ParShap” (from “Partial correlation of Shap values”). We can repeat this procedure for each feature, both on train set and test set: parshap_train = partial_correlation(shap_train, y_train)parshap_test = partial_correlation(shap_test, y_test) Note: you can find the definition of the function partial_correlation at the end of this article. Now, let’s plot parshap_train on the x-axis and parshap_test on the y-axis. plt.scatter(parshap_train, parshap_test) If a feature lies on the bisector, it means it performs exactly the same on train set and on test set. It’s the ideal situation, when there is neither overfitting nor underfitting. On the contrary, if a feature lies below the bisector, it means it has performed worse on test set than it did on training set. This is the overfitting area. Visually, it’s immediately apparent which features are underperforming: I have circled them in blue. Therefore, the arithmetic difference between parshap_test and parshap_train (which equals the vertical distance between each feature and the bisector) gives us a measure of how much the feature is overfitting, for our model. parshap_diff = parshap_test — parshap_train How should we interpret this output? Based on what we have said above, the more negative this score, the more overfitting is brought by the feature. It’s fine: you don’t have to! Can you figure out a way to check whether the intuition behind this article is correct? In logic, if we remove the “overfitting features” from the dataset, we should be able to reduce the overfitting (namely, the distance between roc_train and roc_test). So let’s try to drop one feature at a time and see how the area under ROC changes. On the left, we are removing one feature at a time, sorted by feature importance. So, first the least important (`edlevel4`) is removed, then the two least important (`edlevel4` and `edlevel1`) are removed, and so on. On the right, we are following the same process, but the order of removal is given by ParShap. So, first the most negative ParShap (`id`) is removed, then the two most negative ParShap (`id` and `year`) are removed, and so on. As we had hoped, dropping features with most negative ParShap has led to a strong decrease in overfitting. In fact, roc_train is getting closer and closer to roc_test. Note that this was only a test to check the correctness of our line of reasoning. In general, ParShap should not be used as a method for feature selection. Indeed, the fact that some features are prone to overfitting does not imply that those features don’t carry useful information at all! (For instance, income and age, in this example). However, ParShap proves extremely helpful in giving us hints on how to debug our model. In fact, it allows us to focus the attention on those features that require some more feature engineering or regularization. Full code used for this article (you may obtain slightly different results due to random seed): # Import librariesimport pandas as pdimport pydatasetfrom sklearn.model_selection import train_test_splitfrom catboost import CatBoostClassifier, Poolfrom sklearn.metrics import roc_auc_scorefrom pingouin import partial_corrimport matplotlib.pyplot as plt# Print documentation and read dataprint('################# Print docs')pydataset.data('rwm5yr', show_doc = True)X = pydataset.data('rwm5yr')y = (X['hospvis'] > 1).astype(int)X = X.drop('hospvis', axis = 1)# Split data in train + testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .2, stratify = y)# Fit modelcat = CatBoostClassifier(silent = True).fit(X_train, y_train)# Show feature importancefimpo = pd.Series(cat.feature_importances_, index = X_train.columns)fig, ax = plt.subplots()fimpo.sort_values().plot.barh(ax = ax)fig.savefig('fimpo.png', dpi = 200, bbox_inches="tight")fig.show()# Compute metricsroc_train = roc_auc_score(y_train, cat.predict_proba(X_train)[:, 1])roc_test = roc_auc_score(y_test, cat.predict_proba(X_test)[:, 1])print('\n################# Print roc')print('roc_auc train: {:.2f}'.format(roc_train))print('roc_auc test: {:.2f}'.format(roc_test))# Compute SHAP values shap_train = pd.DataFrame( data = cat.get_feature_importance(data = Pool(X_train), type = 'ShapValues')[:, :-1], index = X_train.index, columns = X_train.columns)shap_test = pd.DataFrame( data = cat.get_feature_importance(data = Pool(X_test), type = 'ShapValues')[:, :-1], index = X_test.index, columns = X_test.columns)print('\n################# Print df shapes')print(f'X_train.shape: {X_train.shape}')print(f'X_test.shape: {X_test.shape}\n')print(f'shap_train.shape: {shap_train.shape}')print(f'shap_test.shape: {shap_test.shape}')print('\n################# Print data and SHAP')print('Original data:')display(X_test.head(3))print('\nCorresponding SHAP values:')display(shap_test.head(3).round(3))# Define function for partial correlationdef partial_correlation(X, y): out = pd.Series(index = X.columns, dtype = float) for feature_name in X.columns: out[feature_name] = partial_corr( data = pd.concat([X, y], axis = 1).astype(float), x = feature_name, y = y.name, x_covar = [f for f in X.columns if f != feature_name] ).loc['pearson', 'r'] return out# Compute ParShapparshap_train = partial_correlation(shap_train, y_train)parshap_test = partial_correlation(shap_test, y_test)parshap_diff = pd.Series(parshap_test - parshap_train, name = 'parshap_diff')print('\n################# Print parshap_diff')print(parshap_diff.sort_values()) # Plot parshapplotmin, plotmax = min(parshap_train.min(), parshap_test.min()), max(parshap_train.max(), parshap_test.max())plotbuffer = .05 * (plotmax - plotmin)fig, ax = plt.subplots()if plotmin < 0: ax.vlines(0, plotmin - plotbuffer, plotmax + plotbuffer, color = 'darkgrey', zorder = 0) ax.hlines(0, plotmin - plotbuffer, plotmax + plotbuffer, color = 'darkgrey', zorder = 0)ax.plot( [plotmin - plotbuffer, plotmax + plotbuffer], [plotmin - plotbuffer, plotmax + plotbuffer], color = 'darkgrey', zorder = 0)sc = ax.scatter( parshap_train, parshap_test, edgecolor = 'grey', c = fimpo, s = 50, cmap = plt.cm.get_cmap('Reds'), vmin = 0, vmax = fimpo.max())ax.set(title = 'Partial correlation bw SHAP and target...', xlabel = '... on Train data', ylabel = '... on Test data')cbar = fig.colorbar(sc)cbar.set_ticks([])for txt in parshap_train.index: ax.annotate(txt, (parshap_train[txt], parshap_test[txt] + plotbuffer / 2), ha = 'center', va = 'bottom')fig.savefig('parshap.png', dpi = 300, bbox_inches="tight")fig.show()# Feature selectionn_drop_max = 5iterations = 4features = {'parshap': parshap_diff, 'fimpo': fimpo}features_dropped = {}roc_auc_scores = { 'fimpo': {'train': pd.DataFrame(), 'test': pd.DataFrame()}, 'parshap': {'train': pd.DataFrame(), 'test': pd.DataFrame()}}for type_ in ['parshap', 'fimpo']: for n_drop in range(n_drop_max + 1): features_drop = features[type_].sort_values().head(n_drop).index.to_list() features_dropped[type_] = features_drop X_drop = X.drop(features_drop, axis = 1) for i in range(iterations): X_train, X_test, y_train, y_test = train_test_split(X_drop, y, test_size = .2, stratify = y) cat = CatBoostClassifier(silent = True).fit(X_train, y_train) roc_auc_scores[type_]['train'].loc[n_drop, i] = roc_auc_score(y_train, cat.predict_proba(X_train)[:, 1]) roc_auc_scores[type_]['test'].loc[n_drop, i] = roc_auc_score(y_test, cat.predict_proba(X_test)[:, 1]) # Plot feature selectionfig, axs = plt.subplots(1, 2, sharey = True, figsize = (8, 3))plt.subplots_adjust(wspace = .1)axs[0].plot(roc_auc_scores['fimpo']['train'].index, roc_auc_scores['fimpo']['train'].mean(axis = 1), lw = 3, label = 'Train')axs[0].plot(roc_auc_scores['fimpo']['test'].index, roc_auc_scores['fimpo']['test'].mean(axis = 1), lw = 3, label = 'Test')axs[0].set_xticks(roc_auc_scores['fimpo']['train'].index)axs[0].set_xticklabels([''] + features_dropped['fimpo'], rotation = 90)axs[0].set_title('Feature Importance')axs[0].set_xlabel('Feature dropped')axs[0].grid()axs[0].legend(loc = 'center left')axs[0].set(ylabel = 'ROC-AUC score')axs[1].plot(roc_auc_scores['parshap']['train'].index, roc_auc_scores['parshap']['train'].mean(axis = 1), lw = 3, label = 'Train')axs[1].plot(roc_auc_scores['parshap']['test'].index, roc_auc_scores['parshap']['test'].mean(axis = 1), lw = 3, label = 'Test')axs[1].set_xticks(roc_auc_scores['parshap']['train'].index)axs[1].set_xticklabels([''] + features_dropped['parshap'], rotation = 90)axs[1].set_title('ParShap')axs[1].set_xlabel('Feature dropped')axs[1].grid()axs[1].legend(loc = 'center left')fig.savefig('feature_selection.png', dpi = 300, bbox_inches="tight")fig.show() Thank you for reading! I hope you enjoyed this article. If you’d like, add me on Linkedin!
[ { "code": null, "e": 249, "s": 171, "text": "What matters most in machine learning is making good predictions on new data." }, { "code": null, "e": 507, "s": 249, "text": "When predictions are good on training data but bad on test data, it is said that the model is “overfitting”....
Build your first ML integrated ChatBot on DialogFlow! | by Chayan Kathuria | Towards Data Science
Your first Machine Learning integrated chat bot on Google’s DialogFlow in 4 steps! Any Machine Learning model is pretty much useless unless you put it to some real life use. Running the model on Jupyter Notebook and bragging about 99.99% accuracy doesn’t help. You need to make an end-to-end application out of it to present it to the outer world. And chatbots are one fun and easy way to do that. Building chatbots has never been so easy. Google’s DialogFlow is an obvious choice as it’s extremely simple, fast and free! Before proceeding, try out the app for yourself first here! Now that you’ve tried it, coming to building the complete application, we’d be going over below steps: Your Machine Learning Model (Iris, in this case)The DialogFlow Chatbot which fetches inputs from userA Flask app deployed on any public host which renders the request and responseA webhook call which your chatbot makes to the flask api to send the data and fetch the resultIntegrating DialogFlow with Telegram Your Machine Learning Model (Iris, in this case) The DialogFlow Chatbot which fetches inputs from user A Flask app deployed on any public host which renders the request and response A webhook call which your chatbot makes to the flask api to send the data and fetch the result Integrating DialogFlow with Telegram We’ll go over each step one by one. Let’s first take a look at how the architecture of our complete app will look: So the user has access to the Telegram chatbot which we will be built on DialogFlow and integrate with Telegram later. The conversation starts and the chatbot prompts the user to input the Data, which are the flower dimensions (Petal length, Petal width, Sepal length and Sepal width). Once the chatbot receives the last input, it will trigger a webhook call to the flask API which will be deployed on a public host. This flask API consists of our app which will retrieve the 4 data points and fit that to our Machine Learning model and then reply back to the chatbot with the prediction. You can find the complete code at my Github. Now let’s go over each step! First, let’s build a basic ML model which take Iris dimensions and predicts the Iris type. No rocket science here. Just a very basic model which renders result with decent accuracy. Below is the bare-bones code to that quickly. #Load datairis = load_iris() X = iris.data y = iris.target#Train test splitX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.25)#Define and fit to the modelclf = RandomForestClassifier(n_estimators=10)clf.fit(X_train, y_train)predicted = clf.predict(X_test)print(accuracy_score(predicted, y_test))print(clf.predict(X_test))#Save the model as Pickleimport picklewith open(r'rf.pkl','wb') as model_pkl: pickle.dump(clf, model_pkl, protocol=2) We just load the data and fit it to Random Forest classifier. No need of cleaning the data as the dataset is already clean extremely small. I am not diving into any optimization here just to avoid complexity as our main aim is not the model accuracy but the complete application. Then just pickle the model and later this model, ‘rf.pkl’, will then be loaded in our flask app. Now let’s dive straight into DialogFlow to make our chatbot. You can use other APIs and frameworks as well to build a chatbot but Google’s DialogFlow is an obvious choice as its easy, free and super quick to build! Go to DialogFlow and sign in with your Google account. Then click on ‘Create Agent’ to create your chatbot. Next, we need to create an intent which will ask the user for data and make a webhook call. Let’s first edit the Default Welcome Intent to make it ask for a ‘Yes’ or ‘No’ from a user. Now as soon as the user types ‘Yes’, DialogFlow should call another intent which will ask the user for inputs and store the data points in ‘Entities’. Here we are dealing with simple random numbers so we don’t need to create our custom Entities. DialogFlow has default Entities in place to handle such data. So we need to create a ‘Yes- FollowUp Intent’ for this intent because that intent will be called after a positive reply from the user. Click on ‘Add follow-up intent’ > ‘Yes’. You can rename this intent to something else if you want. I will rename this to ‘IrisData’. Now we need to add the entities, which will hold the data received from the user. We will just use the default @sys.number entity here for all the 4 inputs. Make 4 different parameters for the 4 data points needed from user — Petal Length, Petal Width, Sepal Length, Sepal Width. Make sure to add the prompts as well to ask the user for inputs separately. Train the model with a few inputs so that it knows what to expect. You can test the chatbot now on the right panel to check if it is performing accordingly. Once done, you’ll need to enable fulfillment by ‘Enable webhook call for this intent’. By doing this, this particular intent will make a webhook call to our app deployed on public host, which is Heroku. We now need to build the flask app and deploy it on Heroku and then put the URL in the ‘Fulfillment’ tab which is available on the left side. We now need to build our flask app which gets the webhook call from our chatbot, retrieves the data, then fits to the ML model (rf.pkl) and returns back the fulfillment text to DialogFlow with the prediction. Below is the code: # Importing necessary librariesimport numpy as npfrom flask import Flask, request, make_responseimport jsonimport picklefrom flask_cors import cross_origin# Declaring the flask appapp = Flask(__name__)#Loading the model from pickle filemodel = pickle.load(open('rf.pkl', 'rb'))# geting and sending response to dialogflow@app.route('/webhook', methods=['POST'])@cross_origin()def webhook(): req = request.get_json(silent=True, force=True) res = processRequest(req) res = json.dumps(res, indent=4) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r Once this is done, we need to process the fulfillment request from DialogFlow which is in JSON format to retrieve data. The fulfillment request looks something like this: So we need to get into ‘queryResult’ >> ‘parameters’ >> ‘number’, ‘number1’, ‘number2’, ‘number4’. Once retrieved, we will dump these data points into an array and slam it to our model and get the prediction. # processing the request from dialogflowdef processRequest(req): result = req.get("queryResult") #Fetching the data points parameters = result.get("parameters") Petal_length=parameters.get("number") Petal_width = parameters.get("number1") Sepal_length=parameters.get("number2") Sepal_width=parameters.get("number3") int_features = [Petal_length,Petal_width,Sepal_length,Sepal_width] #Dumping the data into an array final_features = [np.array(int_features)] #Getting the intent which has fullfilment enabled intent = result.get("intent").get('displayName') #Fitting out model with the data points if (intent=='IrisData'): prediction = model.predict(final_features) output = round(prediction[0], 2) if(output==0): flowr = 'Setosa' if(output==1): flowr = 'Versicolour' if(output==2): flowr = 'Virginica' #Returning back the fullfilment text back to DialogFlow fulfillmentText= "The Iris type seems to be.. {} !".format(flowr) #log.write_log(sessionID, "Bot Says: "+fulfillmentText) return { "fulfillmentText": fulfillmentText }if __name__ == '__main__': app.run() Once this is done, we just need to deploy the code on the public host. I have chosen Heroku as again, it is easy, free and super quick! You just need to add below files to your new Github repository: the flask app, the model pickle file, a Procfile (this is very essential and helps Heroku locate the flask app), and a requirements text file which tells Heroku which all libraries and versions to pre-install to run the app correctly. Just make a repository on your Github and go to Heroku. Create a ‘New App’ and ‘Connect’ your Github repository there. Once connected, just hit the deploy button and you are done! On to the final step now. We now need to connect our deployed app to our chatbot. Just enter the URL on which your app is deployed and add ‘/webhook’ to it. Remember from the flask code above that the app is routed to ‘/webhook’. Just go to the ‘Fulfillment’ tab on the left panel in DialogFlow, enable ‘Webhook’ and just add the <your_app’s_URL>/webhook. And we are done! (Don’t forget to click on save button!) You can test on the right panel by initiating a chat to test if the webhook request/response is working fine. You should get the fulfillment response back with the prediction. Coming to the final step. Nothing much to do here as integrating web apps with DialogFlow is very easy. We first need to go to Telegram to generate a dummy bot there and generate its token. Search for ‘BotFather’ and click on ‘new bot’. It will ask you for the bot name. Enter any name as you wish. It will then prompt you to enter a username. After you have done that, a token and a link for your bot will be generated there. Just copy that token and go to DialogFlow ‘Integrations’ panel on the left. Enable Telegram there, paste the token you just generated and click on start. That’s it! Now just head on to the Telegram bot link and try out the app!
[ { "code": null, "e": 254, "s": 171, "text": "Your first Machine Learning integrated chat bot on Google’s DialogFlow in 4 steps!" }, { "code": null, "e": 569, "s": 254, "text": "Any Machine Learning model is pretty much useless unless you put it to some real life use. Running the ...
abs() function for complex number in c++ - GeeksforGeeks
10 Oct, 2018 The abs() function for complex number is defined in the complex header file. This function is used to return the absolute value of the complex number z. Syntax: template<class T> T abs (const complex<T>& z); Parameter: z: It represents the given complex number. Return: It returns the absolute value of the complex number. Below programs illustrate the above function:- Example 1:- // C++ program to demonstrate// example of abs() function. #include <bits/stdc++.h>using namespace std; // driver functionint main (){ // defines the complex number: (5.0+12.0i) complex<double> complexnumber (5.0, 12.0); // prints the absolute value of the complex number cout << "The absolute value of " << complexnumber << " is: "; cout << abs(complexnumber) << endl; return 0;} The absolute value of (5,12) is: 13 Example 2:- // C++ program to demonstrate// example of abs() function. #include <bits/stdc++.h>using namespace std; // driver functionint main (){ // defines the complex number: (4.0+3.0i) complex<double> complexnumber (4.0, 3.0); // prints the absolute value of the complex number cout << "The absolute value of " << complexnumber << " is: "; cout << abs(complexnumber) << endl; return 0;} The absolute value of (4,3) is: 5 C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to implement Singly Linked List in C++ using class Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Difference between user defined function and library function in C/C++ Handling the Divide by Zero Exception in C++ Different ways to print elements of vector Dynamic _Cast in C++ Count substrings that contain all vowels | SET 2 Base class pointer pointing to derived class object
[ { "code": null, "e": 24448, "s": 24420, "text": "\n10 Oct, 2018" }, { "code": null, "e": 24601, "s": 24448, "text": "The abs() function for complex number is defined in the complex header file. This function is used to return the absolute value of the complex number z." }, { ...
What is Poisson Distribution? When to use it? How to predict football match results? | Towards Data Science
Understanding the dataset, performing appropriate preprocessing operations, and interpreting the results are essential for training the machine in the light of more accurate data. For example, if we consider dimensionality reduction, the type of dimensionality reduction method (linear or nonlinear) is applied depending on the structure of the dataset. Distribution types are also one of the most important approaches for reading, understanding, and making inferences about the dataset. This article explains the probability of teams scoring goals against each other by using the Poisson Distribution and 2019–2020 Turkish Football League dataset, which is always memoryless, with the Poisson distribution. This article explains in-depth the Poisson distribution and models the probability of Galatasaray and Fenerbahçe scoring each other using the Poisson Distribution based on the real dataset of the 2019–2020 Turkish Football League. Table of Contents1. What is Poisson Distribution?1.1. How can we decide whether is a poisson distribution?1.2. Examples1.3. Real Applications2. Predicting Football Match Result3. References In its shortest form, the distribution of the number of independent events occurring in a certain interval (this interval can be time, distance, area, volume, etc.) is the Poisson distribution. For example, the number of accidents at a certain junction in 24 hours, chickens in a square meter plot of land, the number of fires in X region in 3 months, etc. Before continuing with these examples, let’s take a look at the theoretical background of the subject: where λ= mean number of occurrences at a certain interval e = Euler constant x = the number of events of which probability is desired Events occur randomly and independently in Poisson Distribution. Events occur in a specific range. To model with a Poisson Distribution, distribution should be given according to the count of events. For example, the average weight of people crossing the street in a 10-minute period is not the Poisson distribution, but the number of people who are >x kg can be modeled with the Poisson distribution. Looking at the 2 graphs in Figure 1 and the red square randomly placed: In the graph on the left, it is seen that while the number of events (data points) in the square is 0 in some places, it is 15–20 in some other places. This indicates that the data is not independently distributed but grouped with certain conditions, If the events (data points) are distributed randomly, independently and at the same theoretical rate across the entire plot then it does not make sense to get 15–20 events in a square if we get 0 events at another square. So, it cannot be modeled with the Poisson distribution. When the red square is applied to different parts of the graph on the right, the number of events (data points) in the square will be close to each other. This can be modeled with the Poisson distribution compared to the other. Here, what is modeled with Poisson is not the dataset at hand, but the numbers of events (data points) in the frames applied to the dataset. Let’s solve some basic problems to dive into the topic. 1- One nanogram of Uranium-234 has an average of 4.6 radioactive decays per second and let’s calculate the probability of 3 radioactive decays per second based on the Poisson distribution. Lambda = 4.6 X=3 and the following code block solves the equation: The probabilities of values are shown in Figure 2 and if 4.6 radioactive decays per second, the probability of 3 radioactive decays 16%, and the other probabilities of other values are shown. 2- An average of 12 people visits a museum in 30 minutes. What is the probability that no new people will come to this museum in any 5 minutes? If an average of 12 people visit in 30 minutes, then an average of 2 people will visit in 5 minutes, so lambda = 2; If the X value, that is, the probability, is the desired value, it is 0. The following code block solves this problem without using the Poisson distribution library: In Figure 3, the probability of visiting up to 10 people is shown. The probability of no new visitors in 5 minutes is 13.53%. The following list includes the real applications of the Poisson distribution: The study aims to determine the probability of the number of goals scored by the teams when Galatasaray is home and Fenerbahçe is away (GS vs FB). In this context, the following dataset containing all match results in the Turkish league between 1959–2021 was used. To find the probability of the number of goals they will score each other in the match where Galatasaray is home and Fenerbahçe is away, it has been studied the 2019–2020 season as seen in the code block below: The dataset (license:CC0: Public Domain) can be accessed from the link In the first part, by choosing the 2019–2020 season with the dataset imported; home, away, home goal score, and away goal score columns are selected.In the second part, the total and the average number of goals scored by the home and away teams in the 2019–2020 season are calculated. There are a total of 18 teams in the league and 18*17 = 306 matches were played during the season, the total number of goals scored by the home teams was 493 (average: 1.611), while the total number of goals scored by the away teams was 382 (average 1.248).In the third section, the total goals scored and conceded by Galatasaray in the home matches and the average goal values ​​were calculated. Galatasaray scored 32 goals (average: 1.882) in 17 home matches and conceded 15 goals (average: 0.882).In the fourth section, the total goals scored and conceded by Fenerbahçe in the away matches and the average number of goals were calculated. The goal scored by the home team in Fenerbahce’s 17 away matches, which means Fenerbahce’s number of goals conceded is 24 goals (average of 1.412), while Fenerbahce’s number of goals scored is 17 (average 1.00).In the fifth section, the values ​​collected in the previous section were compiled and tabulated. (Figure 5) In the first part, by choosing the 2019–2020 season with the dataset imported; home, away, home goal score, and away goal score columns are selected. In the second part, the total and the average number of goals scored by the home and away teams in the 2019–2020 season are calculated. There are a total of 18 teams in the league and 18*17 = 306 matches were played during the season, the total number of goals scored by the home teams was 493 (average: 1.611), while the total number of goals scored by the away teams was 382 (average 1.248). In the third section, the total goals scored and conceded by Galatasaray in the home matches and the average goal values ​​were calculated. Galatasaray scored 32 goals (average: 1.882) in 17 home matches and conceded 15 goals (average: 0.882). In the fourth section, the total goals scored and conceded by Fenerbahçe in the away matches and the average number of goals were calculated. The goal scored by the home team in Fenerbahce’s 17 away matches, which means Fenerbahce’s number of goals conceded is 24 goals (average of 1.412), while Fenerbahce’s number of goals scored is 17 (average 1.00). In the fifth section, the values ​​collected in the previous section were compiled and tabulated. (Figure 5) 6. In the sixth section, the attack and defense powers of Galatasaray(home) and Fenerbahçe(away) are calculated as follows: Galatasaray attack power: The average of goals scored in the matches where Galatasaray is home / league home average Fenerbahce attack power: The average of goals scored in the matches where Fenerbahce is away / league away average Galatasaray defense power: The average of goals conceded by Galatasaray where Galatasaray is home / league away average Fenerbahce defense power: The average of goals conceded by Fenerbahçe in away matches / league home average This part can optionally be calculated using different mathematical operators. 7. In the seventh section, the average number of goals that Galatasaray will score against Fenerbahçe when it is home and the average number of goals that Fenerbahçe will score against Galatasaray when it is away are calculated by using the attack and defense powers of the teams obtained in the sixth section. (GS 1.649–0.707 FB) Of course, since the result of the match is not likely to end 1.649–0.707, the distribution of these average values ​​with the Poisson distribution has been obtained in the following sections: 8. In the eighth episode, the probability of goals that Galatasaray will score against Fenerbahçe is shown in Figure-6. The highest probability of Galatasaray against Fenerbahce scoring is 1 goal (31.7%) and the second one is the 2 goals with 26.14% 9. In the ninth section, the probability of goals that Fenerbahçe will score against Galatasaray is shown in Figure-7. The highest probability of Galatasaray against Fenerbahce scoring is 0 goal (49.32%), which means Galatasaray has a 49.32% chance of not conceding a goal. The second one is the 1 goal with 34.86%. [1] J. Letkowski, “Applications of the Poisson probability distribution.”
[ { "code": null, "e": 1112, "s": 172, "text": "Understanding the dataset, performing appropriate preprocessing operations, and interpreting the results are essential for training the machine in the light of more accurate data. For example, if we consider dimensionality reduction, the type of dimensio...
What is APP_BASE_HREF in Angular 10 ?
13 Apr, 2021 In this article, we are going to see what is APP_BASE_HREF in Angular 10 and how to use it. APP_BASE_HREF returns a predefined DI token for the base href of the current page. The APP_BASE_HREF is the URL prefix that should be preserved. Syntax: provide: APP_BASE_HREF, useValue: '/gfgapp' Approach: In app.module.ts and APP_BASE_HREF in providers with useValue. In app.component.ts store APP_BASE_HREF into any variable and use it. Example 1: app.module.ts Javascript import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import {APP_BASE_HREF} from '@angular/common'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ {provide: APP_BASE_HREF, useValue: '/gfgapp'} ], bootstrap: [AppComponent]})export class AppModule { } app.component.ts Javascript import { Component, Inject } from '@angular/core';import {APP_BASE_HREF} from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'demo1'; constructor(@Inject(APP_BASE_HREF) private baseHref:string) { var a = this.baseHref; console.log(a, " is base HREF") } } Output: AngularJS-Questions AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to setup 404 page in angular routing ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 120, "s": 28, "text": "In this article, we are going to see what is APP_BASE_HREF in Angular 10 and how to use it." }, { "code": null, "e": 265, "s": 120, "text": "APP_BASE_HREF ...
Maximum number of customers that can be satisfied with given quantity
25 May, 2022 A new variety of rice has been brought in supermarket and being available for the first time, the quantity of this rice is limited. Each customer demands the rice in two different packaging of size a and size b. The sizes a and b are decided by staff as per the demand. Given the size of the packets a and b, the total quantity of rice available d and the number of customers n, find out maximum number of customers that can be satisfied with the given quantity of rice. Display the total number of customers that can be satisfied and the index of customers that can be satisfied. Note: If a customer orders 2 3, he requires 2 packets of size a and 3 packets of size b. Assume indexing of customers starts from 1. Input: The first line of input contains two integers n and d; next line contains two integers a and b. Next n lines contain two integers for each customer denoting total number of bags of size a and size b that customer requires. Output: Print the maximum number of customers that can be satisfied and in the next line print the space-separated indexes of satisfied customers. Examples: Input : n = 5, d = 5 a = 1, b = 1 2 0 3 2 4 4 10 0 0 1 Output : 2 5 1 Input : n = 6, d = 1000000000 a = 9999, b = 10000 10000 9998 10000 10000 10000 10000 70000 70000 10000 10000 10000 10000 Output : 5 1 2 3 5 6 Explanation: In first example, the order of customers according to their demand is: Customer ID Demand 5 1 1 2 2 5 3 8 4 10 From this, it can easily be concluded that only customer 5 and customer 1 can be satisfied for total demand of 1 + 2 = 3. Rest of the customer cannot purchase the remaining rice, as their demand is greater than available amount. Approach: In order to meet the demand of maximum number of customers we must start with the customer with minimum demand so that we have maximum amount of rice left to satisfy remaining customers. Therefore, sort the customers according to the increasing order of demand so that maximum number of customers can be satisfied. Below is the implementation of above approach: C++ Python3 // CPP program to find maximum number// of customers that can be satisfied#include <bits/stdc++.h>using namespace std; vector<pair<long long, int> > v; // print maximum number of satisfied// customers and their indexesvoid solve(int n, int d, int a, int b, int arr[][2]){ // Creating an vector of pair of // total demand and customer number for (int i = 0; i < n; i++) { int m = arr[i][0], t = arr[i][1]; v.push_back(make_pair((a * m + b * t), i + 1)); } // Sorting the customers according // to their total demand sort(v.begin(), v.end()); vector<int> ans; // Taking the first k customers that // can be satisfied by total amount d for (int i = 0; i < n; i++) { if (v[i].first <= d) { ans.push_back(v[i].second); d -= v[i].first; } } cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) cout << ans[i] << " ";} // Driver programint main(){ // Initializing variables int n = 5; long d = 5; int a = 1, b = 1; int arr[][2] = {{2, 0}, {3, 2}, {4, 4}, {10, 0}, {0, 1}}; solve(n, d, a, b, arr); return 0;} # Python3 program to find maximum number# of customers that can be satisfiedv = [] # print maximum number of satisfied# customers and their indexesdef solve(n, d, a, b, arr): first, second = 0, 1 # Creating an vector of pair of # total demand and customer number for i in range(n): m = arr[i][0] t = arr[i][1] v.append([a * m + b * t, i + 1]) # Sorting the customers according # to their total demand v.sort() ans = [] # Taking the first k customers that # can be satisfied by total amount d for i in range(n): if v[i][first] <= d: ans.append(v[i][second]) d -= v[i][first] print(len(ans)) for i in range(len(ans)): print(ans[i], end = " ") # Driver Codeif __name__ == '__main__': # Initializing variables n = 5 d = 5 a = 1 b = 1 arr = [[2, 0], [3, 2], [4, 4], [10, 0], [0, 1]] solve(n, d, a, b, arr) # This code is contributed by PranchalK Output: 2 5 1 Time Complexity: O(n*log(n)) Auxiliary Space: O(n) PranchalKatiyar shivamanandrj9 Competitive Programming Greedy Matrix Greedy Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Competitive Programming - A Complete Guide Practice for cracking any coding interview Modulo 10^9+7 (1000000007) Arrow operator -> in C/C++ with Examples Fast I/O for Competitive Programming 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": "\n25 May, 2022" }, { "code": null, "e": 1153, "s": 52, "text": "A new variety of rice has been brought in supermarket and being available for the first time, the quantity of this rice is limited. Each customer demands the rice in two dif...
How to return a json object from a Python function?
20 Dec, 2021 The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json and this module can be used to convert a python dictionary to JSON object. In Python dictionary is used to get its equivalent JSON object. Import module Create a Function Create a Dictionary Convert Dictionary to JSON Object Using dumps() method Return JSON Object Syntax: json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Implementation using the above approach is given below: Example 1: Python3 # Import Moduleimport json # Create geeks function def geeks(): # Define Variable language = "Python" company = "GeeksForGeeks" Itemid = 1 price = 0.00 # Create Dictionary value = { "language": language, "company": company, "Itemid": Itemid, "price": price } # Dictionary to JSON Object using dumps() method # Return JSON Object return json.dumps(value) # Call Function and Print it.print(geeks()) Output: {“language”: “Python”, “company”: “GeeksForGeeks”, “Itemid”: 1, “price”: 0.0} Example 2: Using the list as Dictionary value. Python3 # Import Moduleimport json # Create geeks function def geeks(): # Create Dictionary value = { "firstName": "Pawan", "lastName": "Gupta", "hobbies": ["playing", "problem solving", "coding"], "age": 20, "children": [ { "firstName": "mohan", "lastName": "bansal", "age": 15 }, { "firstName": "prerna", "lastName": "Doe", "age": 18 } ] } # Dictionary to JSON Object using dumps() method # Return JSON Object return json.dumps(value) # Call Function and Print it.print(geeks()) Output: {“firstName”: “Pawan”, “lastName”: “Gupta”, “hobbies”: [“playing”, “problem solving”, “coding”], “age”: 20, “children”: [{“firstName”: “mohan”, “lastName”: “bansal”, “age”: 15}, {“firstName”: “prerna”, “lastName”: “Doe”, “age”: 18}]} sweetyty Picked Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Dec, 2021" }, { "code": null, "e": 410, "s": 28, "text": "The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer th...
Difference between dict.items() and dict.iteritems() in Python - GeeksforGeeks
12 Dec, 2019 dict.items() and dict.iteriteams() almots does the same thing, but there is a slight difference between them – dict.items(): returns a copy of the dictionary’s list in the form of (key, value) tuple pairs, which is a (Python v3.x) version, and exists in (Python v2.x) version. dict.iteritems(): returns an iterator of the dictionary’s list in the form of (key, value) tuple pairs. which is a (Python v2.x) version and got omitted in (Python v3.x) version. For Python2.x: Example-1 # Python2 code to demonstrate# d.iteritems() d ={ "fantasy": "harrypotter", "romance": "me before you", "fiction": "divergent" } # every time you run the object address keeps changesprint d.iteritems() Output: <dictionary-itemiterator object at 0x7f04628d5890> To print the dictionary items, use a for() loop to divide the objects and print themExample-2 # Python2 code to demonstrate# d.iteritems() d ={"fantasy": "harrypotter","romance": "me before you","fiction": "divergent"} for i in d.iteritems(): # prints the items print(i) Output: ('romance', 'me before you') ('fantasy', 'harrypotter') ('fiction', 'divergent') If we try to run the dict.items() in Python v2.x, it runs as dict.items() exists in v2.x. Example-3 # Python2 code to demonstrate# d.items() d ={ "fantasy": "harrypotter", "romance": "me before you", "fiction": "divergent" } # places the tuples in a list.print(d.items()) # returns iterators and never builds a list fully.print(d.iteritems()) Output: [(‘romance’, ‘me before you’), (‘fantasy’, ‘harrypotter’), (‘fiction’, ‘divergent’)]<dictionary-itemiterator object at 0x7f1d78214890> For Python3: Example-1 # Python3 code to demonstrate# d.items() d ={ "fantasy": "harrypotter", "romance": "me before you", "fiction": "divergent" } # saves as a copyprint(d.items()) Output: dict_items([(‘fantasy’, ‘harrypotter’), (‘fiction’, ‘divergent’), (‘romance’, ‘me before you’)]) If we try to run the dict.iteritems() in Python v3.x, we will ecounter with an error. Example-2 # Python3 code to demonstrate# d.iteritems() d ={ "fantasy": "harrypotter", "romance": "me before you", "fiction": "divergent" } print("d.items() in (v3.6.2) = ")for i in d.items(): # prints the items print(i) print("\nd.iteritems() in (v3.6.2)=") for i in d.iteritems(): # prints the items print(i) Output: d.items() in (v3.6.2) = ('fiction', 'divergent') ('fantasy', 'harrypotter') ('romance', 'me before you') d.iteritems() in (v3.6.2)= Traceback (most recent call last): File "/home/33cecec06331126ebf113f154753a9a0.py", line 19, in for i in d.iteritems(): AttributeError: 'dict' object has no attribute 'iteritems' python-dict Python Technical Scripter python-dict 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 How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24182, "s": 24154, "text": "\n12 Dec, 2019" }, { "code": null, "e": 24293, "s": 24182, "text": "dict.items() and dict.iteriteams() almots does the same thing, but there is a slight difference between them –" }, { "code": null, "e": 24459, "s":...
Extract Content from HTML
How to extract content from an HTML document using java. Following is the program to extract content from an HTML document using java. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.html.HtmlParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class ExtractContentFromHTMLDoc { public static void main(String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File( "C:/tika/htmlExample.html")); ParseContext pcontext = new ParseContext(); //Html parser HtmlParser htmlparser = new HtmlParser(); htmlparser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Contents of the document:Sheet1 ID NAME BRANCH PERCENTAGE EMAIL 1 Ram IT 85 ram123@gmail.com 2 Rahim EEE 95 rahim123@gmail.com 3 Robert ECE 90 robert123@gmail.com Metadata of the document: Content-Encoding: windows-1252 Content-Type: text/html; charset=windows-1252 Print Add Notes Bookmark this page
[ { "code": null, "e": 2125, "s": 2068, "text": "How to extract content from an HTML document using java." }, { "code": null, "e": 2203, "s": 2125, "text": "Following is the program to extract content from an HTML document using java." }, { "code": null, "e": 3420, ...
10 Examples to Master *args and **kwargs in Python | by Soner Yıldırım | Towards Data Science
Functions are building blocks in Python. They take zero or more arguments and return a value. Python is pretty flexible in terms of how arguments are passed to a function. The *args and **kwargs make it easier and cleaner to handle arguments. The important parts are “*” and “**”. You can use any word instead of args and kwargs but it is the common practice to use the words args and kwargs. Thus, there is no need for unnecessary adventures. In this post, we will go over 10 examples that I think will make the concept of *args and **kwargs crystal clear. Consider the following function that sums up two numbers. def addition(a, b): return a + bprint(addition(3,4))7 This function sums up only two numbers. What if we want a function that sums up three or four numbers? We may not even want to put a constraint on the number of arguments that passes to the function. In such cases, we can use *args as parameter. *args allow a function to take any number of positional arguments. def addition(*args): result = 0 for i in args: result += i return result The parameters passed to the addition function are stored in a tuple. Thus, we can iterate over the args variable. print(addition())0print(addition(1,4))5print(addition(1,7,3))11 Before the second example, it is better to explain the difference between a positional argument and a key word argument. Positional arguments are declared by a name only. Keyword arguments are declared by a name and a default value. When a function is called, values for positional arguments must be given. Otherwise, we will get an error. If we do not specify the value for a keyword argument, it takes the default value. def addition(a, b=2): #a is positional, b is keyword argument return a + bprint(addition(1))3def addition(a, b): #a and b are positional arguments return a + bprint(addition(1))TypeError: addition() missing 1 required positional argument: 'b' We can do the second example now. It is possible to use the *args and named variables together. The following function prints the passed arguments accordingly. def arg_printer(a, b, *args): print(f'a is {a}') print(f'b is {b}') print(f'args are {args}')arg_printer(3, 4, 5, 8, 3)a is 3b is 4args are (5, 8, 3) The first two values are given to a and b. The remaining values are stored in the args tuple. Python wants us to put keyword arguments after positional arguments. We need to keep that in mind when calling a functions. Consider the following example: arg_printer(a=4, 2, 4, 5)SyntaxError: positional argument follows keyword argument If we assign a value to a positional argument, it becomes a keyword argument. Since it is followed by positional arguments, we get a SyntaxError. In the following function, the option is a keyword argument (it has a default value). def addition(a, b, *args, option=True): result = 0 if option: for i in args: result += i return a + b + result else: return result This function performs addition operation if option is True. Since the default value is True, the function returns the sum of the arguments unless option parameter is declared as False. print(addition(1,4,5,6,7))23print(addition(1,4,5,6,7, option=False))0 The **kwargs collect all the keyword arguments that are not explicitly defined. Thus, it does the same operation as *args but for keyword arguments. **kwargs allow a function to take any number of keyword arguments. By default, **kwargs is an empty dictionary. Each undefined keyword argument is stored as a key-value pair in the **kwargs dictionary. def arg_printer(a, b, option=True, **kwargs): print(a, b) print(option) print(kwargs)arg_printer(3, 4, param1=5, param2=6)3 4True{'param1': 5, 'param2': 6} We can use both *args and **kwargs in a function but *args must be put before **kwargs. def arg_printer(a, b, *args, option=True, **kwargs): print(a, b) print(args) print(option) print(kwargs)arg_printer(1, 4, 6, 5, param1=5, param2=6)1 4(6, 5)True{'param1': 5, 'param2': 6} We can pack and unpack variables using *args and **kwargs. def arg_printer(*args): print(args) If we pass a list to the function above, it will stored in args tuple as one single element. lst = [1,4,5]arg_printer(lst)([1, 4, 5],) If we put an asterisk before lst, the values in the list will be unpacked and stored in args tuple separately. lst = [1,4,5]arg_printer(*lst)(1, 4, 5) We can pass multiple iterables to be unpacked together with single elements. All values will be stored in the args tuple. lst = [1,4,5]tpl = ('a','b',4)arg_printer(*lst, *tpl, 5, 6)(1, 4, 5, 'a', 'b', 4, 5, 6) We can do the packing and unpacking with keyword arguments as well. def arg_printer(**kwargs): print(kwargs) But the iterable that is passed as keyword arguments must be a mapping such as a dictionary. dct = {'param1':5, 'param2':8}arg_printer(**dct){'param1': 5, 'param2': 8} If we also pass additional keyword arguments together with a dictionary, they will combined and stored in the kwargs dictionary. dct = {'param1':5, 'param2':8}arg_printer(param3=9, **dct){'param3': 9, 'param1': 5, 'param2': 8} To summarize what we have covered: There are two types of arguments in a function which are positional arguments (declared by a name only) and keyword arguments (declared by a name and a default value). When a function is called, values for positional arguments must be given. Keywords arguments are optional (they take the default value if not specified). *args collects the positional arguments that are not explicitly defined and store them in a tuple **kwargs does the same as *args but for keyword arguments. They are stored in a dictionary because keyword arguments are stored as name-value pairs. Python does not allow positional arguments to follow keyword arguments. Thus, we first declare positional arguments and then keyword arguments. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 415, "s": 172, "text": "Functions are building blocks in Python. They take zero or more arguments and return a value. Python is pretty flexible in terms of how arguments are passed to a function. The *args and **kwargs make it easier and cleaner to handle arguments." }, { ...
Python - Pairs with Sum equal to K in tuple list - GeeksforGeeks
06 Mar, 2020 Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. This kind of problem can be important in web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loopThis can be solved using loop. This is brute way in which this task is performed. In this, we iterate the list for pair summation and retain whose sum is K. # Python3 code to demonstrate # Pairs with Sum equal to K in tuple list# using loop # Initializing listtest_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] # printing original listprint("The original list is : " + str(test_list)) # Initializing K K = 9 # Pairs with Sum equal to K in tuple list# using loopres = []for ele in test_list: if ele[0] + ele[1] == K: res.append(ele) # printing result print ("List after extracting pairs equal to K : " + str(res)) The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)] Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. In this, we extract the elements in similar method as above, the difference is that we perform this task as shorthand and in one line. # Python3 code to demonstrate # Pairs with Sum equal to K in tuple list# using list comprehension # Initializing listtest_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] # printing original listprint("The original list is : " + str(test_list)) # Initializing K K = 9 # Pairs with Sum equal to K in tuple list# using list comprehensionres = [(ele[0], ele[1]) for ele in test_list if ele[0] + ele[1] == K] # printing result print ("List after extracting pairs equal to K : " + str(res)) The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)] Python list-programs Python Python Programs 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 How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24984, "s": 24956, "text": "\n06 Mar, 2020" }, { "code": null, "e": 25293, "s": 24984, "text": "Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. Thi...
Julia Programming - Environment Setup
To install Julia, we need to download binary Julia platform in executable form which you can download from the link https://julialang.org/downloads/. On the webpage, you will find Julia in 32-bit and 64-bit format for all three major platforms, i.e. Linux, Windows, and Macintosh (OS X). The current stable release which we are going to use is v1.5.1. Let us see how we can install Julia on various platforms − The command set given below can be used to download the latest version of Julia programming language into a directory, let’s say Julia-1.5.1 − wget https://julialang-s3.julialang.org/bin/linux/x64/1.5/julia-1.5.1-linux-x86_64.tar.gz tar zxvf julia-1.5.1-linux-x86_64.tar.gz Once installed, we can do any of the following to run Julia − Use Julia’s full path, <Julia directory>/bin/Julia to invoke Julia executable. Here <Julia directory> refers to the directory where Julia is installed on your computer. Use Julia’s full path, <Julia directory>/bin/Julia to invoke Julia executable. Here <Julia directory> refers to the directory where Julia is installed on your computer. You can also create a symbolic link to Julia programming language. The link should be inside a folder which is on your system PATH. You can also create a symbolic link to Julia programming language. The link should be inside a folder which is on your system PATH. You can add Julia’s bin folder with full path to system PATH environment variable by editing the ~/.bashrc or ~/.bash_profile file. It can be done by opening the file in any of the editors and adding the line given below: You can add Julia’s bin folder with full path to system PATH environment variable by editing the ~/.bashrc or ~/.bash_profile file. It can be done by opening the file in any of the editors and adding the line given below: export PATH="$PATH:/path/to/<Julia directory>/bin" Once you downloaded the installer as per your windows specifications, run the installer. It is recommended to note down the installation directory which looks like C:\Users\Ga\AppData\Local\Programs\Julia1.5.1. To invoke Julia programming language by simply typing Julia in cmd, we must add Julia executable directory to system PATH. You need to follow the following steps according to your windows specifications − On Windows 10 First open Run by using the shortcut Windows key + R. First open Run by using the shortcut Windows key + R. Now, type rundll32 sysdm.cpl, EditEnvironmentVariables and press enter. Now, type rundll32 sysdm.cpl, EditEnvironmentVariables and press enter. We will now find the row with “Path” under “User Variable” or “System Variable”. We will now find the row with “Path” under “User Variable” or “System Variable”. Now click on edit button to get the “Edit environment variable” UI. Now click on edit button to get the “Edit environment variable” UI. Now, click on “New” and paste in the directory address we have noted while installation (C:\Users\Ga\AppData\Local\Programs\Julia1.5.1\bin). Now, click on “New” and paste in the directory address we have noted while installation (C:\Users\Ga\AppData\Local\Programs\Julia1.5.1\bin). Finally click OK and Julia is ready to be run from command line by typing Julia. Finally click OK and Julia is ready to be run from command line by typing Julia. On Windows 7 or 8 First open Run by using the shortcut Windows key + R. First open Run by using the shortcut Windows key + R. Now, type rundll32 sysdm.cpl, EditEnvironmentVariables and press enter. Now, type rundll32 sysdm.cpl, EditEnvironmentVariables and press enter. We will now find the row with “Path” under “User Variable” or “System Variable”. We will now find the row with “Path” under “User Variable” or “System Variable”. Click on edit button and we will get the “Edit environment variable” UI. Click on edit button and we will get the “Edit environment variable” UI. Now move the cursor to the end of this field and check if there is semicolon at the end or not. If not found, then add a semicolon. Now move the cursor to the end of this field and check if there is semicolon at the end or not. If not found, then add a semicolon. Once added, we need to paste in the directory address we have noted while installation (C:\Users\Ga\AppData\Local\Programs\Julia1.5.1\bin). Once added, we need to paste in the directory address we have noted while installation (C:\Users\Ga\AppData\Local\Programs\Julia1.5.1\bin). Finally click OK and Julia is ready to be run from command line by typing Julia. Finally click OK and Julia is ready to be run from command line by typing Julia. On macOS, a file named Julia-<version>.dmg will be given. This file contains Julia-<version>.app and you need to drag this file to Applications Folder Shortcut. One other way to run Julia is from the disk image by opening the app. If you want to run Julia from terminal, type the below given command − ln -s /Applications/Julia-1.5.app/Contents/Resources/julia/bin/julia /usr/local/bin/julia This command will create a symlink to the Julia version we have chosen. Now close the shell profile page and quit terminal as well. Now once again open the Terminal and type julia in it and you will be with your version of Julia programming language. To build Julia from source rather than binaries, we need to follow the below given steps. Here we will be outlining the procedure for Ubuntu OS. Download the source code from GitHub at https://github.com/JuliaLang/julia. Download the source code from GitHub at https://github.com/JuliaLang/julia. Compile it and you will get the latest version. It will not give us the stable version. Compile it and you will get the latest version. It will not give us the stable version. If you do not have git installed, use the following command to install the same − If you do not have git installed, use the following command to install the same − sudo apt-get -f install git Using the following command, clone the Julia sources − git clone git://github.com/JuliaLang/julia.git The above command will download the source code into a julia directory and that is in current folder. Now, by using the command given below, install GNU compilation tools g++, gfortran, and m4 − sudo apt-get install gfortran g++ m4 Once installation done, start the compilation process as follows − cd Julia make After this, successful build Julia programming language will start up with the ./julia command. REPL (read-eval-print loop) is the working environment of Julia. With the help of this shell we can interact with Julia’s JIT (Just in Time) compiler to test and run our code. We can also copy and paste our code into .jl extension, for example, first.jl. Another option is to use a text editor or IDE. Let us have a look at REPL below − After clicking on Julia logo, we will get a prompt with julia> for writing our piece of code or program. Use exit() or CTRL + D to end the session. If you want to evaluate the expression, press enter after input. Almost all the standard libraries in Julia are written in Julia itself but the rest of the Julia’s code ecosystem can be found in Packages which are Git repositories. Some important points about Julia packages are given below − Packages provide reusable functionality that can be easily used by other Julia projects. Packages provide reusable functionality that can be easily used by other Julia projects. Julia has built-in package manager named pkg.jl for package installation. Julia has built-in package manager named pkg.jl for package installation. The package manager handles installation, removal, and updates of packages. The package manager handles installation, removal, and updates of packages. The package manager works only if the packages are in REPL. The package manager works only if the packages are in REPL. Step 1 − First open the Julia command line. Step 2 − Now open the Julia package management environment by pressing, ]. You will get the following console − You can check https://juliaobserver.com/packages to see which packages we can install on Julia. For adding a package in Julia environment, we need to use addcommand with the name of the package. For example, we will be adding the package named Graphs which is uses for working with graphs in Julia. For removing a package from Julia, we need to use rm command with the name of the of the package. For example, we will be removing the package named Graphs as follows − To update a Julia package, either you can use update command, which will update all the Julia packages, or you can use up command along with the name of the package, which will update specific package. Use test command to test a Julia package. For example, below we have tested JSON package − To install IJulia, use add IJulia command in Julia package environment. We need to make sure that you have preinstalled Anaconda on your machine. Once it gets installed, open Jupyter notebook and choose Julia1.5.1 as follows − Now you will be able to write Julia programs using IJulia as follows − Juno is a powerful IDE for Julia programming language. It is free, and to install follow the steps given below − Step 1 − First we need to install Julia on our system. Step 2 − Now you need to install Atom from here. It must be updated(version 1.41+). Step 3 − In Atom, go to settings and then install panel. It will install Juno for you. Step 4 − Start working in Juno by opening REPL with Juno > open REPL command. 73 Lectures 4 hours Lemuel Ogbunude 24 Lectures 3 hours Mohammad Nauman 29 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2430, "s": 2078, "text": "To install Julia, we need to download binary Julia platform in executable form which you can download from the link https://julialang.org/downloads/. On the webpage, you will find Julia in 32-bit and 64-bit format for all three major platforms, i.e. Lin...
Java Program for Counting Sort
The Counting Sort counts the number of objects having distinct key values. Let us see an example − Note − The below code can be used with negative numbers as well. Live Demo import java.util.*; public class Demo{ static void count_sort(int[] arr){ int max_val = Arrays.stream(arr).max().getAsInt(); int min_val = Arrays.stream(arr).min().getAsInt(); int range = max_val - min_val + 1; int count[] = new int[range]; int result[] = new int[arr.length]; for (int i = 0; i < arr.length; i++){ count[arr[i] - min_val]++; } for (int i = 1; i < count.length; i++){ count[i] += count[i - 1]; } for (int i = arr.length - 1; i >= 0; i--){ result[count[arr[i] - min_val] - 1] = arr[i]; count[arr[i] - min_val]--; } for (int i = 0; i < arr.length; i++){ arr[i] = result[i]; } } static void printVal(int[] arr){ for (int i = 0; i < arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(""); } public static void main(String[] args){ int[] arr = {-5, 0, -3, 8, 34, 56, 89, -11, -95, -1, 10}; System.out.println("The array contains"); for (int i = 0; i < arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); System.out.println("Implementing Counting Sort in Java results in : "); count_sort(arr); printVal(arr); } } The array contains -5 0 -3 8 34 56 89 -11 -95 -1 10 Implementing Counting Sort in Java results in : -95 -11 -5 -3 -1 0 8 10 34 56 89 A class named Demo contains the ‘count_sort’ function. Here, the array is iterated over and the count value is increment. Next, this count array is iterated over and previous value is assigned to the next value. The array is iterated over again and the element of the array is assigned to the result array and the count array is decremented. Then, the array is iterated over again and the elements in the result array is assigned to the array. A print function is defined that prints the data on the console. The main function defines the elements of the array and calls the count sort on these elements.
[ { "code": null, "e": 1161, "s": 1062, "text": "The Counting Sort counts the number of objects having distinct key values. Let us see an example −" }, { "code": null, "e": 1226, "s": 1161, "text": "Note − The below code can be used with negative numbers as well." }, { "cod...
D3.js - Installation
In this chapter, we will learn how to set up the D3.js development environment. Before we start, we need the following components − D3.js library Editor Web browser Web server Let us go through the steps one by one in detail. We need to include the D3.js library into your HTML webpage in order to use D3.js to create data visualization. We can do it in the following two ways − Include the D3.js library from your project's folder. Include D3.js library from CDN (Content Delivery Network). D3.js is an open-source library and the source code of the library is freely available on the web at https://d3js.org/ website. Visit the D3.js website and download the latest version of D3.js (d3.zip). As of now, the latest version is 4.6.0. After the download is complete, unzip the file and look for d3.min.js. This is the minified version of the D3.js source code. Copy the d3.min.js file and paste it into your project's root folder or any other folder, where you want to keep all the library files. Include the d3.min.js file in your HTML page as shown below. Example − Let us consider the following example. <!DOCTYPE html> <html lang = "en"> <head> <script src = "/path/to/d3.min.js"></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html> D3.js is a JavaScript code, so we should write all our D3 code within “script” tag. We may need to manipulate the existing DOM elements, so it is advisable to write the D3 code just before the end of the “body” tag. We can use the D3.js library by linking it directly into our HTML page from the Content Delivery Network (CDN). CDN is a network of servers where files are hosted and are delivered to a user based on their geographic location. If we use the CDN, we do not need to download the source code. Include the D3.js library using the CDN URL https://d3js.org/d3.v4.min.js into our page as shown below. Example − Let us consider the following example. <!DOCTYPE html> <html lang = "en"> <head> <script src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html> We will need an editor to start writing your code. There are some great IDEs (Integrated Development Environment) with support for JavaScript like − Visual Studio Code WebStorm Eclipse Sublime Text These IDEs provide intelligent code completion as well as support some of the modern JavaScript frameworks. If you do not have fancy IDE, you can always use a basic editor like Notepad, VI, etc. D3.js works on all the browsers except IE8 and lower. Most browsers serve local HTML files directly from the local file system. However, there are certain restrictions when it comes to loading external data files. In the latter chapters of this tutorial, we will be loading data from external files like CSV and JSON. Therefore, it will be easier for us, if we set up the web server right from the beginning. You can use any web server, which you are comfortable with − e.g. IIS, Apache, etc. In most cases, we can just open your HTML file in a web browser to view it. However, when loading external data sources, it is more reliable to run a local web server and view your page from the server (http://localhost:8080). Print Add Notes Bookmark this page
[ { "code": null, "e": 2262, "s": 2130, "text": "In this chapter, we will learn how to set up the D3.js development environment. Before we start, we need the following components −" }, { "code": null, "e": 2276, "s": 2262, "text": "D3.js library" }, { "code": null, "e":...
Django - Apache Setup
So far, in our examples, we have used the Django dev web server. But this server is just for testing and is not fit for production environment. Once in production, you need a real server like Apache, Nginx, etc. Let's discuss Apache in this chapter. Serving Django applications via Apache is done by using mod_wsgi. So the first thing is to make sure you have Apache and mod_wsgi installed. Remember, when we created our project and we looked at the project structure, it looked like − myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py The wsgi.py file is the one taking care of the link between Django and Apache. Let's say we want to share our project (myproject) with Apache. We just need to set Apache to access our folder. Assume we put our myproject folder in the default "/var/www/html". At this stage, accessing the project will be done via 127.0.0.1/myproject. This will result in Apache just listing the folder as shown in the following snapshot. As seen, Apache is not handling Django stuff. For this to be taken care of, we need to configure Apache in httpd.conf. So open the httpd.conf and add the following line − WSGIScriptAlias / /var/www/html/myproject/myproject/wsgi.py WSGIPythonPath /var/www/html/myproject/ <Directory /var/www/html/myproject/> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> If you can access the login page as 127.0.0.1/myapp/connection, you will get to see the following page − 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2295, "s": 2045, "text": "So far, in our examples, we have used the Django dev web server. But this server is just for testing and is not fit for production environment. Once in production, you need a real server like Apache, Nginx, etc. Let's discuss Apache in this chapter." ...
Kibana - Management
The Management section in Kibana is used to manage the index patterns. In this chapter, we will discuss the following − Create Index Pattern without Time filter field Create Index Pattern with Time filter field To do this, go to Kibana UI and click Management − To work with Kibana, we first have to create index which is populated from elasticsearch. You can get all the indices available from Elasticsearch → Index Management as shown − At present elasticsearch has the above indices. The Docs count tells us the no of records available in each of the index. If there is any index which is updated, the docs count will keep changing. Primary storage tells the size of each index uploaded. To create New index in Kibana, we need to click on Index Patterns as shown below − Once you click Index Patterns, we get the following screen − Note that the Create Index Pattern button is used to create a new index. Recall that we already have countriesdata-28.12.2018 created at the very start of the tutorial. Click on Create Index Pattern to create a new index. The indices from elasticsearch are displayed, select one to create a new index. Now, click Next step. The next step is to configure the setting, where you need to enter the following − Time filter field name is used to filter data based on time. The dropdown will display all time and date related fields from the index. Time filter field name is used to filter data based on time. The dropdown will display all time and date related fields from the index. In the image shown below, we have Visiting_Date as a date field. Select Visiting_Date as the Time Filter field name. Click Create index pattern button to create the index. Once done it will display all the fields present in your index medicalvisits-26.01.2019 as shown below − We have following fields in the index medicalvisits-26.01.2019 − ["Visit_Status","Time_Delay","City","City_id","Patient_Age","Zipcode","Latitude ","Longitude","Pathology","Visiting_Date","Id_type","Id_personal","Number_Home_ Visits","Is_Patient_Minor","Geo_point"]. The index has all the data for home medical visits. There are some additional fields added by elasticsearch when inserted from logstash. Print Add Notes Bookmark this page
[ { "code": null, "e": 2225, "s": 2105, "text": "The Management section in Kibana is used to manage the index patterns. In this chapter, we will discuss the following −" }, { "code": null, "e": 2272, "s": 2225, "text": "Create Index Pattern without Time filter field" }, { "...
How to Deploy your Machine Learning Models on Kubernetes | by Dimitris Poulopoulos | Towards Data Science
Kubernetes is a production-grade container orchestration system, which automates the deployment, scaling and management of containerized applications. The project is open-sourced and battle-tested with mission-critical applications that Google runs. Machine learning solutions are often broken down into many steps that can be OS and framework agnostic. Also, it is common for data science projects to follow the dataflow programming paradigm, where a program is designed as a directed graph with data moving from one operation to the next. These methodologies and abstractions are easily implemented with Kubernetes, leaving the infrastructure management burden on the system. In this story, we will deploy a simple image classifier web service on Kubernetes. We will be working on Google Cloud Platform (GCP) and take advantage of their secured and managed Kubernetes service offering: GKE. We will first use Terraform to provision and manage the needed infrastructure and then create a simple deployment of a pre-trained PyTorch model. Let us start. Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here! To build the infrastructure needed we will use Terraform. Terraform treats infrastructure as code, to provision and manage any cloud, infrastructure, or service. Terraform will make very easy for us to create the resources we need and clean up after ourselves when we are done, to avoid accumulating costs. To install Terraform follow the instructions for your platform. To work on GCP we first need to create a project resource. The project resource is a logical organization entity which forms the basis for creating, enabling, and using other Google Cloud services, among others. It is necessary to start working on GCP and easy to construct one or use the default project initialized with any new GCP account. To create a new one, from the side panel go to IAM & Admin and choose Manage Resources at the bottom. Press the Create Project button, give a name and you are good to go. The next step is to create a Sevice Account that terraform will use to create the resources we need. A service account is a special kind of account used by an application, not a person. Make sure you are using the project you created, go back to IAM & Admin choice and pick Service Accounts. Create a new one by pressing the button Create Service Account, name it terraform and press create. On the next step, grand the service account the role of Project Editor and press continue. Finally, generate a JSON key by pressing the Create Key button. This key will be the method of authentication for Terraform. First, we need to configure Terraform to use a Google Storage bucket to store the metadata it needs. This is a great way to keep Terraform running in an automated environment. First, let us create the bucket; create a new file called main.tf: Then, we need to create a new file for the variables it uses. Create that file and name it variables.tf: This file tells Terraform which variables to expect and provides some defaults. For example, the location variable in our first script now has a default which is US. There are other variables, like the project_id, that we need to provide the value ourselves. To this end, we create a new terraform.tfvars file: Be sure to fill the terraform.tfvars file with the info necessary and then run terraform init followed byterraform apply. Finally, go to the GCP console to verify that the bucket is there. We are now ready to spin off our Kubernetes cluster. We will create three separate files in a new directory: one to define the Terraform backend, one for the cloud provider and one for the actual cluster. Of course, we will need two extra files for the variables. Let us set the backend. Create a terraform.tf file and copy the following inside: Be sure to provide the name of the bucket you created before. Then create a provider.tf file for the cloud provider: Finally, create a main.tf file to configure the GKE cluster we want. For this example, we will keep it to a bare minimum. One thing we will change though is to remove the default node pool and create one of our own, where we use n1-standard-1 preemptible machines. Finally, create the variables.tf and terraform.tfvars files, to provide the necessary variables. And the terraform.tfvars file: Setting the location to a zone format will create a zonal cluster. Google offers one free zonal cluster per billing account, thus we will take advantage of that discount. As before, run terraform init and terraform apply, wait a few minutes and your cluster will be ready to go. For this example, we use a pre-trained PyTorch model and Flask, to create a simple machine learning web service. Next, we will create a simple Kubernetes deployment to deploy, manage and scale the web service. To design a simple image-classifier service, we use a PyTorch implementation of AlexNet, a CNN model for image classification. We serve it using the Flask micro-framework. First, we define a Predict Flask resource that initializes the model and accepts an HTTP POST request. We serve it with flask using the any-host identifier (0.0.0.0). Flask’s built-in server is not suitable for production as it doesn’t scale well. For our purposes is fine but if you want to see how to deploy a Flask application properly see here. To deploy it on Kubernetes we first need to containerize the service. To this end, we define the following Dockerfile: To build an image from this Dockerfile, create a requirements.txt file, in the same folder, with the following contents: flaskflask-restful Download in the same folder the JSON file that contained the labels of Imagenet here. We are now ready to build our docker image; run the following command: docker build -t <your-dockerhub-username>/image-classifier:latest . Finally, you need to push the image on a container registry. For instance, to push it on docker hub, create an account, configure docker and run the following commands: docker login --username usernamedocker push <your-dockerhub-username>/image-classifier:latest For simplicity, you can use the image I prepared for you. You can pull it from docker hub. The last step is deployment. For that, we use a simple YAML configuration file. But first, we need to install kubectl and get the credentials to connect to our cluster. To install kubectl follow the instructions for your platform. Next, install gcloud, the CLI tool for GCP. To get the credentials of your GKE cluster run the following command: cloud container clusters get-credentials <the-name-of-your-cluster> --zone <the-zone-that-it-is-in> For example: cloud container clusters get-credentials my-gke-cluster --zone us-central1-a This command will create a configuration file and instruct kubectl on how to connect with your GKE cluster. Finally, define the image classifier YAML deployment file. This configuration is split three-ways: first, we define a namespace which provides a scope for our resource names. Then, we define the actual deployment, where we use only one replica of our service. You can scale that number to whatever serves your needs. Finally, we expose our web service with a LoadBalancer. This will make our service accessible from the internet. Create the deployment by running the following command: kubectl apply -f image-classifier.yaml You are now ready to test your image classifier web service. For this example, we use curl. curl -X POST -d '{"url": "https://i.imgur.com/jD2hDMc.jpg"}' -H 'Content-Type: application/json' http://<your-cluster's-ip>/predict This command will query your service with a kitten image. What you get back is the prediction associated with some confidence. You have now successfully deployed a machine learning model on Kubernetes! To clean up after ourselves we will move in reverse order: Delete the namespace, deployment and load balancer: Delete the namespace, deployment and load balancer: kubectl delete -f image-classifier.yaml 2. Destroy the cluster: terraform destroy Run this command from the folder which you created in the “Terraform your GKE cluster” step. 3. Delete the Google Storage Bucket: terraform destroy Run this command from the folder which you created in the “Terraform configuration” step. In this story, we saw how to create resources with Terraform on GKE. Specifically, we created a GKE cluster, to leverage the hosted Kubernetes solution provided by Google Cloud Platform. Then, we created a simple image classification web service, build a docker image out of it and deploy it on Kubernetes. Finally, we cleaned up after ourselves, destroying the resource we do not need anymore to avoid extra costs. Kubernetes is a great platform to deploy machine learning models for production. In later articles, we will explore Kubeflow; a machine learning toolkit for Kubernetes. My name is Dimitris Poulopoulos and I’m a machine learning researcher at BigDataStack and PhD(c) at the University of Piraeus, Greece. I have worked on designing and implementing AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA. If you are interested in reading more posts about Machine Learning, Deep Learning and Data Science, follow me on Medium, LinkedIn or @james2pl on twitter.
[ { "code": null, "e": 297, "s": 47, "text": "Kubernetes is a production-grade container orchestration system, which automates the deployment, scaling and management of containerized applications. The project is open-sourced and battle-tested with mission-critical applications that Google runs." }, ...
Python | Average String length in list - GeeksforGeeks
29 Nov, 2019 Sometimes, while working with data, we can have a problem in which we need to gather information of average length of String data in list. This kind of information might be useful in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + sum() + len()The combination of above functions can be used to perform this task. In this we compute lengths of all Strings using list comprehension and then divide the sum by length of list using len() and sum(). # Python3 code to demonstrate working of# Average String lengths in list# using list comprehension + sum() + len() # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Average String lengths in list# using list comprehension + sum() + len()temp = [len(ele) for ele in test_list]res = 0 if len(temp) == 0 else (float(sum(temp)) / len(temp)) # printing resultprint("The Average length of String in list is : " + str(res)) The original list : ['gfg', 'is', 'best', 'for', 'geeks'] The Average length of String in list is : 3.4 Method #2 : Using map() + sum() + len()The combination of above functions can also be used to perform this task. In this, we compute lengths using map(). Rest all the logic is similar to above method. # Python3 code to demonstrate working of# Average String lengths in list# using map() + sum() + len() # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Average String lengths in list# using map() + sum() + len()res = sum(map(len, test_list))/float(len(test_list)) # printing resultprint("The Average length of String in list is : " + str(res)) The original list : ['gfg', 'is', 'best', 'for', 'geeks'] The Average length of String in list is : 3.4 Python list-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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24200, "s": 24172, "text": "\n29 Nov, 2019" }, { "code": null, "e": 24468, "s": 24200, "text": "Sometimes, while working with data, we can have a problem in which we need to gather information of average length of String data in list. This kind of information...
Jar files in Java - GeeksforGeeks
28 Jul, 2021 A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform. In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image files, or directories. We can imagine a .jar file as a zipped file(.zip) that is created by using WinZip software. Even, WinZip software can be used to extract the contents of a .jar . So you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. Let us see how to create a .jar file and related commands which help us to work with .jar files 1.1 Create a JAR file In order to create a .jar file, we can use jar cf command in the following ways as discussed below: Syntax: jar cf jarfilename inputfiles Here, cf represents to create the file. For example , assuming our package pack is available in C:\directory , to convert it into a jar file into the pack.jar , we can give the command as: C:\> jar cf pack.jar pack 1. 2 View a JAR file Now, pack.jar file is created. In order to view a JAR file ‘.jar’ files, we can use the command as: Syntax: jar tf jarfilename Here, tf represents the table view of file contents. For example, to view the contents of our pack.jar file, we can give the command: C:/> jar tf pack.jar Now, the contents of pack.jar are displayed as follows: META-INF/ META-INF/MANIFEST.MF pack/ pack/class1.class pack/class2.class .. .. Here class1, class2, etc are the classes in the package pack. The first two entries represent that there is a manifest file created and added to pack.jar. The third entry represents the sub-directory with the name pack and the last two represent the files name in the directory pack. Note: When we create .jar files, it automatically receives the default manifest file. There can be only one manifest file in an archive, and it always has the pathname. META-INF/MANIFEST.MF This manifest file is useful to specify the information about other files which are packaged. 1.3 Extracting a JAR file In order to extract the files from a .jar file, we can use the commands below listed: jar xf jarfilename Here, xf represents extract files from the jar files. For example, to extract the contents of our pack.jar file, we can write: C:\> jar xf pack.jar This will create the following directories in C:\ META-INF In this directory, we can see class1.class and class2.class. pack 1.4 Updating a JAR File The Jar tool provides a ‘u’ option that you can use to update the contents of an existing JAR file by modifying its manifest or by adding files. The basic command for adding files has this format as shown below: Syntax: jar uf jar-file input-file(s) Here ‘uf’ represents the updated jar file. For example, to update the contents of our pack.jar file, we can write: C:\>jar uf pack.jar 1.5 Running a JAR file In order to run an application packaged as a JAR file (requires the Main-class manifest header), the following command can be used as listed: Syntax: C:\>java -jar pack.jar Related Article: Working with JAR and Manifest files In Java This article is contributed by Nishant Sharma. 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. obulreddymalapati GBlog Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GET and POST requests using Python How to Start Learning DSA? Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 24368, "s": 24340, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25016, "s": 24368, "text": "A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one...
Working with Times and Dates in BigQuery | by Christianlauer | Towards Data Science
Who is not familiar with this situation? What was that thing again with the correct timestamp format? Just google it and next time it will end so again. Here are some of the use cases, that I often come in touch with and which I wanted to write down, in the hope not to have to google them again. Let’s start with a very easy but useful one. Get the current time — you might need it for comparison e.g. within analytics or for technical data transformations: SELECT CURRENT_DATETIME() as now; This function supports the optional timezone parameter. See Timezone definitions for instructions on how to set a timezone [1]. Return a value corresponding to the specified part from a provided datetime_expression. For example, here I extracted only the year. I often use this logic for constraints in analyses or for data transformations, where I convert date formats and store them in new tables in a different format. SELECT EXTRACT(YEAR FROM DATETIME(2021, 07, 02, 15, 45, 00)) as year; Calculates the difference between two dates. If the first DATETIME is before the second, the output is negative [1]. Select DATETIME_DIFF(DATETIME”2021–03–03", DATETIME”2021–04–04", Day)as difference; This results in -32. Format a DATETIME object according to the specified format_string. Similar to the other examples, one likes to use this formatting option in the data transformation process. SELECT FORMAT_DATETIME(“%c”, DATETIME “2008–12–25 15:30:00”) AS formatted; Here, for example with %c, the whole date and time representation are output [2]. With PARSE_DATETIME you can do the opposite of the example mentioned above. It converts the string representation of a DATETIME object into a DATETIME object. SELECT PARSE_DATETIME(‘%Y-%m-%d %H:%M:%S’, ‘2021–03–03 13:55:55’) AS datetime; Always useful when other sources for example display the date as string and you want to display it in BigQuery as standardized DATETIME. Returns the last day from a DATETIME expression containing the date. This is often used to return the last day of the month. You have the option to specify the date part for which the last day should be returned. SELECT LAST_DAY(DATETIME ‘2008–11–25’, MONTH) AS last_day If this parameter is not used, the default value is MONTH. Especially in the area of evaluations, for example for a financial month statement interesting and often used. Since I often find myself googling date formats within BigQuery because I forgot what the correct SQL expression was, I have provided you with my cheatsheet on the subject. These are the most common use cases in my opinion — feel free to let me know if I forgot anything.
[ { "code": null, "e": 343, "s": 46, "text": "Who is not familiar with this situation? What was that thing again with the correct timestamp format? Just google it and next time it will end so again. Here are some of the use cases, that I often come in touch with and which I wanted to write down, in th...
Java Basic Data Types | Practice | GeeksforGeeks
Read a value and store it in the appropriate Java Data Type. Example 1: Input: 18 abc 9.9876 Output: 18 abc 9.9876 Explanation: The three inputs are stored in approriate data types and then printed in order. Your Task: Your task is to complete each of the given functions javaIntType() : read an integer input, store it in appropriate data type and return it. javaStringType() : read a string input, store it in appropriate data type and return it. javaFloatType() : read a float input, store it in appropriate data type and return it. Each of the function have an object of Scanner in the parameter to be used to read the input. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) 0 indhu64771 month ago class Solution { int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }}; +2 imohdalam1 month ago Java | O(1) class Solution { int javaIntType(Scanner sc) { // code here int ans = sc.nextInt(); return ans; } String javaStringType(Scanner sc) { // code here String ans = sc.next(); return ans; } float javaFloatType(Scanner sc) { // code here float ans = sc.nextFloat(); return ans; } }; 0 rohitpandey484Premium2 months ago Java Solution class Solution { int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }}; 0 sachin1947s2 months ago Class Solution 0 vishwajeetofficial20222 months ago //JAVA SOLUTION class Solution { int javaIntType(Scanner sc) { // code here return sc.nextInt(); } String javaStringType(Scanner sc) { // code here return sc.next(); } float javaFloatType(Scanner sc) { // code here return sc.nextFloat(); } }; 0 shaktig1011013 months ago package abc; import java.util.Scanner; class Solution { int nextIntType(Scanner sc ){ return sc.nextInt (); } String nextStringType(Scanner sc){ return sc.next(); } Float nextFloatType(Scanner sc){ return sc.nextFloatType(); } } 0 neetathakur88783 months ago class Solution { int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }}; 0 rishitachail1253 months ago // { Driver Code Startsimport java.io.*;import java.util.*; class GFG { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { Solution ob = new Solution(); System.out.println(ob.javaIntType(sc)); System.out.println(ob.javaStringType(sc)); System.out.println(ob.javaFloatType(sc)); } }}// } Driver Code Ends class Solution { int javaIntType(Scanner sc) { // code here return sc.nextInt(); } String javaStringType(Scanner sc) { // code here return sc.next(); } float javaFloatType(Scanner sc) { // code here return sc.nextFloat(); }}; 0 gauravverma9918187053 months ago #Code Here# class Solution { int nextIntType(Scanner sc ){ return sc.nextInt (); } String nextStringType(Scanner sc){ return sc.next(); } Float nextFloatType(Scanner sc){ return sc.nextFloatType(); } }; 0 pinaksangamnerkar1234 months ago ArrayList<Integer> list = new ArrayList<Integer>(); int res = 0; for(Integer i1: A) res ^= i1; for(Integer i1: A) list.add(res ^ i1); return list; } } 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": 288, "s": 226, "text": "Read a value and store it in the appropriate Java Data Type. " }, { "code": null, "e": 300, "s": 288, "text": "\nExample 1:" }, { "code": null, "e": 445, "s": 300, "text": "Input: \n18 \nabc \n9.9876 \nOutput:\n18 \...
basename - Unix, Linux Command
basename - Strips directory and suffix from filenames. basename NAME [SUFFIX] basename OPTION basename prints NAME with any leading directory components removed. If Suffix is specified, it will also remove a trailing SUFFIX. To get the name of the file present in test folder $ basename test/sample.txt sample.txt 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10632, "s": 10577, "text": "basename - Strips directory and suffix from filenames." }, { "code": null, "e": 10671, "s": 10632, "text": "basename NAME [SUFFIX]\nbasename OPTION" }, { "code": null, "e": 10802, "s": 10671, "text": "basename p...
Design a 3D Hover Annotation Card using tilt.js - GeeksforGeeks
01 Feb, 2021 3D Hover Annotation Card: Upon hovering the card will display another card in 3D effect on top, the card possesses a tilting effect as well. This effect can be created using vanilla-tilt.js library and CSS. Installation: This can be installed by using a node package manager (npm) or by adding the CDN link in the code. npm command:npm install vanilla-tilt npm command: npm install vanilla-tilt CDN link: https://cdnjs.cloudflare.com/ajax/libs/vanilla-tilt/1.7.0/vanilla-tilt.min.js CDN link: https://cdnjs.cloudflare.com/ajax/libs/vanilla-tilt/1.7.0/vanilla-tilt.min.js Example: Below example uses tilt.js to create 3D hover effect card. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--CDN Link--> <script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-tilt/1.7.0/vanilla-tilt.min.js"> </script> <style> .parent_box { top: 30px; left: 30px; position: relative; width: 300px; height: 230px; margin: 10px 0; transform-style: preserve-3d; background-color: green; color: white; } .parent_box:hover { box-shadow: 0 50px 80px rgba(0, 0, 0, 0.2); } .parent_box .base_element { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .parent_box .content_box { background-color: white; position: absolute; top: 30%; left: 40px; right: 40px; font-weight: 700; font-size: 20px; color: green; text-align: center; transform: translateZ(20px) scaleY(0); padding: 40px 25px; transform-origin: top; transform: 0.5s; transform-style: preserve-3d; } .parent_box:hover .content_box { transform: translateZ(50px) scaleY(1); } </style></head> <body> <div class="parent_box" data-tilt data-tilt-scale="1.1"> <!-- Initial Element--> <div class="Base_element"> You Are On </div> <!--Element To Be Showed On Hovering--> <div class="content_box"> Geeks For Geeks </div> </div> <script type="text/javascript"> VanillaTilt.init(document.querySelectorAll(".parent_box"), { // max tilt rotation (degrees) max: 25, // Speed of the enter/exit transition speed: 400, }); </script></body> </html> Output: 3D Hover Annotation Card CSS-Questions HTML-Questions JavaScript-Questions CSS HTML JavaScript Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 26255, "s": 26227, "text": "\n01 Feb, 2021" }, { "code": null, "e": 26463, "s": 26255, "text": "3D Hover Annotation Card: Upon hovering the card will display another card in 3D effect on top, the card possesses a tilting effect as well. This effect can be cre...
How to implement Single Responsibility Principle using C#?
A class should have only one reason to change. Definition − In this context, responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and if in the future we need to make one change we are going to make it in the class which handles it. When we need to make a change in a class having more responsibilities the change might affect the other functions related to the other responsibility of the class. Code Before the Single Responsibility Principle using System; using System.Net.Mail; namespace SolidPrinciples.Single.Responsibility.Principle.Before { class Program{ public static void SendInvite(string email,string firstName,string lastname){ if(String.IsNullOrWhiteSpace(firstName)|| String.IsNullOrWhiteSpace(lastname)){ throw new Exception("Name is not valid"); } if (!email.Contains("@") || !email.Contains(".")){ throw new Exception("Email is not Valid!"); } SmtpClient client = new SmtpClient(); client.Send(new MailMessage("Test@gmail.com", email) { Subject="Please Join the Party!"}) } } } Code After Single Responsibility Principle using System; using System.Net.Mail; namespace SolidPrinciples.Single.Responsibility.Principle.After{ internal class Program{ public static void SendInvite(string email, string firstName, string lastname){ UserNameService.Validate(firstName, lastname); EmailService.validate(email); SmtpClient client = new SmtpClient(); client.Send(new MailMessage("Test@gmail.com", email) { Subject = "Please Join the Party!" }); } } public static class UserNameService{ public static void Validate(string firstname, string lastName){ if (string.IsNullOrWhiteSpace(firstname) || string.IsNullOrWhiteSpace(lastName)){ throw new Exception("Name is not valid"); } } } public static class EmailService{ public static void validate(string email){ if (!email.Contains("@") || !email.Contains(".")){ throw new Exception("Email is not Valid!"); } } } }
[ { "code": null, "e": 1109, "s": 1062, "text": "A class should have only one reason to change." }, { "code": null, "e": 1196, "s": 1109, "text": "Definition − In this context, responsibility is considered to be one reason to change." }, { "code": null, "e": 1632, "...
RFMT Segmentation Using K-Means Clustering | by Yexi Yuan | Towards Data Science
Important note: This was created as part of my own personal learning process for data science in python. I find it extremely helpful when i write this down to help me learn better and faster. This was part of the course on DataCamp and the code is based on the course and other online resources I used. Please visit DataCamp for the original syllabus. I am not affiliated with DataCamp in any form and only use their resources as a learner. On the final part of our customer segmentation journey we will be applying K-Means clustering method to segment our customer data. We will continue to use the features we’ve engineered in our RFM model. Additionally, we will be including tenure as a new feature for our model to create RFMT model. K-Means is a popular and simple unsupervised machine learning algorithm. Put simply, the K-means algorithm identifies k number of centroids, and then allocates every data point to the nearest cluster, while keeping the centroids as small as possible. We will not dive into the specifics of how K-Means work so let us dive into the customer segmentation implementation. These will be the 4 features that we are going to use to implement our K-Means model. Before we can fit the K-Means model to our data, we need to ensure that these key assumptions are fulfilled. Distribution of variablesVariables with same average valuesVariables with same variance Distribution of variables Variables with same average values Variables with same variance Looking at our RFMT summary statistics, we can see that our data set do not fulfill these key assumptions at the moment. Let’s create a data pre-processing pipeline to prep our data to be K-Means ready. Below are the steps we need to take to perform our data transformation and dive into each step in details: Unskew the data — We will be using log transformation to do thisStandardize to the same average valuesScale to the same standard deviationStore as a separate array to be used for clustering Unskew the data — We will be using log transformation to do this Standardize to the same average values Scale to the same standard deviation Store as a separate array to be used for clustering Let’s examine the shape of the distribution of our current data set. # Plot RFM distributionsplt.figure(figsize=(16,14))# Plot distribution of Rplt.subplot(4, 1, 1); sns.distplot(data_process['Recency'])# Plot distribution of Fplt.subplot(4, 1, 2); sns.distplot(data_process['Frequency'])# Plot distribution of Mplt.subplot(4, 1, 3); sns.distplot(data_process['MonetaryValue'])# Plot distribution of Tplt.subplot(4, 1, 4); sns.distplot(data_process['Tenure'])# Show the plotplt.show() As you can see, these is a general skewness of R, F, and M to the right. T has a more evenly distributed shape. To address this, we will apply Log Transformation to our data. # Apply Log Transformationdata_process['MonetaryValue'] = data_process['MonetaryValue'] + 0.0000000001recency_log = np.log(data_process['Recency'])frequency_log = np.log(data_process['Frequency'])monetary_log = np.log(data_process['MonetaryValue'])tenure_log = np.log(data_process['Tenure'])# Plot RFM distributionsplt.figure(figsize=(16,14))# Plot distribution of Rplt.subplot(4, 1, 1); sns.distplot(recency_log)# Plot distribution of Fplt.subplot(4, 1, 2); sns.distplot(frequency_log)# Plot distribution of Mplt.subplot(4, 1, 3); sns.distplot(monetary_log)# Plot distribution of Mplt.subplot(4, 1, 4); sns.distplot(tenure_log)# Show the plotplt.show() Great! Looks like we have normalized our RFM features. However, notice that by log transforming T, we’ve caused the data to left-skew. We have to always be careful when transforming data by examine through visualization or otherwise to ensure we create the most accurate representation of our customer segments. In order to standard mean and standard deviation, we can use the following formula: datamart_centered = datamart_rfm - datamart_rfm.mean()datamart_scaled = datamart_rfm / datamart_rfm.std() However, let’s make use of SKLearn library’s StandardScaler, to center and scale our data instead. from sklearn.preprocessing import StandardScalerscaler = StandardScaler()scaler.fit(data_process_log)data_process_norm = scaler.transform(data_process_log)data_process_norm_df = pd.DataFrame(data_process_norm)data_process_norm_df.describe().round(2) Awesome! Now we have fulfilled the key assumptions in order for us to properly and accurately apply K-Means clustering to segment our customers. Now let’s get into the most exciting portion of any machine learning project — applying the ML model! But before that, we need to choose the number of clusters for our K-Means model. This can be done in a few ways: Visualization Method — The Elbow CriterionMathematical Method — Silhouette CoefficientExperimentation and interpretation that makes the most business sense Visualization Method — The Elbow Criterion Mathematical Method — Silhouette Coefficient Experimentation and interpretation that makes the most business sense We will be using the elbow criterion method. The sum-of-squared-errors (SSE) is the sum of squared distances from every data point to their cluster center. We want to choose the optimal number of clusters that reduces the number SSE without over-fitting. Let’s plot our elbow chart to determine that. # Fit KMeans and calculate SSE for each *k*sse = {}for k in range(1, 11): kmeans = KMeans(n_clusters=k, random_state=1) kmeans.fit(data_process_norm) sse[k] = kmeans.inertia_# Plot SSE for each *k*plt.title('The Elbow Method')plt.xlabel('k'); plt.ylabel('SSE')sns.pointplot(x=list(sse.keys()), y=list(sse.values()))plt.show() Ideally, we want to choose the point on the elbow chart where the SSE stops decreasing at an increasing rate — i.e. the point where the change gradient of between the number of clusters becomes constant. For our model we will choose k=4. # Import KMeans from skLearnfrom sklearn.cluster import KMeans# Choose k=4 and fit data set to k-means modelkmeans = KMeans(n_clusters=4, random_state=1)kmeans.fit(data_process_norm)# Assign k-means labels to cluster labelscluster_labels = kmeans.labels_# Assign cluster labels to original pre-transformed data setdata_process_k4 = data_process.assign(Cluster = cluster_labels)# Group data set by k-means clusterdata_process_k4.groupby(['Cluster']).agg({ 'Recency': 'mean', 'Frequency': 'mean', 'MonetaryValue': 'mean', 'Tenure': ['mean', 'count']}).round(0) We can see that our grouped summary of the mean of R, F, M, and T that each cluster of customers places a different emphasis on our 4 features: Cluster 0 has the highest MontaryValue mean and lowest Recency mean and the highest frequency mean — This is our ideal customer segment Cluster 1 performs poorly across R, F, and M and has a long tenure in our database as well — we will need to design campaigns to activate them again Cluster 2 shopped with us recently but have not spend as much or as frequently as we would like them to — perhaps some personalization of products targeted at them can help to maximize their lifetime-value? Cluster 3 has spent quite a fair amount with us but has not shopped with us in the 3–4 months — We will need to do something before we lose them! We can visualize the relative importance of each feature for our 4 clusters through a heatmap. # Calculate average RFM values for each clustercluster_avg = data_process_k4.groupby(['Cluster']).mean()# Calculate average RFM values for the total customer populationpopulation_avg = data_process.mean()# Calculate relative importance of cluster's attribute value compared to populationrelative_imp = cluster_avg / population_avg - 1# Initialize a plot with a figure size of 8 by 2 inches plt.figure(figsize=(8, 4))# Add the plot titleplt.title('Relative importance of attributes')# Plot the heatmapsns.heatmap(data=relative_imp, annot=True, fmt='.2f', cmap='RdYlGn')plt.show() The heatmap provides a simple and easy way to understand how our K-Means model place relative importance of our RFMT attributes to assign each customer to their respective segments. Lastly, let’s visualize our K-Means Clusters in scatter plots to warp up our customer segmentation journey. # Plot RFM distributionsplt.figure(figsize=(20,20))plt.subplot(3, 1, 1);plt.scatter(data_process_k4[cluster_labels == 0].loc[:,'Recency'], data_process_k4[cluster_labels == 0].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 1', alpha=0.2)plt.scatter(data_process_k4[cluster_labels == 1].loc[:,'Recency'], data_process_k4[cluster_labels == 1].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 2', alpha=0.2)plt.scatter(data_process_k4[cluster_labels == 2].loc[:,'Recency'], data_process_k4[cluster_labels == 2].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 3', alpha=0.3)plt.scatter(data_process_k4[cluster_labels == 3].loc[:,'Recency'], data_process_k4[cluster_labels == 3].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 4', alpha=0.3)plt.xticks(np.arange(0, 1000, 100)) plt.yticks(np.arange(0, 10000, 1000))axes = plt.gca()axes.set_xlim(0, 500)axes.set_ylim(0, 10000)plt.title('Cusomter Clusters')plt.xlabel('Recency')plt.ylabel('Monetary Value')plt.legend()plt.subplot(3, 1, 2);plt.scatter(data_process_k4[cluster_labels == 0].loc[:,'Frequency'], data_process_k4[cluster_labels == 0].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 1', alpha=0.2)plt.scatter(data_process_k4[cluster_labels == 1].loc[:,'Frequency'], data_process_k4[cluster_labels == 1].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 2', alpha=0.2)plt.scatter(data_process_k4[cluster_labels == 2].loc[:,'Frequency'], data_process_k4[cluster_labels == 2].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 3', alpha=0.3)plt.scatter(data_process_k4[cluster_labels == 3].loc[:,'Frequency'], data_process_k4[cluster_labels == 3].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 4', alpha=0.3)plt.xticks(np.arange(0, 1000, 100)) plt.yticks(np.arange(0, 10000, 1000))axes = plt.gca()axes.set_xlim(0, 500)axes.set_ylim(0, 10000)plt.title('Cusomter Clusters')plt.xlabel('Frequency')plt.ylabel('Monetary Value')plt.legend()plt.subplot(3, 1, 3);plt.scatter(data_process_k4[cluster_labels == 0].loc[:,'Tenure'], data_process_k4[cluster_labels == 0].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 1', alpha=0.2)plt.scatter(data_process_k4[cluster_labels == 1].loc[:,'Tenure'], data_process_k4[cluster_labels == 1].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 2', alpha=0.2)plt.scatter(data_process_k4[cluster_labels == 2].loc[:,'Tenure'], data_process_k4[cluster_labels == 2].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 3', alpha=0.3)plt.scatter(data_process_k4[cluster_labels == 3].loc[:,'Tenure'], data_process_k4[cluster_labels == 3].loc[:,'MonetaryValue'], s= 10, cmap='rainbow', label = 'Cluster 4', alpha=0.3)plt.xticks(np.arange(0, 1000, 100)) plt.yticks(np.arange(0, 10000, 1000))axes = plt.gca()axes.set_xlim(0, 500)axes.set_ylim(0, 10000)plt.title('Cusomter Clusters')plt.xlabel('Tenure')plt.ylabel('Monetary Value')plt.legend()plt.show() Thanks for taking time to explore customer segmentation with through this 3-part series. If you enjoyed the content, stay tuned and I will be using exploring more data and perhaps build other interesting projects as well with Python.
[ { "code": null, "e": 613, "s": 172, "text": "Important note: This was created as part of my own personal learning process for data science in python. I find it extremely helpful when i write this down to help me learn better and faster. This was part of the course on DataCamp and the code is based o...
Implementing web scraping using lxml in Python - GeeksforGeeks
05 Oct, 2021 Web scraping basically refers to fetching only some important piece of information from one or more websites. Every website has recognizable structure/pattern of HTML elements. Steps to perform web scraping :1. Send a link and get the response from the sent link 2. Then convert response object to a byte string. 3. Pass the byte string to ‘fromstring’ method in html class in lxml module. 4. Get to a particular element by xpath. 5. Use the content according to your need. For accomplishing this task some third-party packages is needed to install. Use pip to install wheel(.whl) files. pip install requests pip install lxml xpath to the element is also needed from which data will be scrapped. An easy way to do this is – 1. Right-click the element in the page which has to be scrapped and go-to “Inspect”. 2. Right-click the element on source-code to the right. 3. Copy xpath. Here is a simple implementation on “geeksforgeeks homepage“: Python3 # Python3 code implementing web scraping using lxml import requests # import only html classfrom lxml import html # url to scrap data fromurl = 'https://www.geeksforgeeks.org' # path to particular elementpath = '//*[@id ="post-183376"]/div / p' # get response objectresponse = requests.get(url) # get byte stringbyte_data = response.content # get filtered source codesource_code = html.fromstring(byte_data) # jump to preferred html elementtree = source_code.xpath(path) # print texts in first element in listprint(tree[0].text_content()) The above code scrapes the paragraph in first article from “geeksforgeeks homepage” homepage. Here’s the sample output. The output may not be same for everyone as the article would have changed. Output : "Consider the following C/C++ programs and try to guess the output? Output of all of the above programs is unpredictable (or undefined). The compilers (implementing... Read More »" Here’s another example for data scraped from Wiki-web-scraping. Python3 import requestsfrom lxml import html # url to scrap data fromlink = 'https://en.wikipedia.org / wiki / Web_scraping' # path to particular elementpath = '//*[@id ="mw-content-text"]/div / p[1]' response = requests.get(link)byte_string = response.content # get filtered source codesource_code = html.fromstring(byte_string) # jump to preferred html elementtree = source_code.xpath(path) # print texts in first element in listprint(tree[0].text_content()) Output : Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites.[1] Web scraping software may access the World Wide Web directly using the Hypertext Transfer Protocol, or through a web browser. While web scraping can be done manually by a software user, the term typically refers to automate processes implemented using a bot or web crawler. It is a form of copying, in which specific data is gathered and copied from the web, typically into a central local database or spreadsheet, for later retrieval or analysis. ruhelaa48 Python-Miscellaneous python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24932, "s": 24904, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25110, "s": 24932, "text": "Web scraping basically refers to fetching only some important piece of information from one or more websites. Every website has recognizable structure/pattern of H...
gets() is risky to use! - GeeksforGeeks
05 Nov, 2020 Consider the below program. C void read(){ char str[20]; gets(str); printf("%s", str); return;} The code looks simple, it reads string from standard input and prints the entered string, but it suffers from Buffer Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a newline character. To avoid Buffer Overflow, fgets() should be used instead of gets() as fgets() makes sure that not more than MAX_LIMIT characters are read. C #define MAX_LIMIT 20void read(){ char str[MAX_LIMIT]; fgets(str, MAX_LIMIT, stdin); printf("%s", str); getchar(); return;} NOTE: fgets() stores the ‘\n’ character if it is read, so removing that has to be done explicitly by the programmer. It is hence, generally advised that your str can store at least (MAX_LIMIT + 1) characters if your intention is to keep the newline character. This is done so there is enough space for the null terminating character ‘\0’ to be added at the end of the string. If keeping the newline character is not intended, then one can simply do the following- C int len = strlen(str); // Remove the '\n' character and replace it with '\0'str[len - 1] = '\0'; Please feel free to read more about gets() and fgets() here. Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above. priyanshulgovil C Array and String C-programming gets secure-coding Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Analysis of Algorithms | Set 1 (Asymptotic Analysis) Mutex vs Semaphore Understanding "extern" keyword in C Time Complexity and Space Complexity SQL | Views Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Arrays in C/C++ Bitwise Operators in C/C++ std::sort() in C++ STL Multidimensional Arrays in C / C++
[ { "code": null, "e": 24454, "s": 24426, "text": "\n05 Nov, 2020" }, { "code": null, "e": 24483, "s": 24454, "text": "Consider the below program. " }, { "code": null, "e": 24485, "s": 24483, "text": "C" }, { "code": "void read(){ char str[20]; gets(...
Start Coding | Practice | GeeksforGeeks
When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (cout<<"Hello World") to print Hello World. Input Format :No input Output format :Hello World Your Task:Your task is to complete the function below to print Hello World. Explanation:Hello World is printed. Video: YouTubeGeeksforGeeks502K subscribersC++ Programming Language Tutorial | Writing first C++ program : Hello World example | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=37GG-T6B7bc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 0 mathurpriyansh1519 hours ago void printHello(){ // Your code goes here cout<<"Hello World"; } 0 programmeramit4444 days ago #include <iostream>using namespace std; int main() { cout << “hello world”; return 0; } 0 noboy254 weeks ago #include<iostream> using namespace std; int main(){ cout<<"HELLO WORLD"; return 0; } 0 itsriyakundu4 weeks ago #include <iostream> using namespace std; int main( ) { cout<<"Hello World"; return 0; } 0 me12110331 month ago Error in driver code .NO need to put ; after function printhello(). 0 ak21eeb0b062 months ago #include <iostream> using namespace std; int main( ) { cout <<"Hello World" return 0; } 0 alekhya119129142 months ago cant able to type code 0 sumitmaurya20152 months ago #include <iostream> using namespace std; int main( ) { cout <<"Hello World" return 0; } 0 ritikakhatri578 This comment was deleted. 0 rohitkumar012 months ago void printHello(){ cout<<"Hello World"; } 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": 512, "s": 226, "text": "When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (cout<<\"Hell...
SaltStack - Installation
Before moving to installation, you need to have the following requirements − A Linux server (latest Ubuntu server). A Linux server (latest Ubuntu server). sudo or root access to this server. sudo or root access to this server. Install all the updates using the following command − sudo apt-get update Install the SaltMaster from the repository with the following apt-get command. sudo apt-get install salt-master Install the Salt minion from the repository with the following apt-get command. sudo apt-get install salt-minion Install the Salt syndic from the repository with the following apt-get command. sudo apt-get install salt-syndic Salt configuration is very simple. The default configuration for the master will work for most installations. The configuration files are installed in the ‘/etc/salt’ directory and are named after their respective components, such as − /etc/salt/master and /etc/salt/minion. #interface: 0.0.0.0 interface: <local ip address> After updating the configuration file, restart the Salt master using the following command. sudo service salt-master restart Configuring a Salt Minion is very simple. By default a Salt Minion will try to connect to the DNS name “salt”; if the Minion is able to resolve that name correctly, no configuration is required. Redefine the “master” directive in the minion configuration file, which is typically /etc/salt/minion, as shown in the code below − #master: salt master: <local ip address> After updating the configuration file, restart the Salt minion using the command below. sudo service salt-minion restart Salt uses AES Encryption for all the communication between the Master and the Minion. The communication between Master and Minion is authenticated through trusted, accepted keys. salt-key -L It will produce the following output − Accepted Keys: Denied Keys: Unaccepted Keys: <local system name> Rejected Keys: Accept all keys by issuing the command below. sudo salt-key -A It will produce the following output − The following keys are going to be accepted: Unaccepted Keys: <local system name> Proceed? [n/Y] y Key for minion bala-Inspiron-N4010 accepted. Now again issue the salt key listing command, salt-key -L It will produce the following output − Accepted Keys: <local system name> Denied Keys: Unaccepted Keys: Rejected Keys: The communication between the Master and a Minion must be verified by running the test.ping command. sudo salt '*' test.ping It will produce the following output − <local system name> True Here, ‘*’ refers to all the minions. Since, we only have one minion – test.ping, it executes the ping command and returns whether the ping is successful or not. Print Add Notes Bookmark this page
[ { "code": null, "e": 2284, "s": 2207, "text": "Before moving to installation, you need to have the following requirements −" }, { "code": null, "e": 2323, "s": 2284, "text": "A Linux server (latest Ubuntu server)." }, { "code": null, "e": 2362, "s": 2323, "tex...
How to edit values of an object inside an array in a class - JavaScript?
For this, use the “this” keyword. Following is the code − class Employee { constructor() { this.tempObject = [ { firstName: "David", setTheAnotherFirstName() { this.firstName = "Carol"; }, }, ]; } } var empObject = new Employee(); empObject.tempObject[0].setTheAnotherFirstName(); console.log("The Change First Name is=" + empObject.tempObject[0].firstName); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo220.js. The output is as follows − PS C:\Users\Amit\JavaScript-code> node demo220.js The Change First Name is=Carol
[ { "code": null, "e": 1096, "s": 1062, "text": "For this, use the “this” keyword." }, { "code": null, "e": 1120, "s": 1096, "text": "Following is the code −" }, { "code": null, "e": 1540, "s": 1120, "text": "class Employee {\n constructor() {\n this.t...
How to find the minimum value of an array in JavaScript?
Math.min() function usually takes all the elements in an array and scrutinize each and every value to get the minimum value.It's methodology is discussed in the below example. Live Demo Example <html> <body> <script> function minimum(value) { if (toString.call(value) !== "[object Array]") return false; return Math.min.apply(null, value); } document.write(minimum([6,39,55,1,44])); </script> </body> </html> 1 Using sort() and compare functions we can write the elements in ascending or descending order, later on using length property we can find the minimum in the following way Live Demo <html> <body> <input type ="button" onclick="myFunction()" value = "clickme"> <p id="min"></p> <script> var numbers = [6,39,55,1,44]; document.getElementById("min").innerHTML = numbers; function myFunction() { numbers.sort(function(a, b){return b - a}); document.getElementById("min").innerHTML = numbers; document.write(numbers[numbers.length-1]); } </script> </body> </html> After running the program the out put will be shown as in the following image On clicking the click me button above the output would display as 1
[ { "code": null, "e": 1238, "s": 1062, "text": "Math.min() function usually takes all the elements in an array and scrutinize each and every value to get the minimum value.It's methodology is discussed in the below example." }, { "code": null, "e": 1249, "s": 1238, "text": " Live ...
SQLAlchemy Core - Using Aliases
The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name. In case of a table, this allows the same table to be named in the FROM clause multiple times. It provides a parent name for the columns represented by the statement, allowing them to be referenced relative to this name. In SQLAlchemy, any Table, select() construct, or other selectable object can be turned into an alias using the From Clause.alias() method, which produces an Alias construct. The alias() function in sqlalchemy.sql module represents an alias, as typically applied to any table or sub-select within a SQL statement using the AS keyword. from sqlalchemy.sql import alias st = students.alias("a") This alias can now be used in select() construct to refer to students table − s = select([st]).where(st.c.id>2) This translates to SQL expression as follows − SELECT a.id, a.name, a.lastname FROM students AS a WHERE a.id > 2 We can now execute this SQL query with the execute() method of connection object. The complete code is as follows − from sqlalchemy.sql import alias, select st = students.alias("a") s = select([st]).where(st.c.id > 2) conn.execute(s).fetchall() When above line of code is executed, it generates the following output − [(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar'), (5, 'Priya', 'Rajhans')] 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2594, "s": 2340, "text": "The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name....
Difference between DOMContentLoaded and load Events - GeeksforGeeks
18 Nov, 2019 These two events DOMContentLoaded and load are used to check when a webpage has loaded completely. Still, there are some factors that determine the preference of one over the other. Let’s have a look at both of them and understand their working. DOMContentLoaded event gets executed once the basic HTML document is loaded and its parsing has taken place. This event doesn’t wait for the completion of the loading of add-ons such as stylesheets, sub-frames and images/pictures. Syntax: document.addEventListener("DOMContentLoaded", function(e) { console.log("GfG page has loaded"); }); Example 1: <!DOCTYPE><html> <head> <title> Output of DOMContentLoaded and Load events </title> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function(e) { console.log("GfG page has loaded"); }); </script></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png" style="align-content: center"></body> </html> Output: Here in the output, it can be seen that the console log window displays the message, which signifies the completion of loading the DOM of the webpage. Advantages of using DOMContentLoaded event: It helps in improving user experience as it shows messages or content much faster. It takes lesser time in loading the page. load event performs its execution differently. This event gets completed once all the components i.e. DOM hierarchy along with associated features of a webpage such as CSS files, JavaScript files, images/pictures, and external links are loaded. So basically, the load event helps in knowing when the page has fully-loaded. Syntax: document.addEventListener("load", function(e) { console.log("The page has completely loaded."); }); Example 2: <!DOCTYPE html><html> <head> <title> Output of DOMContentLoaded and Load events </title> <script type="text/javascript"> document.addEventListener("load", function(e) { console.log("GfG page has loaded completely"); }); </script></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png" style="align-content: center"></body> </html> Output: Advantages of using load event: This event helps in knowing when all the components of the webpage is loaded. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM HTML-Misc Picked Difference Between HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Mealy machine and Moore machine Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24858, "s": 24830, "text": "\n18 Nov, 2019" }, { "code": null, "e": 25104, "s": 24858, "text": "These two events DOMContentLoaded and load are used to check when a webpage has loaded completely. Still, there are some factors that determine the preference of o...
C# | Insert an object at the top of the Stack - Push Operation - GeeksforGeeks
01 Feb, 2019 Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.Push(T) Method is used to inserts an object at the top of the Stack<T>. Properties: The capacity of a Stack<T> is the number of elements the Stack<T> can hold. As elements are added to a Stack<T> , the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. Stack<T> accepts null as a valid value and allows duplicate elements. Syntax: void Push(object obj); Example: // C# code to insert an object// at the top of the Stackusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push("one"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); myStack.Push("two"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); myStack.Push("three"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); myStack.Push("four"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); myStack.Push("five"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); myStack.Push("six"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); }} Total number of elements in the Stack are : 1 Total number of elements in the Stack are : 2 Total number of elements in the Stack are : 3 Total number of elements in the Stack are : 4 Total number of elements in the Stack are : 5 Total number of elements in the Stack are : 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.push?view=netframework-4.7.2 CSharp-Generic-Namespace CSharp-Generic-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Method Overriding C# Dictionary with examples C# | Delegates Difference between Ref and Out keywords in C# Destructors in C# Extension Method in C# C# | Constructors C# | Abstract Classes Introduction to .NET Framework C# | Class and Object
[ { "code": null, "e": 24466, "s": 24438, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24789, "s": 24466, "text": "Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is ...
Python 3 - List list() Method
The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket. This function also converts characters in a string into a list. Following is the syntax for list() method − list( seq ) seq − This is a tuple or string to be converted into list. This method returns the list. The following example shows the usage of list() method. #!/usr/bin/python3 aTuple = (123, 'C++', 'Java', 'Python') list1 = list(aTuple) print ("List elements : ", list1) str = "Hello World" list2 = list(str) print ("List elements : ", list2) When we run above program, it produces the following result − List elements : [123, 'C++', 'Java', 'Python'] List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] 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": 2456, "s": 2340, "text": "The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list." }, { "code": null, "e": 2704, "s": 2456, "text": "Note − Tuple are very similar to lists with only difference that e...
How to setup cookies in Python CGI Programming?
It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows − #!/usr/bin/python print "Set-Cookie:UserID = XYZ;\r\n" print "Set-Cookie:Password = XYZ123;\r\n" print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT;\r\n" print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n" print "Set-Cookie:Path = /perl;\n" print "Content-type:text/html\r\n\r\n" ...........Rest of the HTML Content.... From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
[ { "code": null, "e": 1280, "s": 1062, "text": "It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows −" }, { "code": null, "e"...