title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
SQL ALTER TABLE Statement | The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on
an existing table.
To add a column in a table, use the following syntax:
The following SQL adds an "Email" column to the "Customers" table:
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
The following SQL deletes the "Email" column from the "Customers" table:
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
My SQL / Oracle (prior version 10G):
Oracle 10G and later:
Look at the "Persons" table:
Now we want to add a column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a
date. The data type specifies what type of data the column can hold. For a complete
reference of all the data types available in MS Access, MySQL, and SQL Server,
go to our complete Data Types reference.
The "Persons" table will now look like this:
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-digit format.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
The "Persons" table will now look like this:
Add a column of type DATE called Birthday.
Persons
;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 90,
"s": 0,
"text": "The ALTER TABLE statement is used to add, delete, or modify columns in an existing table."
},
{
"code": null,
"e": 188,
"s": 90,
"text": "The ALTER TABLE statement is also used to add and drop various constraints on \nan existing table."
},
{
"code": null,
"e": 242,
"s": 188,
"text": "To add a column in a table, use the following syntax:"
},
{
"code": null,
"e": 309,
"s": 242,
"text": "The following SQL adds an \"Email\" column to the \"Customers\" table:"
},
{
"code": null,
"e": 433,
"s": 309,
"text": "To delete a column in a table, use the following syntax (notice that some \ndatabase systems don't allow deleting a column):"
},
{
"code": null,
"e": 506,
"s": 433,
"text": "The following SQL deletes the \"Email\" column from the \"Customers\" table:"
},
{
"code": null,
"e": 580,
"s": 506,
"text": "To change the data type of a column in a table, use the following syntax:"
},
{
"code": null,
"e": 604,
"s": 580,
"text": "SQL Server / MS Access:"
},
{
"code": null,
"e": 641,
"s": 604,
"text": "My SQL / Oracle (prior version 10G):"
},
{
"code": null,
"e": 663,
"s": 641,
"text": "Oracle 10G and later:"
},
{
"code": null,
"e": 692,
"s": 663,
"text": "Look at the \"Persons\" table:"
},
{
"code": null,
"e": 764,
"s": 692,
"text": "Now we want to add a column named \"DateOfBirth\" in the \"Persons\" table."
},
{
"code": null,
"e": 800,
"s": 764,
"text": "We use the following SQL statement:"
},
{
"code": null,
"e": 1089,
"s": 800,
"text": "Notice that the new column, \"DateOfBirth\", is of type date and is going to hold a \ndate. The data type specifies what type of data the column can hold. For a complete \nreference of all the data types available in MS Access, MySQL, and SQL Server, \ngo to our complete Data Types reference."
},
{
"code": null,
"e": 1134,
"s": 1089,
"text": "The \"Persons\" table will now look like this:"
},
{
"code": null,
"e": 1228,
"s": 1134,
"text": "Now we want to change the data type of the column named \"DateOfBirth\" in the \"Persons\" table."
},
{
"code": null,
"e": 1264,
"s": 1228,
"text": "We use the following SQL statement:"
},
{
"code": null,
"e": 1381,
"s": 1264,
"text": "Notice that the \"DateOfBirth\" column is now of type year and is going to hold a year in a two- or four-digit format."
},
{
"code": null,
"e": 1460,
"s": 1381,
"text": "Next, we want to delete the column named \"DateOfBirth\" in the \"Persons\" table."
},
{
"code": null,
"e": 1496,
"s": 1460,
"text": "We use the following SQL statement:"
},
{
"code": null,
"e": 1541,
"s": 1496,
"text": "The \"Persons\" table will now look like this:"
},
{
"code": null,
"e": 1584,
"s": 1541,
"text": "Add a column of type DATE called Birthday."
},
{
"code": null,
"e": 1596,
"s": 1584,
"text": " Persons\n;\n"
},
{
"code": null,
"e": 1615,
"s": 1596,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1648,
"s": 1615,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1690,
"s": 1648,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1797,
"s": 1690,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1816,
"s": 1797,
"text": "[email protected]"
}
] |
Sorting a Dictionary in Python. How to sort a dictionary in python | by Luay Matalka | Towards Data Science | We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python’s built-in sorted() function. Just like with other iterables, we can sort dictionaries based on different criteria depending on the key argument of the sorted() function.
In this tutorial, we will learn how to sort dictionaries using the sorted() function in python.
The sorted() function can accept three parameters: the iterable, the key, and reverse.
sorted(iterable, key, reverse)
In contrast to the sort() method which only works on lists, the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged.
Note: No matter what iterable is passed in to the sorted() function, it always returns a list.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
Let’s say that we have a dictionary, with the keys being names, and the values being ages.
dictionary_of_names = {'beth': 37, 'jane': 32, 'john': 41, 'mike': 59}
If we just pass in the entire dictionary as the iterable to the sorted() function, we will get the following output:
print(sorted(dictionary_of_names))# ['beth', 'jane', 'john', 'mike']
As we can see, if we pass in the entire dictionary as the iterable to the sorted() function, it returns a list that contains only the keys sorted alphabetically.
towardsdatascience.com
If we want to get a sorted copy of the entire dictionary, we need to use the dictionary items() method:
print(dictionary_of_names.items())# dict_items([('beth', 37), ('jane', 32), ('john', 41), ('mike', 59)])
Notice how the items() method returns a dict_items object, which looks similar to a list of tuples. This dict_items object is an iterable. Thus, it can be passed in as the iterable to the sorted() function.
We can sort this dict_items object the same way we sorted the list of tuples seen earlier. For example, to sort by the second element in each tuple, which would be the age, we can use the following code:
sorted_age = sorted(dictionary_of_names.items(), key = lambda kv: kv[1])print(sorted_age)# [('jane', 32), ('beth', 37), ('john', 41), ('mike', 59)]
Notice how the sorted() function returns a list of tuples, sorted by the age (or second element in each tuple). To convert this list of tuples into a dictionary, we can use the built-in dict() function:
sorted_dictionary = dict(sorted_age)print(sorted_dictionary)# {'jane': 32, 'beth': 37, 'john': 41, 'mike': 59}
Now we have a dictionary sorted by age!
Let’s say that we want to create a function that when passed a list of numbers, returns a sorted dictionary that contains the numbers and their counts in ascending order. Thus, we can have the keys of the dictionary being the different elements (or numbers) in the list, and their corresponding values equal to the number of times that specific element (or number) shows up in the list.
Well, we can accomplish this task with the following function:
nums = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]def count(num_list): count_dict = {} for num in num_list: count_dict[num] = num_list.count(num) return dict(sorted(count_dict.items(), key=lambda x:x[1]))print(count(nums))# {7: 1, 5: 2, 9: 2, 1: 3, 3: 3, 2: 6}
We first define the function count() with one parameter, num_list. Within the function, we first create an empty dictionary, count_dict. Then as we loop through num_list, which will be the list passed as an argument to the function, using a for loop, we are creating key:value pairs in count_dict. The key will equal the current number we are on while iterating through num_list, and its corresponding value is equal to the count of that number in num_list. Finally, we return the sorted dictionary.
count() is a list method that returns the number of times the value we pass in occurs in our list.
We can further shorten this function by using a dictionary comprehension to create the count_dict dictionary instead of a for loop:
def count(num_list): count_dict = {num:num_list.count(num) for num in num_list} return dict(sorted(count_dict.items(), key=lambda x:x[1]))
We use curly brackets to establish that we want to create a dictionary (as opposed to a list where we would use brackets in a list comprehension). Then, as we loop over num_list, we are creating key:value pairs as follows: num:num_list.count(num), where the key is the number (or num), and its value being the count of that number in num_list.
We can shorten this function to only one line of code by using the items() method directly on the dictionary comprehension:
def count(num_list): return dict(sorted({num:num_list.count(num) for num in num_list}.items(), key=lambda x:x[1]))
For more information on dictionary comprehensions, check out the following:
towardsdatascience.com
In this tutorial, we briefly reviewed the sorted() function. We learned how the sorted() function works on any iterable object (without modifying it) and returns a new list, but the sort() method only works on lists and modifies them in-place and returns None. Lastly, we saw how we can use the sorted() function to sort dictionaries in python. | [
{
"code": null,
"e": 591,
"s": 172,
"text": "We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python’s built-in sorted() function. Just like with other iterables, we can sort dictionaries based on different criteria depending on the key argument of the sorted() function."
},
{
"code": null,
"e": 687,
"s": 591,
"text": "In this tutorial, we will learn how to sort dictionaries using the sorted() function in python."
},
{
"code": null,
"e": 774,
"s": 687,
"text": "The sorted() function can accept three parameters: the iterable, the key, and reverse."
},
{
"code": null,
"e": 805,
"s": 774,
"text": "sorted(iterable, key, reverse)"
},
{
"code": null,
"e": 1133,
"s": 805,
"text": "In contrast to the sort() method which only works on lists, the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged."
},
{
"code": null,
"e": 1228,
"s": 1133,
"text": "Note: No matter what iterable is passed in to the sorted() function, it always returns a list."
},
{
"code": null,
"e": 1329,
"s": 1228,
"text": "Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values."
},
{
"code": null,
"e": 1420,
"s": 1329,
"text": "Let’s say that we have a dictionary, with the keys being names, and the values being ages."
},
{
"code": null,
"e": 1559,
"s": 1420,
"text": "dictionary_of_names = {'beth': 37, 'jane': 32, 'john': 41, 'mike': 59}"
},
{
"code": null,
"e": 1676,
"s": 1559,
"text": "If we just pass in the entire dictionary as the iterable to the sorted() function, we will get the following output:"
},
{
"code": null,
"e": 1745,
"s": 1676,
"text": "print(sorted(dictionary_of_names))# ['beth', 'jane', 'john', 'mike']"
},
{
"code": null,
"e": 1907,
"s": 1745,
"text": "As we can see, if we pass in the entire dictionary as the iterable to the sorted() function, it returns a list that contains only the keys sorted alphabetically."
},
{
"code": null,
"e": 1930,
"s": 1907,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2034,
"s": 1930,
"text": "If we want to get a sorted copy of the entire dictionary, we need to use the dictionary items() method:"
},
{
"code": null,
"e": 2139,
"s": 2034,
"text": "print(dictionary_of_names.items())# dict_items([('beth', 37), ('jane', 32), ('john', 41), ('mike', 59)])"
},
{
"code": null,
"e": 2346,
"s": 2139,
"text": "Notice how the items() method returns a dict_items object, which looks similar to a list of tuples. This dict_items object is an iterable. Thus, it can be passed in as the iterable to the sorted() function."
},
{
"code": null,
"e": 2550,
"s": 2346,
"text": "We can sort this dict_items object the same way we sorted the list of tuples seen earlier. For example, to sort by the second element in each tuple, which would be the age, we can use the following code:"
},
{
"code": null,
"e": 2698,
"s": 2550,
"text": "sorted_age = sorted(dictionary_of_names.items(), key = lambda kv: kv[1])print(sorted_age)# [('jane', 32), ('beth', 37), ('john', 41), ('mike', 59)]"
},
{
"code": null,
"e": 2901,
"s": 2698,
"text": "Notice how the sorted() function returns a list of tuples, sorted by the age (or second element in each tuple). To convert this list of tuples into a dictionary, we can use the built-in dict() function:"
},
{
"code": null,
"e": 3012,
"s": 2901,
"text": "sorted_dictionary = dict(sorted_age)print(sorted_dictionary)# {'jane': 32, 'beth': 37, 'john': 41, 'mike': 59}"
},
{
"code": null,
"e": 3052,
"s": 3012,
"text": "Now we have a dictionary sorted by age!"
},
{
"code": null,
"e": 3439,
"s": 3052,
"text": "Let’s say that we want to create a function that when passed a list of numbers, returns a sorted dictionary that contains the numbers and their counts in ascending order. Thus, we can have the keys of the dictionary being the different elements (or numbers) in the list, and their corresponding values equal to the number of times that specific element (or number) shows up in the list."
},
{
"code": null,
"e": 3502,
"s": 3439,
"text": "Well, we can accomplish this task with the following function:"
},
{
"code": null,
"e": 3771,
"s": 3502,
"text": "nums = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]def count(num_list): count_dict = {} for num in num_list: count_dict[num] = num_list.count(num) return dict(sorted(count_dict.items(), key=lambda x:x[1]))print(count(nums))# {7: 1, 5: 2, 9: 2, 1: 3, 3: 3, 2: 6}"
},
{
"code": null,
"e": 4271,
"s": 3771,
"text": "We first define the function count() with one parameter, num_list. Within the function, we first create an empty dictionary, count_dict. Then as we loop through num_list, which will be the list passed as an argument to the function, using a for loop, we are creating key:value pairs in count_dict. The key will equal the current number we are on while iterating through num_list, and its corresponding value is equal to the count of that number in num_list. Finally, we return the sorted dictionary."
},
{
"code": null,
"e": 4370,
"s": 4271,
"text": "count() is a list method that returns the number of times the value we pass in occurs in our list."
},
{
"code": null,
"e": 4502,
"s": 4370,
"text": "We can further shorten this function by using a dictionary comprehension to create the count_dict dictionary instead of a for loop:"
},
{
"code": null,
"e": 4647,
"s": 4502,
"text": "def count(num_list): count_dict = {num:num_list.count(num) for num in num_list} return dict(sorted(count_dict.items(), key=lambda x:x[1]))"
},
{
"code": null,
"e": 4991,
"s": 4647,
"text": "We use curly brackets to establish that we want to create a dictionary (as opposed to a list where we would use brackets in a list comprehension). Then, as we loop over num_list, we are creating key:value pairs as follows: num:num_list.count(num), where the key is the number (or num), and its value being the count of that number in num_list."
},
{
"code": null,
"e": 5115,
"s": 4991,
"text": "We can shorten this function to only one line of code by using the items() method directly on the dictionary comprehension:"
},
{
"code": null,
"e": 5233,
"s": 5115,
"text": "def count(num_list): return dict(sorted({num:num_list.count(num) for num in num_list}.items(), key=lambda x:x[1]))"
},
{
"code": null,
"e": 5309,
"s": 5233,
"text": "For more information on dictionary comprehensions, check out the following:"
},
{
"code": null,
"e": 5332,
"s": 5309,
"text": "towardsdatascience.com"
}
] |
Solidity - Mapping | Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping type.
mapping(_KeyType => _ValueType)
Where
_KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed.
_KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed.
_ValueType − can be any type.
_ValueType − can be any type.
Mapping can only have type of storage and are generally used for state variables.
Mapping can only have type of storage and are generally used for state variables.
Mapping can be marked public. Solidity automatically create getter for it.
Mapping can be marked public. Solidity automatically create getter for it.
Try the following code to understand how the mapping type works in Solidity.
pragma solidity ^0.5.0;
contract LedgerBalance {
mapping(address => uint) public balances;
function updateBalance(uint newBalance) public {
balances[msg.sender] = newBalance;
}
}
contract Updater {
function updateBalance() public returns (uint) {
LedgerBalance ledgerBalance = new LedgerBalance();
ledgerBalance.updateBalance(10);
return ledgerBalance.balances(address(this));
}
}
Run the above program using steps provided in Solidity First Application chapter.
First Click updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as −
{
"0": "uint256: 10"
}
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2657,
"s": 2555,
"text": "Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping type."
},
{
"code": null,
"e": 2690,
"s": 2657,
"text": "mapping(_KeyType => _ValueType)\n"
},
{
"code": null,
"e": 2696,
"s": 2690,
"text": "Where"
},
{
"code": null,
"e": 2806,
"s": 2696,
"text": "_KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed."
},
{
"code": null,
"e": 2916,
"s": 2806,
"text": "_KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed."
},
{
"code": null,
"e": 2946,
"s": 2916,
"text": "_ValueType − can be any type."
},
{
"code": null,
"e": 2976,
"s": 2946,
"text": "_ValueType − can be any type."
},
{
"code": null,
"e": 3058,
"s": 2976,
"text": "Mapping can only have type of storage and are generally used for state variables."
},
{
"code": null,
"e": 3140,
"s": 3058,
"text": "Mapping can only have type of storage and are generally used for state variables."
},
{
"code": null,
"e": 3215,
"s": 3140,
"text": "Mapping can be marked public. Solidity automatically create getter for it."
},
{
"code": null,
"e": 3290,
"s": 3215,
"text": "Mapping can be marked public. Solidity automatically create getter for it."
},
{
"code": null,
"e": 3367,
"s": 3290,
"text": "Try the following code to understand how the mapping type works in Solidity."
},
{
"code": null,
"e": 3789,
"s": 3367,
"text": "pragma solidity ^0.5.0;\n\ncontract LedgerBalance {\n mapping(address => uint) public balances;\n\n function updateBalance(uint newBalance) public {\n balances[msg.sender] = newBalance;\n }\n}\ncontract Updater {\n function updateBalance() public returns (uint) {\n LedgerBalance ledgerBalance = new LedgerBalance();\n ledgerBalance.updateBalance(10);\n return ledgerBalance.balances(address(this));\n }\n}"
},
{
"code": null,
"e": 3871,
"s": 3789,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 3992,
"s": 3871,
"text": "First Click updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as − "
},
{
"code": null,
"e": 4019,
"s": 3992,
"text": "{\n \"0\": \"uint256: 10\"\n}\n"
},
{
"code": null,
"e": 4054,
"s": 4019,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4071,
"s": 4054,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4106,
"s": 4071,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4123,
"s": 4106,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4158,
"s": 4123,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4172,
"s": 4158,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 4179,
"s": 4172,
"text": " Print"
},
{
"code": null,
"e": 4190,
"s": 4179,
"text": " Add Notes"
}
] |
Fraction - GeeksforGeeks | 14 May, 2021
A fraction is a ratio of two values. Fractions have the form a/b where a is called the numerator, b is called the denominator and b cannot equal 0 (since division by 0 is undefined). The denominator gives how many equal parts are there. The numerator represents how many of these are taken. For example, one-half, eight-fifths, three-quarters (1/2, 8/5, 3/4).
Fact about Fraction :
Fractions can be reduced if the numerator and denominator have the greatest common divisor(gcd) greater than 1.Addition and Subtraction of Fractions: When adding or subtracting fractions, they must have the same denominator. If they do not have the same denominator, we must find a common one for both. To do this, we first need to find the lowest common multiple(lcm) of the two denominators or multiply each fraction by the proper integers so that there will be the same denominator. Multiplication and Division of Fractions: When multiplying two fractions, simply multiply the two numerators and multiply the two denominators. When dividing two fractions, the first fraction must be multiplied by the reciprocal of the second fraction.There are three types of fractions :Proper Fractions: The numerator is less than the denominator. For Example, 1/3, 3/4, 2/7Improper Fractions: The numerator is greater than (or equal to) the denominator. For Example, 4/3, 11/4, 7/7.Mixed Fractions: A whole number and proper fraction together. For Example, 1 1/3, 2 1/4, 16 2/5.
Fractions can be reduced if the numerator and denominator have the greatest common divisor(gcd) greater than 1.
Addition and Subtraction of Fractions: When adding or subtracting fractions, they must have the same denominator. If they do not have the same denominator, we must find a common one for both. To do this, we first need to find the lowest common multiple(lcm) of the two denominators or multiply each fraction by the proper integers so that there will be the same denominator.
Multiplication and Division of Fractions: When multiplying two fractions, simply multiply the two numerators and multiply the two denominators. When dividing two fractions, the first fraction must be multiplied by the reciprocal of the second fraction.
There are three types of fractions :Proper Fractions: The numerator is less than the denominator. For Example, 1/3, 3/4, 2/7Improper Fractions: The numerator is greater than (or equal to) the denominator. For Example, 4/3, 11/4, 7/7.Mixed Fractions: A whole number and proper fraction together. For Example, 1 1/3, 2 1/4, 16 2/5.
Proper Fractions: The numerator is less than the denominator. For Example, 1/3, 3/4, 2/7
Improper Fractions: The numerator is greater than (or equal to) the denominator. For Example, 4/3, 11/4, 7/7.
Mixed Fractions: A whole number and proper fraction together. For Example, 1 1/3, 2 1/4, 16 2/5.
How to add two fractions? Add two fractions a/b and c/d and print the answer in the simplest form.
Examples :
Input: 1/2 + 3/2
Output: 2/1
Input: 1/3 + 3/9
Output: 2/3
Input: 1/5 + 3/15
Output: 2/5
Algorithm to add two fractions
Find a common denominator by finding the LCM (The Least Common Multiple) of the two denominators.
Change the fractions to have the same denominator and add both terms.
Reduce the final fraction obtained into its simpler form by dividing both numerator and denominator by their largest common factor.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to add 2 fractions#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to convert the obtained fraction// into it's simplest formvoid lowest(int& den3, int& num3){ // Finding gcd of both terms int common_factor = gcd(num3, den3); // Converting both terms into simpler // terms by dividing them by common factor den3 = den3 / common_factor; num3 = num3 / common_factor;} // Function to add two fractionsvoid addFraction(int num1, int den1, int num2, int den2, int& num3, int& den3){ // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final fraction obtained // finding LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to have same denominator // Numerator of the final fraction obtained num3 = (num1) * (den3 / den1) + (num2) * (den3 / den2); // Calling function to convert final fraction // into it's simplest form lowest(den3, num3);} // Driver programint main(){ int num1 = 1, den1 = 500, num2 = 2, den2 = 1500, den3, num3; addFraction(num1, den1, num2, den2, num3, den3); printf("%d/%d + %d/%d is equal to %d/%d\n", num1, den1, num2, den2, num3, den3); return 0;}
// Java program to add 2 fractionsimport java.util.*; class GFG{static int den3, num3; // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to convert the obtained fraction// into it's simplest formstatic void lowest(){ // Finding gcd of both terms int common_factor = gcd(num3, den3); // Converting both terms into simpler // terms by dividing them by common factor den3 = den3 / common_factor; num3 = num3 / common_factor;} // Function to add two fractionsstatic void addFraction(int num1, int den1, int num2, int den2){ // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final fraction obtained // finding LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to have // same denominator. // Numerator of the final fraction obtained num3 = (num1) * (den3 / den1) + (num2) * (den3 / den2); // Calling function to convert final fraction // into it's simplest form lowest();} // Driver Codepublic static void main(String[] args){ int num1 = 1, den1 = 500, num2 = 2, den2 = 1500; addFraction(num1, den1, num2, den2); System.out.printf("%d/%d + %d/%d is equal to %d/%d\n", num1, den1, num2, den2, num3, den3);}} // This code is contributed by Rajput-Ji
# Python3 program to add 2 fractions # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Function to convert the obtained# fraction into it's simplest formdef lowest(den3, num3): # Finding gcd of both terms common_factor = gcd(num3, den3) # Converting both terms # into simpler terms by # dividing them by common factor den3 = int(den3 / common_factor) num3 = int(num3 / common_factor) print(num3, "/", den3) # Function to add two fractionsdef addFraction(num1, den1, num2, den2): # Finding gcd of den1 and den2 den3 = gcd(den1, den2) # Denominator of final # fraction obtained finding # LCM of den1 and den2 # LCM * GCD = a * b den3 = (den1 * den2) / den3 # Changing the fractions to # have same denominator Numerator # of the final fraction obtained num3 = ((num1) * (den3 / den1) + (num2) * (den3 / den2)) # Calling function to convert # final fraction into it's # simplest form lowest(den3, num3) # Driver Codenum1 = 1; den1 = 500num2 = 2; den2 = 1500 print(num1, "/", den1, " + ", num2, "/", den2, " is equal to ", end = "") addFraction(num1, den1, num2, den2)
// C# program to add 2 fractionsusing System; class GFG{static int den3, num3; // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to convert the obtained fraction// into it's simplest formstatic void lowest(){ // Finding gcd of both terms int common_factor = gcd(num3, den3); // Converting both terms into simpler // terms by dividing them by common factor den3 = den3 / common_factor; num3 = num3 / common_factor;} // Function to add two fractionsstatic void addFraction(int num1, int den1, int num2, int den2){ // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final fraction obtained // finding LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to have // same denominator. // Numerator of the final fraction obtained num3 = (num1) * (den3 / den1) + (num2) * (den3 / den2); // Calling function to convert final fraction // into it's simplest form lowest();} // Driver Codepublic static void Main(String[] args){ int num1 = 1, den1 = 500, num2 = 2, den2 = 1500; addFraction(num1, den1, num2, den2); Console.Write("{0}/{1} + {2}/{3} is equal to {4}/{5}\n", num1, den1, num2, den2, num3, den3);}} // This code is contributed by PrinciRaj1992
<?php// PHP program to add// 2 fractions // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to convert the// obtained fraction into// it's simplest formfunction lowest(&$den3, &$num3){ // Finding gcd of both terms $common_factor = gcd($num3, $den3); // Converting both terms // into simpler terms by // dividing them by common factor $den3 = (int)$den3 / $common_factor; $num3 = (int) $num3 / $common_factor;} // Function to add// two fractionsfunction addFraction($num1, $den1, $num2, $den2, &$num3, &$den3){ // Finding gcd of den1 and den2 $den3 = gcd($den1, $den2); // Denominator of final // fraction obtained finding // LCM of den1 and den2 // LCM * GCD = a * b $den3 = ($den1 * $den2) / $den3; // Changing the fractions to // have same denominator Numerator // of the final fraction obtained $num3 = ($num1) * ($den3 / $den1) + ($num2) * ($den3 / $den2); // Calling function to convert // final fraction into it's // simplest form lowest($den3, $num3);} // Driver Code$num1 = 1; $den1 = 500;$num2 = 2; $den2 = 1500;$den3; $num3;addFraction($num1, $den1, $num2, $den2, $num3, $den3);echo $num1, "/", $den1, " + ", $num2, "/", $den2, " is equal to ", $num3, "/", $den3, "\n"; ?>
<script> // JavaScript program to add // 2 fractions // Function to return // gcd of a and b function gcd(a, b) { if (a === 0) return b; return gcd(b % a, a); } // Function to convert the // obtained fraction into // it's simplest form function lowest(den3, num3) { // Finding gcd of both terms var common_factor = gcd(num3, den3); // Converting both terms // into simpler terms by // dividing them by common factor den3 = parseInt(den3 / common_factor); num3 = parseInt(num3 / common_factor); return [den3, num3]; } // Function to add // two fractions function addFraction(num1, den1, num2, den2, num3, den3) { // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final // fraction obtained finding // LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to // have same denominator Numerator // of the final fraction obtained num3 = num1 * (den3 / den1) + num2 * (den3 / den2); // Calling function to convert // final fraction into it's // simplest form return lowest(den3, num3); } // Driver Code var num1 = 1, den1 = 500, num2 = 2, den2 = 1500, den3, num3; var [den3, num3] = addFraction(num1, den1, num2, den2, num3, den3); document.write( num1 + "/" + den1 + " + " + num2 + "/" + den2 + " is equal to " + num3 + "/" + den3 + "<br>" ); </script>
Output :
1/500 + 2/1500 is equal to 1/300
More problems related to Fraction:
LCM and HCF of fractions
Represent the fraction of two numbers in the string format
Program to compare two fractions
Convert Binary fraction to Decimal
Convert decimal fraction to binary number
Fractional Knapsack Problem
Find Recurring Sequence in a Fraction
Recent Articles on Fraction!
Rajput-Ji
princiraj1992
rdtank
Fraction
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Constructors in C++ | [
{
"code": null,
"e": 24155,
"s": 24127,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 24517,
"s": 24155,
"text": "A fraction is a ratio of two values. Fractions have the form a/b where a is called the numerator, b is called the denominator and b cannot equal 0 (since division by 0 is undefined). The denominator gives how many equal parts are there. The numerator represents how many of these are taken. For example, one-half, eight-fifths, three-quarters (1/2, 8/5, 3/4). "
},
{
"code": null,
"e": 24541,
"s": 24517,
"text": "Fact about Fraction : "
},
{
"code": null,
"e": 25610,
"s": 24541,
"text": "Fractions can be reduced if the numerator and denominator have the greatest common divisor(gcd) greater than 1.Addition and Subtraction of Fractions: When adding or subtracting fractions, they must have the same denominator. If they do not have the same denominator, we must find a common one for both. To do this, we first need to find the lowest common multiple(lcm) of the two denominators or multiply each fraction by the proper integers so that there will be the same denominator. Multiplication and Division of Fractions: When multiplying two fractions, simply multiply the two numerators and multiply the two denominators. When dividing two fractions, the first fraction must be multiplied by the reciprocal of the second fraction.There are three types of fractions :Proper Fractions: The numerator is less than the denominator. For Example, 1/3, 3/4, 2/7Improper Fractions: The numerator is greater than (or equal to) the denominator. For Example, 4/3, 11/4, 7/7.Mixed Fractions: A whole number and proper fraction together. For Example, 1 1/3, 2 1/4, 16 2/5."
},
{
"code": null,
"e": 25722,
"s": 25610,
"text": "Fractions can be reduced if the numerator and denominator have the greatest common divisor(gcd) greater than 1."
},
{
"code": null,
"e": 26099,
"s": 25722,
"text": "Addition and Subtraction of Fractions: When adding or subtracting fractions, they must have the same denominator. If they do not have the same denominator, we must find a common one for both. To do this, we first need to find the lowest common multiple(lcm) of the two denominators or multiply each fraction by the proper integers so that there will be the same denominator. "
},
{
"code": null,
"e": 26352,
"s": 26099,
"text": "Multiplication and Division of Fractions: When multiplying two fractions, simply multiply the two numerators and multiply the two denominators. When dividing two fractions, the first fraction must be multiplied by the reciprocal of the second fraction."
},
{
"code": null,
"e": 26682,
"s": 26352,
"text": "There are three types of fractions :Proper Fractions: The numerator is less than the denominator. For Example, 1/3, 3/4, 2/7Improper Fractions: The numerator is greater than (or equal to) the denominator. For Example, 4/3, 11/4, 7/7.Mixed Fractions: A whole number and proper fraction together. For Example, 1 1/3, 2 1/4, 16 2/5."
},
{
"code": null,
"e": 26771,
"s": 26682,
"text": "Proper Fractions: The numerator is less than the denominator. For Example, 1/3, 3/4, 2/7"
},
{
"code": null,
"e": 26881,
"s": 26771,
"text": "Improper Fractions: The numerator is greater than (or equal to) the denominator. For Example, 4/3, 11/4, 7/7."
},
{
"code": null,
"e": 26978,
"s": 26881,
"text": "Mixed Fractions: A whole number and proper fraction together. For Example, 1 1/3, 2 1/4, 16 2/5."
},
{
"code": null,
"e": 27077,
"s": 26978,
"text": "How to add two fractions? Add two fractions a/b and c/d and print the answer in the simplest form."
},
{
"code": null,
"e": 27090,
"s": 27077,
"text": "Examples : "
},
{
"code": null,
"e": 27183,
"s": 27090,
"text": "Input: 1/2 + 3/2\nOutput: 2/1\n\nInput: 1/3 + 3/9\nOutput: 2/3\n\nInput: 1/5 + 3/15\nOutput: 2/5"
},
{
"code": null,
"e": 27216,
"s": 27183,
"text": "Algorithm to add two fractions "
},
{
"code": null,
"e": 27314,
"s": 27216,
"text": "Find a common denominator by finding the LCM (The Least Common Multiple) of the two denominators."
},
{
"code": null,
"e": 27384,
"s": 27314,
"text": "Change the fractions to have the same denominator and add both terms."
},
{
"code": null,
"e": 27516,
"s": 27384,
"text": "Reduce the final fraction obtained into its simpler form by dividing both numerator and denominator by their largest common factor."
},
{
"code": null,
"e": 27520,
"s": 27516,
"text": "C++"
},
{
"code": null,
"e": 27525,
"s": 27520,
"text": "Java"
},
{
"code": null,
"e": 27533,
"s": 27525,
"text": "Python3"
},
{
"code": null,
"e": 27536,
"s": 27533,
"text": "C#"
},
{
"code": null,
"e": 27540,
"s": 27536,
"text": "PHP"
},
{
"code": null,
"e": 27551,
"s": 27540,
"text": "Javascript"
},
{
"code": "// C++ program to add 2 fractions#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to convert the obtained fraction// into it's simplest formvoid lowest(int& den3, int& num3){ // Finding gcd of both terms int common_factor = gcd(num3, den3); // Converting both terms into simpler // terms by dividing them by common factor den3 = den3 / common_factor; num3 = num3 / common_factor;} // Function to add two fractionsvoid addFraction(int num1, int den1, int num2, int den2, int& num3, int& den3){ // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final fraction obtained // finding LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to have same denominator // Numerator of the final fraction obtained num3 = (num1) * (den3 / den1) + (num2) * (den3 / den2); // Calling function to convert final fraction // into it's simplest form lowest(den3, num3);} // Driver programint main(){ int num1 = 1, den1 = 500, num2 = 2, den2 = 1500, den3, num3; addFraction(num1, den1, num2, den2, num3, den3); printf(\"%d/%d + %d/%d is equal to %d/%d\\n\", num1, den1, num2, den2, num3, den3); return 0;}",
"e": 28923,
"s": 27551,
"text": null
},
{
"code": "// Java program to add 2 fractionsimport java.util.*; class GFG{static int den3, num3; // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to convert the obtained fraction// into it's simplest formstatic void lowest(){ // Finding gcd of both terms int common_factor = gcd(num3, den3); // Converting both terms into simpler // terms by dividing them by common factor den3 = den3 / common_factor; num3 = num3 / common_factor;} // Function to add two fractionsstatic void addFraction(int num1, int den1, int num2, int den2){ // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final fraction obtained // finding LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to have // same denominator. // Numerator of the final fraction obtained num3 = (num1) * (den3 / den1) + (num2) * (den3 / den2); // Calling function to convert final fraction // into it's simplest form lowest();} // Driver Codepublic static void main(String[] args){ int num1 = 1, den1 = 500, num2 = 2, den2 = 1500; addFraction(num1, den1, num2, den2); System.out.printf(\"%d/%d + %d/%d is equal to %d/%d\\n\", num1, den1, num2, den2, num3, den3);}} // This code is contributed by Rajput-Ji",
"e": 30356,
"s": 28923,
"text": null
},
{
"code": "# Python3 program to add 2 fractions # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Function to convert the obtained# fraction into it's simplest formdef lowest(den3, num3): # Finding gcd of both terms common_factor = gcd(num3, den3) # Converting both terms # into simpler terms by # dividing them by common factor den3 = int(den3 / common_factor) num3 = int(num3 / common_factor) print(num3, \"/\", den3) # Function to add two fractionsdef addFraction(num1, den1, num2, den2): # Finding gcd of den1 and den2 den3 = gcd(den1, den2) # Denominator of final # fraction obtained finding # LCM of den1 and den2 # LCM * GCD = a * b den3 = (den1 * den2) / den3 # Changing the fractions to # have same denominator Numerator # of the final fraction obtained num3 = ((num1) * (den3 / den1) + (num2) * (den3 / den2)) # Calling function to convert # final fraction into it's # simplest form lowest(den3, num3) # Driver Codenum1 = 1; den1 = 500num2 = 2; den2 = 1500 print(num1, \"/\", den1, \" + \", num2, \"/\", den2, \" is equal to \", end = \"\") addFraction(num1, den1, num2, den2)",
"e": 31571,
"s": 30356,
"text": null
},
{
"code": "// C# program to add 2 fractionsusing System; class GFG{static int den3, num3; // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to convert the obtained fraction// into it's simplest formstatic void lowest(){ // Finding gcd of both terms int common_factor = gcd(num3, den3); // Converting both terms into simpler // terms by dividing them by common factor den3 = den3 / common_factor; num3 = num3 / common_factor;} // Function to add two fractionsstatic void addFraction(int num1, int den1, int num2, int den2){ // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final fraction obtained // finding LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to have // same denominator. // Numerator of the final fraction obtained num3 = (num1) * (den3 / den1) + (num2) * (den3 / den2); // Calling function to convert final fraction // into it's simplest form lowest();} // Driver Codepublic static void Main(String[] args){ int num1 = 1, den1 = 500, num2 = 2, den2 = 1500; addFraction(num1, den1, num2, den2); Console.Write(\"{0}/{1} + {2}/{3} is equal to {4}/{5}\\n\", num1, den1, num2, den2, num3, den3);}} // This code is contributed by PrinciRaj1992",
"e": 33008,
"s": 31571,
"text": null
},
{
"code": "<?php// PHP program to add// 2 fractions // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to convert the// obtained fraction into// it's simplest formfunction lowest(&$den3, &$num3){ // Finding gcd of both terms $common_factor = gcd($num3, $den3); // Converting both terms // into simpler terms by // dividing them by common factor $den3 = (int)$den3 / $common_factor; $num3 = (int) $num3 / $common_factor;} // Function to add// two fractionsfunction addFraction($num1, $den1, $num2, $den2, &$num3, &$den3){ // Finding gcd of den1 and den2 $den3 = gcd($den1, $den2); // Denominator of final // fraction obtained finding // LCM of den1 and den2 // LCM * GCD = a * b $den3 = ($den1 * $den2) / $den3; // Changing the fractions to // have same denominator Numerator // of the final fraction obtained $num3 = ($num1) * ($den3 / $den1) + ($num2) * ($den3 / $den2); // Calling function to convert // final fraction into it's // simplest form lowest($den3, $num3);} // Driver Code$num1 = 1; $den1 = 500;$num2 = 2; $den2 = 1500;$den3; $num3;addFraction($num1, $den1, $num2, $den2, $num3, $den3);echo $num1, \"/\", $den1, \" + \", $num2, \"/\", $den2, \" is equal to \", $num3, \"/\", $den3, \"\\n\"; ?>",
"e": 34424,
"s": 33008,
"text": null
},
{
"code": "<script> // JavaScript program to add // 2 fractions // Function to return // gcd of a and b function gcd(a, b) { if (a === 0) return b; return gcd(b % a, a); } // Function to convert the // obtained fraction into // it's simplest form function lowest(den3, num3) { // Finding gcd of both terms var common_factor = gcd(num3, den3); // Converting both terms // into simpler terms by // dividing them by common factor den3 = parseInt(den3 / common_factor); num3 = parseInt(num3 / common_factor); return [den3, num3]; } // Function to add // two fractions function addFraction(num1, den1, num2, den2, num3, den3) { // Finding gcd of den1 and den2 den3 = gcd(den1, den2); // Denominator of final // fraction obtained finding // LCM of den1 and den2 // LCM * GCD = a * b den3 = (den1 * den2) / den3; // Changing the fractions to // have same denominator Numerator // of the final fraction obtained num3 = num1 * (den3 / den1) + num2 * (den3 / den2); // Calling function to convert // final fraction into it's // simplest form return lowest(den3, num3); } // Driver Code var num1 = 1, den1 = 500, num2 = 2, den2 = 1500, den3, num3; var [den3, num3] = addFraction(num1, den1, num2, den2, num3, den3); document.write( num1 + \"/\" + den1 + \" + \" + num2 + \"/\" + den2 + \" is equal to \" + num3 + \"/\" + den3 + \"<br>\" ); </script>",
"e": 36166,
"s": 34424,
"text": null
},
{
"code": null,
"e": 36176,
"s": 36166,
"text": "Output : "
},
{
"code": null,
"e": 36209,
"s": 36176,
"text": "1/500 + 2/1500 is equal to 1/300"
},
{
"code": null,
"e": 36248,
"s": 36209,
"text": " More problems related to Fraction: "
},
{
"code": null,
"e": 36273,
"s": 36248,
"text": "LCM and HCF of fractions"
},
{
"code": null,
"e": 36332,
"s": 36273,
"text": "Represent the fraction of two numbers in the string format"
},
{
"code": null,
"e": 36365,
"s": 36332,
"text": "Program to compare two fractions"
},
{
"code": null,
"e": 36400,
"s": 36365,
"text": "Convert Binary fraction to Decimal"
},
{
"code": null,
"e": 36442,
"s": 36400,
"text": "Convert decimal fraction to binary number"
},
{
"code": null,
"e": 36470,
"s": 36442,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 36508,
"s": 36470,
"text": "Find Recurring Sequence in a Fraction"
},
{
"code": null,
"e": 36538,
"s": 36508,
"text": "Recent Articles on Fraction! "
},
{
"code": null,
"e": 36548,
"s": 36538,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36562,
"s": 36548,
"text": "princiraj1992"
},
{
"code": null,
"e": 36569,
"s": 36562,
"text": "rdtank"
},
{
"code": null,
"e": 36578,
"s": 36569,
"text": "Fraction"
},
{
"code": null,
"e": 36591,
"s": 36578,
"text": "Mathematical"
},
{
"code": null,
"e": 36610,
"s": 36591,
"text": "School Programming"
},
{
"code": null,
"e": 36623,
"s": 36610,
"text": "Mathematical"
},
{
"code": null,
"e": 36721,
"s": 36623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36730,
"s": 36721,
"text": "Comments"
},
{
"code": null,
"e": 36743,
"s": 36730,
"text": "Old Comments"
},
{
"code": null,
"e": 36767,
"s": 36743,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 36810,
"s": 36767,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36824,
"s": 36810,
"text": "Prime Numbers"
},
{
"code": null,
"e": 36865,
"s": 36824,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 36892,
"s": 36865,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 36910,
"s": 36892,
"text": "Python Dictionary"
},
{
"code": null,
"e": 36926,
"s": 36910,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 36951,
"s": 36926,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 36970,
"s": 36951,
"text": "Inheritance in C++"
}
] |
Change SQLite Connection Timeout using Python - GeeksforGeeks | 12 Jan, 2022
In this article, we will discuss how to change the SQLite connection timeout when connecting from Python.
A connection timeout is an error that occurs when it takes too long for a server to respond to a user’s request.
Connection timeouts usually occur when there are multiple active connections to a database and one of them is performing an operation that involves modification of the data stored. In that case, the other connections have to wait until that operation is done before they can perform their own operations. When that waiting time crosses the time limit, it causes a connection timeout.
This is a sample python code snippet that uses the sqlite3 package to create and connect to a database and then output its version.
Approach
First, the inbuilt sqlite3 package is imported.
Next, we use the connect method of the connector class to connect to the database, passing its name as a parameter.
After that, using the cursor object of the connector class, we have to create a cursor instance that can execute our queries.
The execute method then executes the query and returns the result.
The results are then extracted from the cursor by using the fetchall method.
And finally, irrespective of whether the query was executed successfully or not, both the database cursor and connection has to be closed.
Python3
# import moduleimport sqlite3 try: # establish connection sqliteConnection = sqlite3.connect('sqlite.db') # create cursor object cursor = sqliteConnection.cursor() print('Database Initialization and Connection successful') # display version query = 'select sqlite_version();' cursor.execute(query) # get data record = cursor.fetchall() print(f'SQLite Version - {record}') cursor.close() except sqlite3.Error as error: print('Error occured - ', error) finally: # If the connection was established then close it if sqliteConnection: sqliteConnection.close() print('SQLite Connection closed')
Output:
Normally, the above code snippet would work perfectly fine. But when the database is already being used by another process, it’d have to wait until that process’s query is resolved before executing its own query. If that waiting time crosses the connection timeout value, then that results in a Connection Timeout.
The default value for connection timeout is 5 seconds. But it can be changed in the connect() method itself. It accepts an optional parameter timeout which accepts the value for connection timeout in seconds. The code snippet has now been modified to have a connection timeout of 20 seconds.
Python3
# import moduleimport sqlite3 try: # establish connection sqliteConnection = sqlite3.connect('sqlite.db', timeout=20) # create cursor object cursor = sqliteConnection.cursor() print('Database Initialization and Connection successful') # display version query = 'select sqlite_version();' cursor.execute(query) # get data record = cursor.fetchall() print(f'SQLite Version - {record}') cursor.close() except sqlite3.Error as error: print('Error occured - ', error) finally: # If the connection was established then # close it if sqliteConnection: sqliteConnection.close() print('SQLite Connection closed')
Output:
In the above example, the python program will be connected to the SQLite database for 20 seconds as the timeout parameter in connect() method is assigned to 20. In this way, one can change SQLite connection timeout when connecting from python.
kashishsoda
simmytarika5
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 24398,
"s": 24292,
"text": "In this article, we will discuss how to change the SQLite connection timeout when connecting from Python."
},
{
"code": null,
"e": 24511,
"s": 24398,
"text": "A connection timeout is an error that occurs when it takes too long for a server to respond to a user’s request."
},
{
"code": null,
"e": 24895,
"s": 24511,
"text": "Connection timeouts usually occur when there are multiple active connections to a database and one of them is performing an operation that involves modification of the data stored. In that case, the other connections have to wait until that operation is done before they can perform their own operations. When that waiting time crosses the time limit, it causes a connection timeout."
},
{
"code": null,
"e": 25028,
"s": 24895,
"text": "This is a sample python code snippet that uses the sqlite3 package to create and connect to a database and then output its version. "
},
{
"code": null,
"e": 25037,
"s": 25028,
"text": "Approach"
},
{
"code": null,
"e": 25085,
"s": 25037,
"text": "First, the inbuilt sqlite3 package is imported."
},
{
"code": null,
"e": 25201,
"s": 25085,
"text": "Next, we use the connect method of the connector class to connect to the database, passing its name as a parameter."
},
{
"code": null,
"e": 25327,
"s": 25201,
"text": "After that, using the cursor object of the connector class, we have to create a cursor instance that can execute our queries."
},
{
"code": null,
"e": 25394,
"s": 25327,
"text": "The execute method then executes the query and returns the result."
},
{
"code": null,
"e": 25471,
"s": 25394,
"text": "The results are then extracted from the cursor by using the fetchall method."
},
{
"code": null,
"e": 25610,
"s": 25471,
"text": "And finally, irrespective of whether the query was executed successfully or not, both the database cursor and connection has to be closed."
},
{
"code": null,
"e": 25618,
"s": 25610,
"text": "Python3"
},
{
"code": "# import moduleimport sqlite3 try: # establish connection sqliteConnection = sqlite3.connect('sqlite.db') # create cursor object cursor = sqliteConnection.cursor() print('Database Initialization and Connection successful') # display version query = 'select sqlite_version();' cursor.execute(query) # get data record = cursor.fetchall() print(f'SQLite Version - {record}') cursor.close() except sqlite3.Error as error: print('Error occured - ', error) finally: # If the connection was established then close it if sqliteConnection: sqliteConnection.close() print('SQLite Connection closed')",
"e": 26286,
"s": 25618,
"text": null
},
{
"code": null,
"e": 26294,
"s": 26286,
"text": "Output:"
},
{
"code": null,
"e": 26609,
"s": 26294,
"text": "Normally, the above code snippet would work perfectly fine. But when the database is already being used by another process, it’d have to wait until that process’s query is resolved before executing its own query. If that waiting time crosses the connection timeout value, then that results in a Connection Timeout."
},
{
"code": null,
"e": 26901,
"s": 26609,
"text": "The default value for connection timeout is 5 seconds. But it can be changed in the connect() method itself. It accepts an optional parameter timeout which accepts the value for connection timeout in seconds. The code snippet has now been modified to have a connection timeout of 20 seconds."
},
{
"code": null,
"e": 26909,
"s": 26901,
"text": "Python3"
},
{
"code": "# import moduleimport sqlite3 try: # establish connection sqliteConnection = sqlite3.connect('sqlite.db', timeout=20) # create cursor object cursor = sqliteConnection.cursor() print('Database Initialization and Connection successful') # display version query = 'select sqlite_version();' cursor.execute(query) # get data record = cursor.fetchall() print(f'SQLite Version - {record}') cursor.close() except sqlite3.Error as error: print('Error occured - ', error) finally: # If the connection was established then # close it if sqliteConnection: sqliteConnection.close() print('SQLite Connection closed')",
"e": 27583,
"s": 26909,
"text": null
},
{
"code": null,
"e": 27591,
"s": 27583,
"text": "Output:"
},
{
"code": null,
"e": 27835,
"s": 27591,
"text": "In the above example, the python program will be connected to the SQLite database for 20 seconds as the timeout parameter in connect() method is assigned to 20. In this way, one can change SQLite connection timeout when connecting from python."
},
{
"code": null,
"e": 27847,
"s": 27835,
"text": "kashishsoda"
},
{
"code": null,
"e": 27860,
"s": 27847,
"text": "simmytarika5"
},
{
"code": null,
"e": 27867,
"s": 27860,
"text": "Picked"
},
{
"code": null,
"e": 27881,
"s": 27867,
"text": "Python-SQLite"
},
{
"code": null,
"e": 27888,
"s": 27881,
"text": "Python"
},
{
"code": null,
"e": 27986,
"s": 27888,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28018,
"s": 27986,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28060,
"s": 28018,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28116,
"s": 28060,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28158,
"s": 28116,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28213,
"s": 28158,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28244,
"s": 28213,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28266,
"s": 28244,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28295,
"s": 28266,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28334,
"s": 28295,
"text": "Python | Get unique values from a list"
}
] |
F# - Sequences | Sequences, like lists also represent an ordered collection of values. However, the elements in a sequence or sequence expression are computed when required. They are not computed at once, and for this reason they are used to represent infinite data structures.
Sequences are defined using the following syntax −
seq { expr }
For example,
let seq1 = seq { 1 .. 10 }
Similar to lists, you can create sequences using ranges and comprehensions.
Sequence expressions are the expressions you can write for creating sequences. These can be done −
By specifying the range.
By specifying the range with increment or decrement.
By using the yield keyword to produce values that become part of the sequence.
By using the → operator.
The following examples demonstrate the concept −
(* Sequences *)
let seq1 = seq { 1 .. 10 }
(* ascending order and increment*)
printfn "The Sequence: %A" seq1
let seq2 = seq { 1 .. 5 .. 50 }
(* descending order and decrement*)
printfn "The Sequence: %A" seq2
let seq3 = seq {50 .. -5 .. 0}
printfn "The Sequence: %A" seq3
(* using yield *)
let seq4 = seq { for a in 1 .. 10 do yield a, a*a, a*a*a }
printfn "The Sequence: %A" seq4
When you compile and execute the program, it yields the following output −
The Sequence: seq [1; 2; 3; 4; ...]
The Sequence: seq [1; 6; 11; 16; ...]
The Sequence: seq [50; 45; 40; 35; ...]
The Sequence: seq [(1, 1, 1); (2, 4, 8); (3, 9, 27); (4, 16, 64); ...]
The following program prints the prime numbers from 1 to 50 −
(* Recursive isprime function. *)
let isprime n =
let rec check i =
i > n/2 || (n % i <> 0 && check (i + 1))
check 2
let primeIn50 = seq { for n in 1..50 do if isprime n then yield n }
for x in primeIn50 do
printfn "%d" x
When you compile and execute the program, it yields the following output −
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
The following table shows the basic operations on sequence data type −
The following examples demonstrate the uses of some of the above functionalities −
This program creates an empty sequence and fills it up later −
(* Creating sequences *)
let emptySeq = Seq.empty
let seq1 = Seq.singleton 20
printfn"The singleton sequence:"
printfn "%A " seq1
printfn"The init sequence:"
let seq2 = Seq.init 5 (fun n -> n * 3)
Seq.iter (fun i -> printf "%d " i) seq2
printfn""
(* converting an array to sequence by using cast *)
printfn"The array sequence 1:"
let seq3 = [| 1 .. 10 |] :> seq<int>
Seq.iter (fun i -> printf "%d " i) seq3
printfn""
(* converting an array to sequence by using Seq.ofArray *)
printfn"The array sequence 2:"
let seq4 = [| 2..2.. 20 |] |> Seq.ofArray
Seq.iter (fun i -> printf "%d " i) seq4
printfn""
When you compile and execute the program, it yields the following output −
The singleton sequence:
seq [20]
The init sequence:
0 3 6 9 12
The array sequence 1:
1 2 3 4 5 6 7 8 9 10
The array sequence 2:
2 4 6 8 10 12 14 16 18 20
Please note that −
The Seq.empty method creates an empty sequence.
The Seq.empty method creates an empty sequence.
The Seq.singleton method creates a sequence of just one specified element.
The Seq.singleton method creates a sequence of just one specified element.
The Seq.init method creates a sequence for which the elements are created by using a given function.
The Seq.init method creates a sequence for which the elements are created by using a given function.
The Seq.ofArray and Seq.ofList<'T> methods create sequences from arrays and lists.
The Seq.ofArray and Seq.ofList<'T> methods create sequences from arrays and lists.
The Seq.iter method allows iterating through a sequence.
The Seq.iter method allows iterating through a sequence.
The Seq.unfold method generates a sequence from a computation function that takes a state and transforms it to produce each subsequent element in the sequence.
The following function produces the first 20 natural numbers −
let seq1 = Seq.unfold (fun state -> if (state > 20) then None else Some(state, state + 1)) 0
printfn "The sequence seq1 contains numbers from 0 to 20."
for x in seq1 do printf "%d " x
printfn" "
When you compile and execute the program, it yields the following output −
The sequence seq1 contains numbers from 0 to 20.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The Seq.truncate method creates a sequence from another sequence, but limits the sequence to a specified number of elements.
The Seq.take method creates a new sequence that contains a specified number of elements from the start of a sequence.
let mySeq = seq { for i in 1 .. 10 -> 3*i }
let truncatedSeq = Seq.truncate 5 mySeq
let takeSeq = Seq.take 5 mySeq
printfn"The original sequence"
Seq.iter (fun i -> printf "%d " i) mySeq
printfn""
printfn"The truncated sequence"
Seq.iter (fun i -> printf "%d " i) truncatedSeq
printfn""
printfn"The take sequence"
Seq.iter (fun i -> printf "%d " i) takeSeq
printfn""
When you compile and execute the program, it yields the following output −
The original sequence
3 6 9 12 15 18 21 24 27 30
The truncated sequence
3 6 9 12 15
The take sequence
3 6 9 12 15
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2422,
"s": 2161,
"text": "Sequences, like lists also represent an ordered collection of values. However, the elements in a sequence or sequence expression are computed when required. They are not computed at once, and for this reason they are used to represent infinite data structures."
},
{
"code": null,
"e": 2473,
"s": 2422,
"text": "Sequences are defined using the following syntax −"
},
{
"code": null,
"e": 2487,
"s": 2473,
"text": "seq { expr }\n"
},
{
"code": null,
"e": 2500,
"s": 2487,
"text": "For example,"
},
{
"code": null,
"e": 2528,
"s": 2500,
"text": "let seq1 = seq { 1 .. 10 }\n"
},
{
"code": null,
"e": 2604,
"s": 2528,
"text": "Similar to lists, you can create sequences using ranges and comprehensions."
},
{
"code": null,
"e": 2703,
"s": 2604,
"text": "Sequence expressions are the expressions you can write for creating sequences. These can be done −"
},
{
"code": null,
"e": 2728,
"s": 2703,
"text": "By specifying the range."
},
{
"code": null,
"e": 2781,
"s": 2728,
"text": "By specifying the range with increment or decrement."
},
{
"code": null,
"e": 2860,
"s": 2781,
"text": "By using the yield keyword to produce values that become part of the sequence."
},
{
"code": null,
"e": 2885,
"s": 2860,
"text": "By using the → operator."
},
{
"code": null,
"e": 2934,
"s": 2885,
"text": "The following examples demonstrate the concept −"
},
{
"code": null,
"e": 3320,
"s": 2934,
"text": "(* Sequences *)\nlet seq1 = seq { 1 .. 10 }\n\n(* ascending order and increment*)\nprintfn \"The Sequence: %A\" seq1\nlet seq2 = seq { 1 .. 5 .. 50 }\n\n(* descending order and decrement*)\nprintfn \"The Sequence: %A\" seq2\n\nlet seq3 = seq {50 .. -5 .. 0}\nprintfn \"The Sequence: %A\" seq3\n\n(* using yield *)\nlet seq4 = seq { for a in 1 .. 10 do yield a, a*a, a*a*a }\nprintfn \"The Sequence: %A\" seq4"
},
{
"code": null,
"e": 3395,
"s": 3320,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 3581,
"s": 3395,
"text": "The Sequence: seq [1; 2; 3; 4; ...]\nThe Sequence: seq [1; 6; 11; 16; ...]\nThe Sequence: seq [50; 45; 40; 35; ...]\nThe Sequence: seq [(1, 1, 1); (2, 4, 8); (3, 9, 27); (4, 16, 64); ...]\n"
},
{
"code": null,
"e": 3643,
"s": 3581,
"text": "The following program prints the prime numbers from 1 to 50 −"
},
{
"code": null,
"e": 3881,
"s": 3643,
"text": "(* Recursive isprime function. *)\nlet isprime n =\n let rec check i =\n i > n/2 || (n % i <> 0 && check (i + 1))\n check 2\n\nlet primeIn50 = seq { for n in 1..50 do if isprime n then yield n }\nfor x in primeIn50 do\n printfn \"%d\" x"
},
{
"code": null,
"e": 3956,
"s": 3881,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 4000,
"s": 3956,
"text": "1\n2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n"
},
{
"code": null,
"e": 4071,
"s": 4000,
"text": "The following table shows the basic operations on sequence data type −"
},
{
"code": null,
"e": 4154,
"s": 4071,
"text": "The following examples demonstrate the uses of some of the above functionalities −"
},
{
"code": null,
"e": 4217,
"s": 4154,
"text": "This program creates an empty sequence and fills it up later −"
},
{
"code": null,
"e": 4820,
"s": 4217,
"text": "(* Creating sequences *)\nlet emptySeq = Seq.empty\nlet seq1 = Seq.singleton 20\n\nprintfn\"The singleton sequence:\"\nprintfn \"%A \" seq1\nprintfn\"The init sequence:\"\n\nlet seq2 = Seq.init 5 (fun n -> n * 3)\nSeq.iter (fun i -> printf \"%d \" i) seq2\nprintfn\"\"\n\n(* converting an array to sequence by using cast *)\nprintfn\"The array sequence 1:\"\nlet seq3 = [| 1 .. 10 |] :> seq<int>\nSeq.iter (fun i -> printf \"%d \" i) seq3\nprintfn\"\"\n\n(* converting an array to sequence by using Seq.ofArray *)\nprintfn\"The array sequence 2:\"\nlet seq4 = [| 2..2.. 20 |] |> Seq.ofArray\nSeq.iter (fun i -> printf \"%d \" i) seq4\nprintfn\"\""
},
{
"code": null,
"e": 4895,
"s": 4820,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 5050,
"s": 4895,
"text": "The singleton sequence:\nseq [20]\nThe init sequence:\n0 3 6 9 12\nThe array sequence 1:\n1 2 3 4 5 6 7 8 9 10\nThe array sequence 2:\n2 4 6 8 10 12 14 16 18 20\n"
},
{
"code": null,
"e": 5069,
"s": 5050,
"text": "Please note that −"
},
{
"code": null,
"e": 5117,
"s": 5069,
"text": "The Seq.empty method creates an empty sequence."
},
{
"code": null,
"e": 5165,
"s": 5117,
"text": "The Seq.empty method creates an empty sequence."
},
{
"code": null,
"e": 5240,
"s": 5165,
"text": "The Seq.singleton method creates a sequence of just one specified element."
},
{
"code": null,
"e": 5315,
"s": 5240,
"text": "The Seq.singleton method creates a sequence of just one specified element."
},
{
"code": null,
"e": 5416,
"s": 5315,
"text": "The Seq.init method creates a sequence for which the elements are created by using a given function."
},
{
"code": null,
"e": 5517,
"s": 5416,
"text": "The Seq.init method creates a sequence for which the elements are created by using a given function."
},
{
"code": null,
"e": 5600,
"s": 5517,
"text": "The Seq.ofArray and Seq.ofList<'T> methods create sequences from arrays and lists."
},
{
"code": null,
"e": 5683,
"s": 5600,
"text": "The Seq.ofArray and Seq.ofList<'T> methods create sequences from arrays and lists."
},
{
"code": null,
"e": 5740,
"s": 5683,
"text": "The Seq.iter method allows iterating through a sequence."
},
{
"code": null,
"e": 5797,
"s": 5740,
"text": "The Seq.iter method allows iterating through a sequence."
},
{
"code": null,
"e": 5957,
"s": 5797,
"text": "The Seq.unfold method generates a sequence from a computation function that takes a state and transforms it to produce each subsequent element in the sequence."
},
{
"code": null,
"e": 6020,
"s": 5957,
"text": "The following function produces the first 20 natural numbers −"
},
{
"code": null,
"e": 6215,
"s": 6020,
"text": "let seq1 = Seq.unfold (fun state -> if (state > 20) then None else Some(state, state + 1)) 0\nprintfn \"The sequence seq1 contains numbers from 0 to 20.\"\nfor x in seq1 do printf \"%d \" x\nprintfn\" \""
},
{
"code": null,
"e": 6290,
"s": 6215,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 6393,
"s": 6290,
"text": "The sequence seq1 contains numbers from 0 to 20.\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n"
},
{
"code": null,
"e": 6518,
"s": 6393,
"text": "The Seq.truncate method creates a sequence from another sequence, but limits the sequence to a specified number of elements."
},
{
"code": null,
"e": 6636,
"s": 6518,
"text": "The Seq.take method creates a new sequence that contains a specified number of elements from the start of a sequence."
},
{
"code": null,
"e": 7006,
"s": 6636,
"text": "let mySeq = seq { for i in 1 .. 10 -> 3*i }\nlet truncatedSeq = Seq.truncate 5 mySeq\nlet takeSeq = Seq.take 5 mySeq\n\nprintfn\"The original sequence\"\nSeq.iter (fun i -> printf \"%d \" i) mySeq\nprintfn\"\"\n\nprintfn\"The truncated sequence\"\nSeq.iter (fun i -> printf \"%d \" i) truncatedSeq\nprintfn\"\"\n\nprintfn\"The take sequence\"\nSeq.iter (fun i -> printf \"%d \" i) takeSeq\nprintfn\"\""
},
{
"code": null,
"e": 7081,
"s": 7006,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 7196,
"s": 7081,
"text": "The original sequence\n3 6 9 12 15 18 21 24 27 30\nThe truncated sequence\n3 6 9 12 15\nThe take sequence\n3 6 9 12 15\n"
},
{
"code": null,
"e": 7203,
"s": 7196,
"text": " Print"
},
{
"code": null,
"e": 7214,
"s": 7203,
"text": " Add Notes"
}
] |
How to add HTML elements dynamically using JavaScript ? | 22 Nov, 2021
In this article, we learn how to add HTML elements dynamically using JavaScript. A basic understanding of HTML, CSS, and javascript is required. Here we are going to use a button and by clicking this button, we can add an HTML element dynamically in this example.
Approach: Create an HTML file with any name (Ex- index.html) then write the outer HTML template and take one button so that when someone clicks on the button, an HTML is dynamically added one by one in a list format. We have attached an onclick event listener to the button, when someone clicks that button immediately the event will fire and execute the callback function attached to that event listener inside the callback function we need to mention a certain task that we want to happen after an onclick event is a fire.
Below is the implementation of the above approach:
index.html
<!DOCTYPE html><html> <head> <style> h1 { color: green; display: flex; justify-content: center; } #mybutton { display: block; margin: 0 auto; } #innerdiv { display: flex; flex-direction: column; justify-content: center; align-items: center; } </style></head> <body> <h1> GeeksforGeeks </h1> <div id="innerdiv"></div> <button id="mybutton"> click me </button> <script> document.getElementById("mybutton"). addEventListener("click", function () { document.getElementById("innerdiv"). innerHTML += "<h3>Hello geeks</h3>"; }); </script></body> </html>
Output:
HTML-Questions
JavaScript-Questions
Picked
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "In this article, we learn how to add HTML elements dynamically using JavaScript. A basic understanding of HTML, CSS, and javascript is required. Here we are going to use a button and by clicking this button, we can add an HTML element dynamically in this example."
},
{
"code": null,
"e": 818,
"s": 292,
"text": "Approach: Create an HTML file with any name (Ex- index.html) then write the outer HTML template and take one button so that when someone clicks on the button, an HTML is dynamically added one by one in a list format. We have attached an onclick event listener to the button, when someone clicks that button immediately the event will fire and execute the callback function attached to that event listener inside the callback function we need to mention a certain task that we want to happen after an onclick event is a fire. "
},
{
"code": null,
"e": 869,
"s": 818,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 880,
"s": 869,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; display: flex; justify-content: center; } #mybutton { display: block; margin: 0 auto; } #innerdiv { display: flex; flex-direction: column; justify-content: center; align-items: center; } </style></head> <body> <h1> GeeksforGeeks </h1> <div id=\"innerdiv\"></div> <button id=\"mybutton\"> click me </button> <script> document.getElementById(\"mybutton\"). addEventListener(\"click\", function () { document.getElementById(\"innerdiv\"). innerHTML += \"<h3>Hello geeks</h3>\"; }); </script></body> </html>",
"e": 1661,
"s": 880,
"text": null
},
{
"code": null,
"e": 1669,
"s": 1661,
"text": "Output:"
},
{
"code": null,
"e": 1684,
"s": 1669,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1705,
"s": 1684,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1712,
"s": 1705,
"text": "Picked"
},
{
"code": null,
"e": 1717,
"s": 1712,
"text": "HTML"
},
{
"code": null,
"e": 1728,
"s": 1717,
"text": "JavaScript"
},
{
"code": null,
"e": 1745,
"s": 1728,
"text": "Web Technologies"
},
{
"code": null,
"e": 1750,
"s": 1745,
"text": "HTML"
}
] |
Decision Tree Classifiers in R Programming | 23 Dec, 2021
Classification is the task in which objects of several categories are categorized into their respective classes using the properties of classes. A classification model is typically used to,
Predict the class label for a new unlabeled data object
Provide a descriptive model explaining what features characterize objects in each class
There are various types of classification techniques such as,
Logistic Regression
Decision Tree
K-Nearest Neighbours
Naive Bayes Classifier
Support Vector Machines (SVM)
Random Forest Classification
A decision tree is a flowchart-like tree structure in which the internal node represents feature(or attribute), the branch represents a decision rule, and each leaf node represents the outcome. A Decision Tree consists of,
Nodes: Test for the value of a certain attribute.
Edges/Branch: Represents a decision rule and connect to the next node.
Leaf nodes: Terminal nodes that represent class labels or class distribution.
And this algorithm can easily be implemented in the R language. Some important points about decision tree classifiers are,
It is more interpretable
Automatically handles decision-making
Bisects the space into smaller spaces
Prone to overfitting
Can be trained on a small training set
Majorly affected by noise
A sample population of 400 people shared their age, gender, and salary with a product company, and if they bought the product or not(0 means no, 1 means yes). Download the dataset Advertisement.csv.
R
# Importing the datasetdataset = read.csv('Advertisement.csv')head(dataset, 10)
Output:
To train the data we will split the dataset into a test set and then make Decision Tree Classifiers with rpart package.
R
# Encoding the target feature as factordataset$Purchased = factor(dataset$Purchased, levels = c(0, 1)) # Splitting the dataset into# the Training set and Test set# install.packages('caTools')library(caTools)set.seed(123)split = sample.split(dataset$Purchased, SplitRatio = 0.75)training_set = subset(dataset, split == TRUE)test_set = subset(dataset, split == FALSE) # Feature Scalingtraining_set[-3] = scale(training_set[-3])test_set[-3] = scale(test_set[-3]) # Fitting Decision Tree Classification# to the Training set# install.packages('rpart')library(rpart)classifier = rpart(formula = Purchased ~ ., data = training_set) # Predicting the Test set resultsy_pred = predict(classifier, newdata = test_set[-3], type = 'class') # Making the Confusion Matrixcm = table(test_set[, 3], y_pred)
The training set contains 300 entries.
The test set contains 100 entries.
Confusion Matrix:
[[62, 6],
[ 3, 29]]
R
# Visualising the Training set results# Install ElemStatLearn if not present# in the packages using(without hashtag)# install.packages('ElemStatLearn')library(ElemStatLearn)set = training_set # Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting them# to grid and labelling the axesy_grid = predict(classifier, newdata = grid_set, type = 'class')plot(set[, -3], main = 'Decision Tree Classification (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
Output:
R
# Visualising the Test set resultslibrary(ElemStatLearn)set = test_set # Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting them# to grid and labelling the axesy_grid = predict(classifier, newdata = grid_set, type = 'class')plot(set[, -3], main = 'Decision Tree Classification (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
Output:
R
# Plotting the treeplot(classifier)text(classifier)
Output:
kumar_satyam
data-science
Picked
R Machine-Learning
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 244,
"s": 54,
"text": "Classification is the task in which objects of several categories are categorized into their respective classes using the properties of classes. A classification model is typically used to,"
},
{
"code": null,
"e": 300,
"s": 244,
"text": "Predict the class label for a new unlabeled data object"
},
{
"code": null,
"e": 388,
"s": 300,
"text": "Provide a descriptive model explaining what features characterize objects in each class"
},
{
"code": null,
"e": 450,
"s": 388,
"text": "There are various types of classification techniques such as,"
},
{
"code": null,
"e": 470,
"s": 450,
"text": "Logistic Regression"
},
{
"code": null,
"e": 484,
"s": 470,
"text": "Decision Tree"
},
{
"code": null,
"e": 505,
"s": 484,
"text": "K-Nearest Neighbours"
},
{
"code": null,
"e": 528,
"s": 505,
"text": "Naive Bayes Classifier"
},
{
"code": null,
"e": 558,
"s": 528,
"text": "Support Vector Machines (SVM)"
},
{
"code": null,
"e": 587,
"s": 558,
"text": "Random Forest Classification"
},
{
"code": null,
"e": 810,
"s": 587,
"text": "A decision tree is a flowchart-like tree structure in which the internal node represents feature(or attribute), the branch represents a decision rule, and each leaf node represents the outcome. A Decision Tree consists of,"
},
{
"code": null,
"e": 860,
"s": 810,
"text": "Nodes: Test for the value of a certain attribute."
},
{
"code": null,
"e": 931,
"s": 860,
"text": "Edges/Branch: Represents a decision rule and connect to the next node."
},
{
"code": null,
"e": 1009,
"s": 931,
"text": "Leaf nodes: Terminal nodes that represent class labels or class distribution."
},
{
"code": null,
"e": 1132,
"s": 1009,
"text": "And this algorithm can easily be implemented in the R language. Some important points about decision tree classifiers are,"
},
{
"code": null,
"e": 1157,
"s": 1132,
"text": "It is more interpretable"
},
{
"code": null,
"e": 1195,
"s": 1157,
"text": "Automatically handles decision-making"
},
{
"code": null,
"e": 1233,
"s": 1195,
"text": "Bisects the space into smaller spaces"
},
{
"code": null,
"e": 1254,
"s": 1233,
"text": "Prone to overfitting"
},
{
"code": null,
"e": 1293,
"s": 1254,
"text": "Can be trained on a small training set"
},
{
"code": null,
"e": 1319,
"s": 1293,
"text": "Majorly affected by noise"
},
{
"code": null,
"e": 1518,
"s": 1319,
"text": "A sample population of 400 people shared their age, gender, and salary with a product company, and if they bought the product or not(0 means no, 1 means yes). Download the dataset Advertisement.csv."
},
{
"code": null,
"e": 1520,
"s": 1518,
"text": "R"
},
{
"code": "# Importing the datasetdataset = read.csv('Advertisement.csv')head(dataset, 10)",
"e": 1600,
"s": 1520,
"text": null
},
{
"code": null,
"e": 1609,
"s": 1600,
"text": " Output:"
},
{
"code": null,
"e": 1729,
"s": 1609,
"text": "To train the data we will split the dataset into a test set and then make Decision Tree Classifiers with rpart package."
},
{
"code": null,
"e": 1731,
"s": 1729,
"text": "R"
},
{
"code": "# Encoding the target feature as factordataset$Purchased = factor(dataset$Purchased, levels = c(0, 1)) # Splitting the dataset into# the Training set and Test set# install.packages('caTools')library(caTools)set.seed(123)split = sample.split(dataset$Purchased, SplitRatio = 0.75)training_set = subset(dataset, split == TRUE)test_set = subset(dataset, split == FALSE) # Feature Scalingtraining_set[-3] = scale(training_set[-3])test_set[-3] = scale(test_set[-3]) # Fitting Decision Tree Classification# to the Training set# install.packages('rpart')library(rpart)classifier = rpart(formula = Purchased ~ ., data = training_set) # Predicting the Test set resultsy_pred = predict(classifier, newdata = test_set[-3], type = 'class') # Making the Confusion Matrixcm = table(test_set[, 3], y_pred)",
"e": 2617,
"s": 1731,
"text": null
},
{
"code": null,
"e": 2656,
"s": 2617,
"text": "The training set contains 300 entries."
},
{
"code": null,
"e": 2691,
"s": 2656,
"text": "The test set contains 100 entries."
},
{
"code": null,
"e": 2731,
"s": 2691,
"text": "Confusion Matrix:\n[[62, 6],\n [ 3, 29]]"
},
{
"code": null,
"e": 2733,
"s": 2731,
"text": "R"
},
{
"code": "# Visualising the Training set results# Install ElemStatLearn if not present# in the packages using(without hashtag)# install.packages('ElemStatLearn')library(ElemStatLearn)set = training_set # Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting them# to grid and labelling the axesy_grid = predict(classifier, newdata = grid_set, type = 'class')plot(set[, -3], main = 'Decision Tree Classification (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))",
"e": 4019,
"s": 2733,
"text": null
},
{
"code": null,
"e": 4028,
"s": 4019,
"text": " Output:"
},
{
"code": null,
"e": 4030,
"s": 4028,
"text": "R"
},
{
"code": "# Visualising the Test set resultslibrary(ElemStatLearn)set = test_set # Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting them# to grid and labelling the axesy_grid = predict(classifier, newdata = grid_set, type = 'class')plot(set[, -3], main = 'Decision Tree Classification (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))",
"e": 5198,
"s": 4030,
"text": null
},
{
"code": null,
"e": 5207,
"s": 5198,
"text": " Output:"
},
{
"code": null,
"e": 5209,
"s": 5207,
"text": "R"
},
{
"code": "# Plotting the treeplot(classifier)text(classifier)",
"e": 5261,
"s": 5209,
"text": null
},
{
"code": null,
"e": 5270,
"s": 5261,
"text": " Output:"
},
{
"code": null,
"e": 5283,
"s": 5270,
"text": "kumar_satyam"
},
{
"code": null,
"e": 5296,
"s": 5283,
"text": "data-science"
},
{
"code": null,
"e": 5303,
"s": 5296,
"text": "Picked"
},
{
"code": null,
"e": 5322,
"s": 5303,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 5339,
"s": 5322,
"text": "Machine Learning"
},
{
"code": null,
"e": 5350,
"s": 5339,
"text": "R Language"
},
{
"code": null,
"e": 5367,
"s": 5350,
"text": "Machine Learning"
},
{
"code": null,
"e": 5465,
"s": 5367,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5488,
"s": 5465,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 5512,
"s": 5488,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 5548,
"s": 5512,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5589,
"s": 5548,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 5613,
"s": 5589,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5658,
"s": 5613,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 5710,
"s": 5658,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5768,
"s": 5710,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 5820,
"s": 5768,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
}
] |
How to iterate a JSON Array in Android using Kotlin? | This example demonstrates how to iterate a JSON Array in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONObject
@Suppress("NAME_SHADOWING")
class MainActivity : AppCompatActivity() {
private lateinit var textView: TextView
var strJson = ("{ \"Employee\" :[{\"ID\":\"01\",\"Name\":\"Sam\",\"Salary\":\"50000\"},"
+ "{\"ID\":\"02\",\"Name\":\"Shankar\",\"Salary\":\"60000\"}] }")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
val data = StringBuilder()
val jsonObject = JSONObject(strJson)
val jsonArray = jsonObject.optJSONArray("Employee")
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val id = jsonObject.optString("ID").toInt()
val name = jsonObject.optString("Name")
val salary = jsonObject.optString("Salary").toFloat()
data.append("Employee ").append(i).append(" : \n ID= ") .append(id).append(" \n " + "Name= ") .append(name).append(" \n Salary= ") .append(salary).append(" \n\n ")
}
textView.text = data.toString()
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1266,
"s": 1187,
"text": "This example demonstrates how to iterate a JSON Array in Android using Kotlin."
},
{
"code": null,
"e": 1395,
"s": 1266,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1460,
"s": 1395,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2451,
"s": 1460,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2506,
"s": 2451,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3746,
"s": 2506,
"text": "import android.os.Bundle\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport org.json.JSONObject\n@Suppress(\"NAME_SHADOWING\")\nclass MainActivity : AppCompatActivity() {\n private lateinit var textView: TextView\n var strJson = (\"{ \\\"Employee\\\" :[{\\\"ID\\\":\\\"01\\\",\\\"Name\\\":\\\"Sam\\\",\\\"Salary\\\":\\\"50000\\\"},\"\n+ \"{\\\"ID\\\":\\\"02\\\",\\\"Name\\\":\\\"Shankar\\\",\\\"Salary\\\":\\\"60000\\\"}] }\")\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n val data = StringBuilder()\n val jsonObject = JSONObject(strJson)\n val jsonArray = jsonObject.optJSONArray(\"Employee\")\n for (i in 0 until jsonArray.length()) {\n val jsonObject = jsonArray.getJSONObject(i)\n val id = jsonObject.optString(\"ID\").toInt()\n val name = jsonObject.optString(\"Name\")\n val salary = jsonObject.optString(\"Salary\").toFloat()\n data.append(\"Employee \").append(i).append(\" : \\n ID= \") .append(id).append(\" \\n \" + \"Name= \") .append(name).append(\" \\n Salary= \") .append(salary).append(\" \\n\\n \")\n }\n textView.text = data.toString()\n }\n}"
},
{
"code": null,
"e": 3801,
"s": 3746,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4477,
"s": 3801,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4828,
"s": 4477,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4869,
"s": 4828,
"text": "Click here to download the project code."
}
] |
std::cbrt() in C++ | 24 Jan, 2022
The std::cbrt() is an inbuilt function in C++ STL which is used to calculate the cube root of number. It accepts a number as argument and returns the cube root of that number.Syntax:
// Returns cube root num (num can be
// of type int, double, long double or
// long long type.
// The return type is same as parameter
// passed.
cbrt(num)
Parameter: The parameter can be of int, double, long double or long long type.Return Value: It returns the cube root of the number num. The datatype of returned cube root is same as that of the parameter passed except when an integer is passed as parameter. If the parameter passed is integral then the cbrt() function will return a value of type double. Examples:
Input : 8
Output : 2
Input : 9
Output : 2.08008
Below program illustrate the cbrt() function:
CPP
// CPP program to demonstrate the cbrt()// STL function#include <bits/stdc++.h>using namespace std; int main(){ // cbrt() function with integral // argument int num1 = 9; cout << cbrt(num1) << endl; // cbrt() function with floating-point // argument double num2 = 7.11; cout << cbrt(num2) << endl; long long num3 = 7; cout << cbrt(num3); return 0;}
Output:
2.08008
1.9229
1.91293
tranlehuy2k1
sumitgumber28
CPP-Functions
cpp-math
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Object Oriented Programming in C++
The C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 238,
"s": 53,
"text": "The std::cbrt() is an inbuilt function in C++ STL which is used to calculate the cube root of number. It accepts a number as argument and returns the cube root of that number.Syntax: "
},
{
"code": null,
"e": 394,
"s": 238,
"text": "// Returns cube root num (num can be\n// of type int, double, long double or\n// long long type.\n// The return type is same as parameter\n// passed.\ncbrt(num)"
},
{
"code": null,
"e": 761,
"s": 394,
"text": "Parameter: The parameter can be of int, double, long double or long long type.Return Value: It returns the cube root of the number num. The datatype of returned cube root is same as that of the parameter passed except when an integer is passed as parameter. If the parameter passed is integral then the cbrt() function will return a value of type double. Examples: "
},
{
"code": null,
"e": 811,
"s": 761,
"text": "Input : 8\nOutput : 2 \n\nInput : 9\nOutput : 2.08008"
},
{
"code": null,
"e": 859,
"s": 811,
"text": "Below program illustrate the cbrt() function: "
},
{
"code": null,
"e": 863,
"s": 859,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate the cbrt()// STL function#include <bits/stdc++.h>using namespace std; int main(){ // cbrt() function with integral // argument int num1 = 9; cout << cbrt(num1) << endl; // cbrt() function with floating-point // argument double num2 = 7.11; cout << cbrt(num2) << endl; long long num3 = 7; cout << cbrt(num3); return 0;}",
"e": 1248,
"s": 863,
"text": null
},
{
"code": null,
"e": 1258,
"s": 1248,
"text": "Output: "
},
{
"code": null,
"e": 1281,
"s": 1258,
"text": "2.08008\n1.9229\n1.91293"
},
{
"code": null,
"e": 1296,
"s": 1283,
"text": "tranlehuy2k1"
},
{
"code": null,
"e": 1310,
"s": 1296,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1324,
"s": 1310,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1333,
"s": 1324,
"text": "cpp-math"
},
{
"code": null,
"e": 1337,
"s": 1333,
"text": "STL"
},
{
"code": null,
"e": 1341,
"s": 1337,
"text": "C++"
},
{
"code": null,
"e": 1345,
"s": 1341,
"text": "STL"
},
{
"code": null,
"e": 1349,
"s": 1345,
"text": "CPP"
},
{
"code": null,
"e": 1447,
"s": 1349,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1490,
"s": 1447,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1517,
"s": 1490,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1571,
"s": 1517,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1605,
"s": 1571,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1630,
"s": 1605,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1647,
"s": 1630,
"text": "Substring in C++"
},
{
"code": null,
"e": 1682,
"s": 1647,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 1722,
"s": 1682,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1741,
"s": 1722,
"text": "Inheritance in C++"
}
] |
ReactJS | Router | 18 Feb, 2022
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.Let us create a simple application to React to understand how the React Router works. The application will contain three components: home component, about a component, and contact component. We will use React Router to navigate between these components.
Setting up the React Application: Create a React application using create-react-app and lets call it geeks.
Note: If you’ve previously installed create-react-app globally via npm, directly use the command below:
npx create-react-app geeks
Your development environment is ready. Let us now install React Router in our Application.
Installing React Router: React Router can be installed via npm in your React application. Follow the steps given below to install Router in your React application:
Step 1: cd into your project directory i.e geeks.
Step 2: To install the React Router use the following command:
npm install – -save react-router-dom
After installing react-router-dom, add its components to your React application.
Adding React Router Components: The main Components of React Router are:
BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.
Routes: It’s a new component introduced in the v6 and a upgrade of the component. The main advantages of Routes over Switch are:Relative s and sRoutes are chosen based on the best match instead of being traversed in order.
Relative s and s
Routes are chosen based on the best match instead of being traversed in order.
Route: Route is the conditionally shown component that renders some UI when its path matches the current URL.
Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.
To add React Router components in your application, open your project directory in the editor you use and go to app.js file. Now, add the below given code in app.js.
import { BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom';
Note: BrowserRouter is aliased as Router.
Using React Router: To use React Router, let us first create few components in the react application. In your project directory, create a folder named component inside the src folder and now add 3 files named home.js, about.js and contact.js to the component folder.Let us add some code to our 3 components:
Home.js:import React from 'react'; function Home (){ return <h1>Welcome to the world of Geeks!</h1>} export default Home;
import React from 'react'; function Home (){ return <h1>Welcome to the world of Geeks!</h1>} export default Home;
About.js:import React from 'react'; function About () { return <div> <h2>GeeksforGeeks is a computer science portal for geeks!</h2> Read more about us at : <a href="https://www.geeksforgeeks.org/about/"> https://www.geeksforgeeks.org/about/ </a> </div>}export default About;
import React from 'react'; function About () { return <div> <h2>GeeksforGeeks is a computer science portal for geeks!</h2> Read more about us at : <a href="https://www.geeksforgeeks.org/about/"> https://www.geeksforgeeks.org/about/ </a> </div>}export default About;
Contact.js:import React from 'react'; function Contact (){ return <address> You can find us here:<br /> GeeksforGeeks<br /> 5th & 6th Floor, Royal Kapsons, A- 118, <br /> Sector- 136, Noida, Uttar Pradesh (201305) </address>} export default Contact;
import React from 'react'; function Contact (){ return <address> You can find us here:<br /> GeeksforGeeks<br /> 5th & 6th Floor, Royal Kapsons, A- 118, <br /> Sector- 136, Noida, Uttar Pradesh (201305) </address>} export default Contact;
Now, let us include React Router components to the application:
BrowserRouter: Add BrowserRouter aliased as Router to your app.js file in order to wrap all the other components. BrowserRouter is a parent component and can have only single child.class App extends Component { render() { return ( <Router> <div className="App"> </div> </Router> ); }}
class App extends Component { render() { return ( <Router> <div className="App"> </div> </Router> ); }}
Link: Let us now create links to our components. Link component uses the to prop to describe the location where the links should navigate to.<div className="App"> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About Us</Link> </li> <li> <Link to="/contact">Contact Us</Link> </li> </ul></div>Now, run your application on the local host and click on the links you created. You will notice the url changing according the value in to props of the Link component.
<div className="App"> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About Us</Link> </li> <li> <Link to="/contact">Contact Us</Link> </li> </ul></div>
Now, run your application on the local host and click on the links you created. You will notice the url changing according the value in to props of the Link component.
Route: Route component will now help us to establish the link between component’s UI and the URL. To include routes to the application, add the code give below to your app.js.<Route exact path='/' element={< Home />}></Route><Route exact path='/about' element={< About />}></Route><Route exact path='/contact' element={< Contact />}></Route>Components are linked now and clicking on any link will render the component associated with it.Let us now try to understand the props associated with the Route component.1.exact: It is used to match the exact value with the URL. For Eg., exact path=’/about’ will only render the component if it exactly matches the path but if we remove exact from the syntax, then UI will still be rendered even if the strucute is like /about/10.2. path: Path specifies a pathname we assign to our component.3. element: It refers to the component which will render on matching the path.Note: By default, routes are inclusive which means more than one Route component can match the URL path and render at the same time. If we want to render a single component, we need to use routes.
<Route exact path='/' element={< Home />}></Route><Route exact path='/about' element={< About />}></Route><Route exact path='/contact' element={< Contact />}></Route>
Components are linked now and clicking on any link will render the component associated with it.Let us now try to understand the props associated with the Route component.
1.exact: It is used to match the exact value with the URL. For Eg., exact path=’/about’ will only render the component if it exactly matches the path but if we remove exact from the syntax, then UI will still be rendered even if the strucute is like /about/10.
2. path: Path specifies a pathname we assign to our component.
3. element: It refers to the component which will render on matching the path.
Note: By default, routes are inclusive which means more than one Route component can match the URL path and render at the same time. If we want to render a single component, we need to use routes.
Routes: To render a single component, wrap all the routes inside the Routes Component.<Routes> <Route exact path='/' element={< Home />}></Route> <Route exact path='/about' element={< About />}></Route> <Route exact path='/contact' element={< Contact />}></Route></Routes>Switch groups together several routes, iterates over them and finds the first one that matches the path. Thereby, the corresponding component to the path is rendered.
<Routes> <Route exact path='/' element={< Home />}></Route> <Route exact path='/about' element={< About />}></Route> <Route exact path='/contact' element={< Contact />}></Route></Routes>
Switch groups together several routes, iterates over them and finds the first one that matches the path. Thereby, the corresponding component to the path is rendered.
After adding all the components here is our complete source code:
import React, { Component } from 'react';import { BrowserRouter as Router,Routes, Route, Link } from 'react-router-dom';import Home from './component/home';import About from './component/about';import Contact from './component/contact';import './App.css'; class App extends Component { render() { return ( <Router> <div className="App"> <ul className="App-header"> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About Us</Link> </li> <li> <Link to="/contact">Contact Us</Link> </li> </ul> <Routes> <Route exact path='/' element={< Home />}></Route> <Route exact path='/about' element={< About />}></Route> <Route exact path='/contact' element={< Contact />}></Route> </Routes> </div> </Router> ); }} export default App;
Now, we you can click on the links and navigate to different components. React Router keeps your application UI in sync with the URL.Finally, we have successfully implemented navigation in our React application using React Router.
aman1122singhas
chaudharinikita9999
ahampriyanshu
bhartik021
syedmohammed
Picked
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
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? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 520,
"s": 54,
"text": "React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.Let us create a simple application to React to understand how the React Router works. The application will contain three components: home component, about a component, and contact component. We will use React Router to navigate between these components."
},
{
"code": null,
"e": 628,
"s": 520,
"text": "Setting up the React Application: Create a React application using create-react-app and lets call it geeks."
},
{
"code": null,
"e": 732,
"s": 628,
"text": "Note: If you’ve previously installed create-react-app globally via npm, directly use the command below:"
},
{
"code": null,
"e": 759,
"s": 732,
"text": "npx create-react-app geeks"
},
{
"code": null,
"e": 850,
"s": 759,
"text": "Your development environment is ready. Let us now install React Router in our Application."
},
{
"code": null,
"e": 1014,
"s": 850,
"text": "Installing React Router: React Router can be installed via npm in your React application. Follow the steps given below to install Router in your React application:"
},
{
"code": null,
"e": 1064,
"s": 1014,
"text": "Step 1: cd into your project directory i.e geeks."
},
{
"code": null,
"e": 1127,
"s": 1064,
"text": "Step 2: To install the React Router use the following command:"
},
{
"code": null,
"e": 1164,
"s": 1127,
"text": "npm install – -save react-router-dom"
},
{
"code": null,
"e": 1245,
"s": 1164,
"text": "After installing react-router-dom, add its components to your React application."
},
{
"code": null,
"e": 1318,
"s": 1245,
"text": "Adding React Router Components: The main Components of React Router are:"
},
{
"code": null,
"e": 1570,
"s": 1318,
"text": "BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components."
},
{
"code": null,
"e": 1793,
"s": 1570,
"text": "Routes: It’s a new component introduced in the v6 and a upgrade of the component. The main advantages of Routes over Switch are:Relative s and sRoutes are chosen based on the best match instead of being traversed in order."
},
{
"code": null,
"e": 1810,
"s": 1793,
"text": "Relative s and s"
},
{
"code": null,
"e": 1889,
"s": 1810,
"text": "Routes are chosen based on the best match instead of being traversed in order."
},
{
"code": null,
"e": 1999,
"s": 1889,
"text": "Route: Route is the conditionally shown component that renders some UI when its path matches the current URL."
},
{
"code": null,
"e": 2144,
"s": 1999,
"text": "Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag."
},
{
"code": null,
"e": 2310,
"s": 2144,
"text": "To add React Router components in your application, open your project directory in the editor you use and go to app.js file. Now, add the below given code in app.js."
},
{
"code": "import { BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom';",
"e": 2402,
"s": 2310,
"text": null
},
{
"code": null,
"e": 2444,
"s": 2402,
"text": "Note: BrowserRouter is aliased as Router."
},
{
"code": null,
"e": 2752,
"s": 2444,
"text": "Using React Router: To use React Router, let us first create few components in the react application. In your project directory, create a folder named component inside the src folder and now add 3 files named home.js, about.js and contact.js to the component folder.Let us add some code to our 3 components:"
},
{
"code": null,
"e": 2877,
"s": 2752,
"text": "Home.js:import React from 'react'; function Home (){ return <h1>Welcome to the world of Geeks!</h1>} export default Home;"
},
{
"code": "import React from 'react'; function Home (){ return <h1>Welcome to the world of Geeks!</h1>} export default Home;",
"e": 2994,
"s": 2877,
"text": null
},
{
"code": null,
"e": 3315,
"s": 2994,
"text": "About.js:import React from 'react'; function About () { return <div> <h2>GeeksforGeeks is a computer science portal for geeks!</h2> Read more about us at : <a href=\"https://www.geeksforgeeks.org/about/\"> https://www.geeksforgeeks.org/about/ </a> </div>}export default About;"
},
{
"code": "import React from 'react'; function About () { return <div> <h2>GeeksforGeeks is a computer science portal for geeks!</h2> Read more about us at : <a href=\"https://www.geeksforgeeks.org/about/\"> https://www.geeksforgeeks.org/about/ </a> </div>}export default About;",
"e": 3627,
"s": 3315,
"text": null
},
{
"code": null,
"e": 3928,
"s": 3627,
"text": "Contact.js:import React from 'react'; function Contact (){ return <address> You can find us here:<br /> GeeksforGeeks<br /> 5th & 6th Floor, Royal Kapsons, A- 118, <br /> Sector- 136, Noida, Uttar Pradesh (201305) </address>} export default Contact;"
},
{
"code": "import React from 'react'; function Contact (){ return <address> You can find us here:<br /> GeeksforGeeks<br /> 5th & 6th Floor, Royal Kapsons, A- 118, <br /> Sector- 136, Noida, Uttar Pradesh (201305) </address>} export default Contact;",
"e": 4218,
"s": 3928,
"text": null
},
{
"code": null,
"e": 4282,
"s": 4218,
"text": "Now, let us include React Router components to the application:"
},
{
"code": null,
"e": 4606,
"s": 4282,
"text": "BrowserRouter: Add BrowserRouter aliased as Router to your app.js file in order to wrap all the other components. BrowserRouter is a parent component and can have only single child.class App extends Component { render() { return ( <Router> <div className=\"App\"> </div> </Router> ); }}"
},
{
"code": "class App extends Component { render() { return ( <Router> <div className=\"App\"> </div> </Router> ); }}",
"e": 4749,
"s": 4606,
"text": null
},
{
"code": null,
"e": 5283,
"s": 4749,
"text": "Link: Let us now create links to our components. Link component uses the to prop to describe the location where the links should navigate to.<div className=\"App\"> <ul> <li> <Link to=\"/\">Home</Link> </li> <li> <Link to=\"/about\">About Us</Link> </li> <li> <Link to=\"/contact\">Contact Us</Link> </li> </ul></div>Now, run your application on the local host and click on the links you created. You will notice the url changing according the value in to props of the Link component."
},
{
"code": "<div className=\"App\"> <ul> <li> <Link to=\"/\">Home</Link> </li> <li> <Link to=\"/about\">About Us</Link> </li> <li> <Link to=\"/contact\">Contact Us</Link> </li> </ul></div>",
"e": 5509,
"s": 5283,
"text": null
},
{
"code": null,
"e": 5677,
"s": 5509,
"text": "Now, run your application on the local host and click on the links you created. You will notice the url changing according the value in to props of the Link component."
},
{
"code": null,
"e": 6786,
"s": 5677,
"text": "Route: Route component will now help us to establish the link between component’s UI and the URL. To include routes to the application, add the code give below to your app.js.<Route exact path='/' element={< Home />}></Route><Route exact path='/about' element={< About />}></Route><Route exact path='/contact' element={< Contact />}></Route>Components are linked now and clicking on any link will render the component associated with it.Let us now try to understand the props associated with the Route component.1.exact: It is used to match the exact value with the URL. For Eg., exact path=’/about’ will only render the component if it exactly matches the path but if we remove exact from the syntax, then UI will still be rendered even if the strucute is like /about/10.2. path: Path specifies a pathname we assign to our component.3. element: It refers to the component which will render on matching the path.Note: By default, routes are inclusive which means more than one Route component can match the URL path and render at the same time. If we want to render a single component, we need to use routes."
},
{
"code": "<Route exact path='/' element={< Home />}></Route><Route exact path='/about' element={< About />}></Route><Route exact path='/contact' element={< Contact />}></Route>",
"e": 6953,
"s": 6786,
"text": null
},
{
"code": null,
"e": 7125,
"s": 6953,
"text": "Components are linked now and clicking on any link will render the component associated with it.Let us now try to understand the props associated with the Route component."
},
{
"code": null,
"e": 7386,
"s": 7125,
"text": "1.exact: It is used to match the exact value with the URL. For Eg., exact path=’/about’ will only render the component if it exactly matches the path but if we remove exact from the syntax, then UI will still be rendered even if the strucute is like /about/10."
},
{
"code": null,
"e": 7449,
"s": 7386,
"text": "2. path: Path specifies a pathname we assign to our component."
},
{
"code": null,
"e": 7528,
"s": 7449,
"text": "3. element: It refers to the component which will render on matching the path."
},
{
"code": null,
"e": 7725,
"s": 7528,
"text": "Note: By default, routes are inclusive which means more than one Route component can match the URL path and render at the same time. If we want to render a single component, we need to use routes."
},
{
"code": null,
"e": 8173,
"s": 7725,
"text": "Routes: To render a single component, wrap all the routes inside the Routes Component.<Routes> <Route exact path='/' element={< Home />}></Route> <Route exact path='/about' element={< About />}></Route> <Route exact path='/contact' element={< Contact />}></Route></Routes>Switch groups together several routes, iterates over them and finds the first one that matches the path. Thereby, the corresponding component to the path is rendered."
},
{
"code": "<Routes> <Route exact path='/' element={< Home />}></Route> <Route exact path='/about' element={< About />}></Route> <Route exact path='/contact' element={< Contact />}></Route></Routes>",
"e": 8369,
"s": 8173,
"text": null
},
{
"code": null,
"e": 8536,
"s": 8369,
"text": "Switch groups together several routes, iterates over them and finds the first one that matches the path. Thereby, the corresponding component to the path is rendered."
},
{
"code": null,
"e": 8602,
"s": 8536,
"text": "After adding all the components here is our complete source code:"
},
{
"code": "import React, { Component } from 'react';import { BrowserRouter as Router,Routes, Route, Link } from 'react-router-dom';import Home from './component/home';import About from './component/about';import Contact from './component/contact';import './App.css'; class App extends Component { render() { return ( <Router> <div className=\"App\"> <ul className=\"App-header\"> <li> <Link to=\"/\">Home</Link> </li> <li> <Link to=\"/about\">About Us</Link> </li> <li> <Link to=\"/contact\">Contact Us</Link> </li> </ul> <Routes> <Route exact path='/' element={< Home />}></Route> <Route exact path='/about' element={< About />}></Route> <Route exact path='/contact' element={< Contact />}></Route> </Routes> </div> </Router> ); }} export default App;",
"e": 9584,
"s": 8602,
"text": null
},
{
"code": null,
"e": 9815,
"s": 9584,
"text": "Now, we you can click on the links and navigate to different components. React Router keeps your application UI in sync with the URL.Finally, we have successfully implemented navigation in our React application using React Router."
},
{
"code": null,
"e": 9831,
"s": 9815,
"text": "aman1122singhas"
},
{
"code": null,
"e": 9851,
"s": 9831,
"text": "chaudharinikita9999"
},
{
"code": null,
"e": 9865,
"s": 9851,
"text": "ahampriyanshu"
},
{
"code": null,
"e": 9876,
"s": 9865,
"text": "bhartik021"
},
{
"code": null,
"e": 9889,
"s": 9876,
"text": "syedmohammed"
},
{
"code": null,
"e": 9896,
"s": 9889,
"text": "Picked"
},
{
"code": null,
"e": 9905,
"s": 9896,
"text": "react-js"
},
{
"code": null,
"e": 9922,
"s": 9905,
"text": "Web Technologies"
},
{
"code": null,
"e": 10020,
"s": 9922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10053,
"s": 10020,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 10115,
"s": 10053,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 10176,
"s": 10115,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 10226,
"s": 10176,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 10269,
"s": 10226,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 10309,
"s": 10269,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 10333,
"s": 10309,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 10366,
"s": 10333,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 10426,
"s": 10366,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
multimap equal_range() in C++ STL | 13 Nov, 2020
The multimap::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container’s internal comparison object (key_comp).
Syntax:
iterator multimap_name.equal_range(key)
Parameters: This function accepts a single mandatory parameter key which specifies the element whose range in the container is to be returned.
Return Value: The function returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container’s internal comparison object (key_comp).
Program below illustrate the above method:
C++
// C++ program to illustrate the// multimap::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 1, 20 }); mp.insert({ 5, 50 }); // Stores the range of key 1 auto it = mp.equal_range(1); cout << "The multimap elements of key 1 is : \n"; cout << "KEY\tELEMENT\n"; // Prints all the elements of key 1 for (auto itr = it.first; itr != it.second; ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The multimap elements of key 1 is :
KEY ELEMENT
1 40
1 20
arorakashish0911
CPP-Functions
cpp-multimap
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Substring in C++
C++ Classes and Objects
The C++ Standard Template Library (STL)
Sorting a vector in C++
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
2D Vector In C++ With User Defined Size | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Nov, 2020"
},
{
"code": null,
"e": 478,
"s": 28,
"text": "The multimap::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container’s internal comparison object (key_comp). "
},
{
"code": null,
"e": 488,
"s": 478,
"text": "Syntax: "
},
{
"code": null,
"e": 530,
"s": 488,
"text": "iterator multimap_name.equal_range(key)\n\n"
},
{
"code": null,
"e": 674,
"s": 530,
"text": "Parameters: This function accepts a single mandatory parameter key which specifies the element whose range in the container is to be returned. "
},
{
"code": null,
"e": 1082,
"s": 674,
"text": "Return Value: The function returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container’s internal comparison object (key_comp)."
},
{
"code": null,
"e": 1127,
"s": 1082,
"text": "Program below illustrate the above method: "
},
{
"code": null,
"e": 1131,
"s": 1127,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// multimap::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 1, 20 }); mp.insert({ 5, 50 }); // Stores the range of key 1 auto it = mp.equal_range(1); cout << \"The multimap elements of key 1 is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; // Prints all the elements of key 1 for (auto itr = it.first; itr != it.second; ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}",
"e": 1805,
"s": 1131,
"text": null
},
{
"code": null,
"e": 1878,
"s": 1805,
"text": "The multimap elements of key 1 is : \nKEY ELEMENT\n1 40\n1 20\n\n\n\n\n"
},
{
"code": null,
"e": 1897,
"s": 1880,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1911,
"s": 1897,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1924,
"s": 1911,
"text": "cpp-multimap"
},
{
"code": null,
"e": 1928,
"s": 1924,
"text": "STL"
},
{
"code": null,
"e": 1932,
"s": 1928,
"text": "C++"
},
{
"code": null,
"e": 1936,
"s": 1932,
"text": "STL"
},
{
"code": null,
"e": 1940,
"s": 1936,
"text": "CPP"
},
{
"code": null,
"e": 2038,
"s": 1940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2065,
"s": 2038,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 2099,
"s": 2065,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2118,
"s": 2099,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 2135,
"s": 2118,
"text": "Substring in C++"
},
{
"code": null,
"e": 2159,
"s": 2135,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 2199,
"s": 2159,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2223,
"s": 2199,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2258,
"s": 2223,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 2312,
"s": 2258,
"text": "Priority Queue in C++ Standard Template Library (STL)"
}
] |
Averages of Levels in Binary Tree | 01 Jul, 2021
Given a non-empty binary tree, print the average value of the nodes on each level.
Examples:
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : [4 5.5 5]
The average value of nodes on level 0 is 4,
on level 1 is 5.5, and on level 2 is 5.
Hence, print [4 5.5 5].
The idea is based on Level order traversal line by line | Set 2 (Using Two Queues)
Start by pushing the root node into the queue. Then, remove a node from the front of the queue.For every node removed from the queue, push all its children into a new temporary queue.Keep on popping nodes from the queue and adding these node’ s children to the temporary queue till queue becomes empty.Every time queue becomes empty, it indicates that one level of the tree has been considered.While pushing the nodes into temporary queue, keep a track of the sum of the nodes along with the number of nodes pushed and find out the average of the nodes on each level by making use of these sum and count values.After each level has been considered, again initialize the queue with temporary queue and continue the process till both queues become empty.
Start by pushing the root node into the queue. Then, remove a node from the front of the queue.
For every node removed from the queue, push all its children into a new temporary queue.
Keep on popping nodes from the queue and adding these node’ s children to the temporary queue till queue becomes empty.
Every time queue becomes empty, it indicates that one level of the tree has been considered.
While pushing the nodes into temporary queue, keep a track of the sum of the nodes along with the number of nodes pushed and find out the average of the nodes on each level by making use of these sum and count values.
After each level has been considered, again initialize the queue with temporary queue and continue the process till both queues become empty.
C++
Java
Python3
C#
Javascript
// C++ program to find averages of all levels// in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int val; struct Node* left, *right;}; /* Function to print the average value of the nodes on each level */void averageOfLevels(Node* root){ vector<float> res; // Traversing level by level queue<Node*> q; q.push(root); while (!q.empty()) { // Compute sum of nodes and // count of nodes in current // level. int sum = 0, count = 0; queue<Node*> temp; while (!q.empty()) { Node* n = q.front(); q.pop(); sum += n->val; count++; if (n->left != NULL) temp.push(n->left); if (n->right != NULL) temp.push(n->right); } q = temp; cout << (sum * 1.0 / count) << " "; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); averageOfLevels(root); return 0;}
// Java program to find averages of all levels// in a binary tree.import java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Function to print the average value of thenodes on each level */static void averageOfLevels(Node root){ //vector<float> res; // Traversing level by level Queue<Node> q = new LinkedList<Node> (); q.add(root); int sum = 0, count = 0; while (!q.isEmpty()) { // Compute sum of nodes and // count of nodes in current // level. sum = 0; count = 0; Queue<Node> temp = new LinkedList<Node> (); while (!q.isEmpty()) { Node n = q.peek(); q.remove(); sum += n.val; count++; if (n.left != null) temp.add(n.left); if (n.right != null) temp.add(n.right); } q = temp; System.out.print((sum * 1.0 / count) + " "); }} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(5); root.right.right = newNode(7); System.out.println("Averages of levels : "); System.out.print("["); averageOfLevels(root); System.out.println("]");}}
# Python3 program to find averages of# all levels in a binary tree. # Importing Queuefrom queue import Queue # Helper class that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Function to print the average value# of the nodes on each leveldef averageOfLevels(root): # Traversing level by level q = Queue() q.put(root) while (not q.empty()): # Compute Sum of nodes and # count of nodes in current # level. Sum = 0 count = 0 temp = Queue() while (not q.empty()): n = q.queue[0] q.get() Sum += n.val count += 1 if (n.left != None): temp.put(n.left) if (n.right != None): temp.put(n.right) q = temp print((Sum * 1.0 / count), end = " ") # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \ # 2 9 # / \ \ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) averageOfLevels(root) # This code is contributed by PranchalK
// C# program to find averages of all levels// in a binary tree.using System;using System.Collections.Generic; class GfG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public int val; public Node left, right; } /* Function to print the average value of the nodes on each level */ static void averageOfLevels(Node root) { //vector<float> res; // Traversing level by level Queue<Node> q = new Queue<Node> (); q.Enqueue(root); int sum = 0, count = 0; while ((q.Count!=0)) { // Compute sum of nodes and // count of nodes in current // level. sum = 0; count = 0; Queue<Node> temp = new Queue<Node> (); while (q.Count != 0) { Node n = q.Peek(); q.Dequeue(); sum += n.val; count++; if (n.left != null) temp.Enqueue(n.left); if (n.right != null) temp.Enqueue(n.right); } q = temp; Console.Write((sum * 1.0 / count) + " "); } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ static Node newNode(int data) { Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp; } // Driver code public static void Main(String[] args) { /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(5); root.right.right = newNode(7); Console.WriteLine("Averages of levels : "); Console.Write("["); averageOfLevels(root); Console.WriteLine("]"); }} // This code has been contributed by// 29AjayKumar
<script> // Javascript program to find averages of// all levels in a binary tree.class Node{ constructor(data) { this.left = null; this.right = null; this.val = data; }} // Function to print the average value// of the nodes on each levelfunction averageOfLevels(root){ // Traversing level by level let q = []; q.push(root); let sum = 0, count = 0; while (q.length > 0) { // Compute sum of nodes and // count of nodes in current // level. sum = 0; count = 0; let temp = []; while (q.length > 0) { let n = q[0]; q.shift(); sum += n.val; count++; if (n.left != null) temp.push(n.left); if (n.right != null) temp.push(n.right); } q = temp; document.write((sum * 1.0 / count) + " "); }} // Helper function that allocates a// new node with the given data and// NULL left and right pointers.function newNode(data){ let temp = new Node(data); return temp;} // Driver code /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */let root = null;root = newNode(4);root.left = newNode(2);root.right = newNode(9);root.left.left = newNode(3);root.left.right = newNode(5);root.right.right = newNode(7); document.write("Averages of levels : " + "</br>");document.write("[");averageOfLevels(root);document.write("]" + "</br>"); // This code is contributed by divyeshrabadiya07 </script>
Output:
Average of levels:
[4 5.5 5]
Complexity Analysis:
Time complexity : O(n). The whole tree is traversed atmost once. Here, n refers to the number of nodes in the given binary tree.
Auxiliary Space : O(n). The size of queues can grow upto atmost the maximum number of nodes at any level in the given binary tree. Here, n refers to the maximum number of nodes at any level in the input tree.
Averages of Levels in Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAverages of Levels in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=BgRuUsatWhw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aakash Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prerna saini
PranchalKatiyar
29AjayKumar
nidhi_biet
divyeshrabadiya07
tree-level-order
Queue
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Sliding Window Maximum (Maximum of all subarrays of size k)
What is Priority Queue | Introduction to Priority Queue
LRU Cache Implementation
Queue | Set 1 (Introduction and Array Implementation)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
Introduction to Tree Data Structure | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Given a non-empty binary tree, print the average value of the nodes on each level."
},
{
"code": null,
"e": 146,
"s": 135,
"text": "Examples: "
},
{
"code": null,
"e": 325,
"s": 146,
"text": "Input : \n 4\n / \\\n 2 9\n / \\ \\\n3 5 7\n\nOutput : [4 5.5 5]\nThe average value of nodes on level 0 is 4, \non level 1 is 5.5, and on level 2 is 5. \nHence, print [4 5.5 5]."
},
{
"code": null,
"e": 408,
"s": 325,
"text": "The idea is based on Level order traversal line by line | Set 2 (Using Two Queues)"
},
{
"code": null,
"e": 1161,
"s": 408,
"text": "Start by pushing the root node into the queue. Then, remove a node from the front of the queue.For every node removed from the queue, push all its children into a new temporary queue.Keep on popping nodes from the queue and adding these node’ s children to the temporary queue till queue becomes empty.Every time queue becomes empty, it indicates that one level of the tree has been considered.While pushing the nodes into temporary queue, keep a track of the sum of the nodes along with the number of nodes pushed and find out the average of the nodes on each level by making use of these sum and count values.After each level has been considered, again initialize the queue with temporary queue and continue the process till both queues become empty."
},
{
"code": null,
"e": 1257,
"s": 1161,
"text": "Start by pushing the root node into the queue. Then, remove a node from the front of the queue."
},
{
"code": null,
"e": 1346,
"s": 1257,
"text": "For every node removed from the queue, push all its children into a new temporary queue."
},
{
"code": null,
"e": 1466,
"s": 1346,
"text": "Keep on popping nodes from the queue and adding these node’ s children to the temporary queue till queue becomes empty."
},
{
"code": null,
"e": 1559,
"s": 1466,
"text": "Every time queue becomes empty, it indicates that one level of the tree has been considered."
},
{
"code": null,
"e": 1777,
"s": 1559,
"text": "While pushing the nodes into temporary queue, keep a track of the sum of the nodes along with the number of nodes pushed and find out the average of the nodes on each level by making use of these sum and count values."
},
{
"code": null,
"e": 1919,
"s": 1777,
"text": "After each level has been considered, again initialize the queue with temporary queue and continue the process till both queues become empty."
},
{
"code": null,
"e": 1923,
"s": 1919,
"text": "C++"
},
{
"code": null,
"e": 1928,
"s": 1923,
"text": "Java"
},
{
"code": null,
"e": 1936,
"s": 1928,
"text": "Python3"
},
{
"code": null,
"e": 1939,
"s": 1936,
"text": "C#"
},
{
"code": null,
"e": 1950,
"s": 1939,
"text": "Javascript"
},
{
"code": "// C++ program to find averages of all levels// in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int val; struct Node* left, *right;}; /* Function to print the average value of the nodes on each level */void averageOfLevels(Node* root){ vector<float> res; // Traversing level by level queue<Node*> q; q.push(root); while (!q.empty()) { // Compute sum of nodes and // count of nodes in current // level. int sum = 0, count = 0; queue<Node*> temp; while (!q.empty()) { Node* n = q.front(); q.pop(); sum += n->val; count++; if (n->left != NULL) temp.push(n->left); if (n->right != NULL) temp.push(n->right); } q = temp; cout << (sum * 1.0 / count) << \" \"; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); averageOfLevels(root); return 0;}",
"e": 3506,
"s": 1950,
"text": null
},
{
"code": "// Java program to find averages of all levels// in a binary tree.import java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Function to print the average value of thenodes on each level */static void averageOfLevels(Node root){ //vector<float> res; // Traversing level by level Queue<Node> q = new LinkedList<Node> (); q.add(root); int sum = 0, count = 0; while (!q.isEmpty()) { // Compute sum of nodes and // count of nodes in current // level. sum = 0; count = 0; Queue<Node> temp = new LinkedList<Node> (); while (!q.isEmpty()) { Node n = q.peek(); q.remove(); sum += n.val; count++; if (n.left != null) temp.add(n.left); if (n.right != null) temp.add(n.right); } q = temp; System.out.print((sum * 1.0 / count) + \" \"); }} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(5); root.right.right = newNode(7); System.out.println(\"Averages of levels : \"); System.out.print(\"[\"); averageOfLevels(root); System.out.println(\"]\");}}",
"e": 5236,
"s": 3506,
"text": null
},
{
"code": "# Python3 program to find averages of# all levels in a binary tree. # Importing Queuefrom queue import Queue # Helper class that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Function to print the average value# of the nodes on each leveldef averageOfLevels(root): # Traversing level by level q = Queue() q.put(root) while (not q.empty()): # Compute Sum of nodes and # count of nodes in current # level. Sum = 0 count = 0 temp = Queue() while (not q.empty()): n = q.queue[0] q.get() Sum += n.val count += 1 if (n.left != None): temp.put(n.left) if (n.right != None): temp.put(n.right) q = temp print((Sum * 1.0 / count), end = \" \") # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \\ # 2 9 # / \\ \\ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) averageOfLevels(root) # This code is contributed by PranchalK",
"e": 6559,
"s": 5236,
"text": null
},
{
"code": "// C# program to find averages of all levels// in a binary tree.using System;using System.Collections.Generic; class GfG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public int val; public Node left, right; } /* Function to print the average value of the nodes on each level */ static void averageOfLevels(Node root) { //vector<float> res; // Traversing level by level Queue<Node> q = new Queue<Node> (); q.Enqueue(root); int sum = 0, count = 0; while ((q.Count!=0)) { // Compute sum of nodes and // count of nodes in current // level. sum = 0; count = 0; Queue<Node> temp = new Queue<Node> (); while (q.Count != 0) { Node n = q.Peek(); q.Dequeue(); sum += n.val; count++; if (n.left != null) temp.Enqueue(n.left); if (n.right != null) temp.Enqueue(n.right); } q = temp; Console.Write((sum * 1.0 / count) + \" \"); } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ static Node newNode(int data) { Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp; } // Driver code public static void Main(String[] args) { /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(5); root.right.right = newNode(7); Console.WriteLine(\"Averages of levels : \"); Console.Write(\"[\"); averageOfLevels(root); Console.WriteLine(\"]\"); }} // This code has been contributed by// 29AjayKumar",
"e": 8659,
"s": 6559,
"text": null
},
{
"code": "<script> // Javascript program to find averages of// all levels in a binary tree.class Node{ constructor(data) { this.left = null; this.right = null; this.val = data; }} // Function to print the average value// of the nodes on each levelfunction averageOfLevels(root){ // Traversing level by level let q = []; q.push(root); let sum = 0, count = 0; while (q.length > 0) { // Compute sum of nodes and // count of nodes in current // level. sum = 0; count = 0; let temp = []; while (q.length > 0) { let n = q[0]; q.shift(); sum += n.val; count++; if (n.left != null) temp.push(n.left); if (n.right != null) temp.push(n.right); } q = temp; document.write((sum * 1.0 / count) + \" \"); }} // Helper function that allocates a// new node with the given data and// NULL left and right pointers.function newNode(data){ let temp = new Node(data); return temp;} // Driver code /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */let root = null;root = newNode(4);root.left = newNode(2);root.right = newNode(9);root.left.left = newNode(3);root.left.right = newNode(5);root.right.right = newNode(7); document.write(\"Averages of levels : \" + \"</br>\");document.write(\"[\");averageOfLevels(root);document.write(\"]\" + \"</br>\"); // This code is contributed by divyeshrabadiya07 </script>",
"e": 10218,
"s": 8659,
"text": null
},
{
"code": null,
"e": 10227,
"s": 10218,
"text": "Output: "
},
{
"code": null,
"e": 10257,
"s": 10227,
"text": "Average of levels: \n[4 5.5 5]"
},
{
"code": null,
"e": 10279,
"s": 10257,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 10408,
"s": 10279,
"text": "Time complexity : O(n). The whole tree is traversed atmost once. Here, n refers to the number of nodes in the given binary tree."
},
{
"code": null,
"e": 10618,
"s": 10408,
"text": "Auxiliary Space : O(n). The size of queues can grow upto atmost the maximum number of nodes at any level in the given binary tree. Here, n refers to the maximum number of nodes at any level in the input tree. "
},
{
"code": null,
"e": 11502,
"s": 10618,
"text": "Averages of Levels in Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAverages of Levels in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:22•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=BgRuUsatWhw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 11921,
"s": 11502,
"text": "This article is contributed by Aakash Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11934,
"s": 11921,
"text": "prerna saini"
},
{
"code": null,
"e": 11950,
"s": 11934,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 11962,
"s": 11950,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11973,
"s": 11962,
"text": "nidhi_biet"
},
{
"code": null,
"e": 11991,
"s": 11973,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 12008,
"s": 11991,
"text": "tree-level-order"
},
{
"code": null,
"e": 12014,
"s": 12008,
"text": "Queue"
},
{
"code": null,
"e": 12019,
"s": 12014,
"text": "Tree"
},
{
"code": null,
"e": 12025,
"s": 12019,
"text": "Queue"
},
{
"code": null,
"e": 12030,
"s": 12025,
"text": "Tree"
},
{
"code": null,
"e": 12128,
"s": 12030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12160,
"s": 12128,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 12220,
"s": 12160,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
},
{
"code": null,
"e": 12276,
"s": 12220,
"text": "What is Priority Queue | Introduction to Priority Queue"
},
{
"code": null,
"e": 12301,
"s": 12276,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 12355,
"s": 12301,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 12405,
"s": 12355,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 12440,
"s": 12405,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 12469,
"s": 12440,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 12501,
"s": 12469,
"text": "Introduction to Data Structures"
}
] |
numpy.tile() in Python | 28 Mar, 2022
The numpy.tile() function constructs a new array by repeating array – ‘arr’, the number of times we want to repeat as per repetitions. The resulted array will have dimensions max(arr.ndim, repetitions) where, repetitions is the length of repetitions. If arr.ndim > repetitions, reps is promoted to arr.ndim by pre-pending 1’s to it. If arr.ndim < repetitions, reps is promoted to arr.ndim by pre-pending new axis. Syntax :
numpy.tile(arr, repetitions)
Parameters :
array : [array_like]Input array.
repetitions : No. of repetitions of arr along each axis.
Return :
An array with repetitions of array - arr as per d, number of times we want to repeat arr
Code 1 :
Python
# Python Program illustrating# numpy.tile() import numpy as geek #Working on 1Darr = geek.arange(5)print("arr : \n", arr) repetitions = 2print("Repeating arr 2 times : \n", geek.tile(arr, repetitions)) repetitions = 3print("\nRepeating arr 3 times : \n", geek.tile(arr, repetitions))# [0 1 2 ..., 2 3 4] means [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]# since it was long output, so it uses [ ... ]
Output :
arr :
[0 1 2 3 4]
Repeating arr 2 times :
[0 1 2 3 4 0 1 2 3 4]
Repeating arr 3 times :
[0 1 2 ..., 2 3 4]
Code 2 :
Python
# Python Program illustrating# numpy.tile() import numpy as geek arr = geek.arange(3)print("arr : \n", arr) a = 2 b = 2 repetitions = (a, b)print("\nRepeating arr : \n", geek.tile(arr, repetitions))print("arr Shape : \n", geek.tile(arr, repetitions).shape) a = 3 b = 2 repetitions = (a, b)print("\nRepeating arr : \n", geek.tile(arr, repetitions))print("arr Shape : \n", geek.tile(arr, repetitions).shape) a = 2b = 3 repetitions = (a, b)print("\nRepeating arr : \n", geek.tile(arr, repetitions))print("arr Shape : \n", geek.tile(arr, repetitions).shape)
Output :
arr :
[0 1 2]
Repeating arr :
[[0 1 2 0 1 2]
[0 1 2 0 1 2]]
arr Shape :
(2, 6)
Repeating arr :
[[0 1 2 0 1 2]
[0 1 2 0 1 2]
[0 1 2 0 1 2]]
arr Shape :
(3, 6)
Repeating arr :
[[0 1 2 ..., 0 1 2]
[0 1 2 ..., 0 1 2]]
arr Shape :
(2, 9)
Code 3 : (repetitions == arr.ndim) == 0
Python
# Python Program illustrating# numpy.tile() import numpy as geek arr = geek.arange(4).reshape(2, 2)print("arr : \n", arr) a = 2 b = 1 repetitions = (a, b)print("\nRepeating arr : \n", geek.tile(arr, repetitions))print("arr Shape : \n", geek.tile(arr, repetitions).shape) a = 3 b = 2 repetitions = (a, b)print("\nRepeating arr : \n", geek.tile(arr, repetitions))print("arr Shape : \n", geek.tile(arr, repetitions).shape) a = 2b = 3 repetitions = (a, b)print("\nRepeating arr : \n", geek.tile(arr, repetitions))print("arr Shape : \n", geek.tile(arr, repetitions).shape)
Output :
arr :
[[0 1]
[2 3]]
Repeating arr :
[[0 1]
[2 3]
[0 1]
[2 3]]
arr Shape :
(4, 2)
Repeating arr :
[[0 1 0 1]
[2 3 2 3]
[0 1 0 1]
[2 3 2 3]
[0 1 0 1]
[2 3 2 3]]
arr Shape :
(6, 4)
Repeating arr :
[[0 1 0 1 0 1]
[2 3 2 3 2 3]
[0 1 0 1 0 1]
[2 3 2 3 2 3]]
arr Shape :
(4, 6)
References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kothavvsaakash
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
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
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 476,
"s": 52,
"text": "The numpy.tile() function constructs a new array by repeating array – ‘arr’, the number of times we want to repeat as per repetitions. The resulted array will have dimensions max(arr.ndim, repetitions) where, repetitions is the length of repetitions. If arr.ndim > repetitions, reps is promoted to arr.ndim by pre-pending 1’s to it. If arr.ndim < repetitions, reps is promoted to arr.ndim by pre-pending new axis. Syntax : "
},
{
"code": null,
"e": 505,
"s": 476,
"text": "numpy.tile(arr, repetitions)"
},
{
"code": null,
"e": 519,
"s": 505,
"text": "Parameters : "
},
{
"code": null,
"e": 617,
"s": 519,
"text": "array : [array_like]Input array. \nrepetitions : No. of repetitions of arr along each axis. "
},
{
"code": null,
"e": 627,
"s": 617,
"text": "Return : "
},
{
"code": null,
"e": 718,
"s": 627,
"text": "An array with repetitions of array - arr as per d, number of times we want to repeat arr "
},
{
"code": null,
"e": 728,
"s": 718,
"text": "Code 1 : "
},
{
"code": null,
"e": 735,
"s": 728,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.tile() import numpy as geek #Working on 1Darr = geek.arange(5)print(\"arr : \\n\", arr) repetitions = 2print(\"Repeating arr 2 times : \\n\", geek.tile(arr, repetitions)) repetitions = 3print(\"\\nRepeating arr 3 times : \\n\", geek.tile(arr, repetitions))# [0 1 2 ..., 2 3 4] means [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]# since it was long output, so it uses [ ... ]",
"e": 1123,
"s": 735,
"text": null
},
{
"code": null,
"e": 1133,
"s": 1123,
"text": "Output : "
},
{
"code": null,
"e": 1247,
"s": 1133,
"text": "arr : \n [0 1 2 3 4]\nRepeating arr 2 times : \n [0 1 2 3 4 0 1 2 3 4]\n\nRepeating arr 3 times : \n [0 1 2 ..., 2 3 4]"
},
{
"code": null,
"e": 1257,
"s": 1247,
"text": "Code 2 : "
},
{
"code": null,
"e": 1264,
"s": 1257,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.tile() import numpy as geek arr = geek.arange(3)print(\"arr : \\n\", arr) a = 2 b = 2 repetitions = (a, b)print(\"\\nRepeating arr : \\n\", geek.tile(arr, repetitions))print(\"arr Shape : \\n\", geek.tile(arr, repetitions).shape) a = 3 b = 2 repetitions = (a, b)print(\"\\nRepeating arr : \\n\", geek.tile(arr, repetitions))print(\"arr Shape : \\n\", geek.tile(arr, repetitions).shape) a = 2b = 3 repetitions = (a, b)print(\"\\nRepeating arr : \\n\", geek.tile(arr, repetitions))print(\"arr Shape : \\n\", geek.tile(arr, repetitions).shape)",
"e": 1819,
"s": 1264,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1819,
"text": "Output : "
},
{
"code": null,
"e": 2083,
"s": 1829,
"text": "arr : \n [0 1 2]\n\nRepeating arr : \n [[0 1 2 0 1 2]\n [0 1 2 0 1 2]]\narr Shape : \n (2, 6)\n\nRepeating arr : \n [[0 1 2 0 1 2]\n [0 1 2 0 1 2]\n [0 1 2 0 1 2]]\narr Shape : \n (3, 6)\n\nRepeating arr : \n [[0 1 2 ..., 0 1 2]\n [0 1 2 ..., 0 1 2]]\narr Shape : \n (2, 9)"
},
{
"code": null,
"e": 2124,
"s": 2083,
"text": "Code 3 : (repetitions == arr.ndim) == 0 "
},
{
"code": null,
"e": 2131,
"s": 2124,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.tile() import numpy as geek arr = geek.arange(4).reshape(2, 2)print(\"arr : \\n\", arr) a = 2 b = 1 repetitions = (a, b)print(\"\\nRepeating arr : \\n\", geek.tile(arr, repetitions))print(\"arr Shape : \\n\", geek.tile(arr, repetitions).shape) a = 3 b = 2 repetitions = (a, b)print(\"\\nRepeating arr : \\n\", geek.tile(arr, repetitions))print(\"arr Shape : \\n\", geek.tile(arr, repetitions).shape) a = 2b = 3 repetitions = (a, b)print(\"\\nRepeating arr : \\n\", geek.tile(arr, repetitions))print(\"arr Shape : \\n\", geek.tile(arr, repetitions).shape)",
"e": 2700,
"s": 2131,
"text": null
},
{
"code": null,
"e": 2710,
"s": 2700,
"text": "Output : "
},
{
"code": null,
"e": 3010,
"s": 2710,
"text": "arr : \n [[0 1]\n [2 3]]\n\nRepeating arr : \n [[0 1]\n [2 3]\n [0 1]\n [2 3]]\narr Shape : \n (4, 2)\n\nRepeating arr : \n [[0 1 0 1]\n [2 3 2 3]\n [0 1 0 1]\n [2 3 2 3]\n [0 1 0 1]\n [2 3 2 3]]\narr Shape : \n (6, 4)\n\nRepeating arr : \n [[0 1 0 1 0 1]\n [2 3 2 3 2 3]\n [0 1 0 1 0 1]\n [2 3 2 3 2 3]]\narr Shape : \n (4, 6)"
},
{
"code": null,
"e": 3620,
"s": 3010,
"text": "References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3635,
"s": 3620,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 3666,
"s": 3635,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 3679,
"s": 3666,
"text": "Python-numpy"
},
{
"code": null,
"e": 3686,
"s": 3679,
"text": "Python"
},
{
"code": null,
"e": 3784,
"s": 3686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3802,
"s": 3784,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3844,
"s": 3802,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3866,
"s": 3844,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3901,
"s": 3866,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3927,
"s": 3901,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3959,
"s": 3927,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3988,
"s": 3959,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4015,
"s": 3988,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4045,
"s": 4015,
"text": "Iterate over a list in Python"
}
] |
Switch Statement in Java | 25 Jun, 2022
The switch statement is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions. It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. It basically tests the equality of variables against multiple values.
Note: Java switch expression must be of byte, short, int, long(with its Wrapper type), enums and string. Beginning with JDK7, it also works with enumerated types (Enums in java), the String class, and Wrapper classes.
There can be any number of cases just imposing condition check but remember duplicate case/s values are not allowed.The value for a case must be of the same data type as the variable in the switch.The value for a case must be constant or literal. Variables are not allowed.The break statement is used inside the switch to terminate a statement sequence.The break statement is optional. If omitted, execution will continue on into the next case.The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.
There can be any number of cases just imposing condition check but remember duplicate case/s values are not allowed.
The value for a case must be of the same data type as the variable in the switch.
The value for a case must be constant or literal. Variables are not allowed.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional. If omitted, execution will continue on into the next case.
The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.
Syntax: Switch-case
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
// We can have any number of case statements
// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}
Note: Java switch statement is a fall through statement that means it executes all statements if break keyword is not used, so it is highly essential to use break keyword inside each case.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Example: Consider the following java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of the day, using the switch statement.
Java
// Java program to Demonstrate Switch Case// with Primitive(int) Data Type // Classpublic class GFG { // Main driver method public static void main(String[] args) { int day = 5; String dayString; // Switch statement with int data type switch (day) { // Case case 1: dayString = "Monday"; break; // Case case 2: dayString = "Tuesday"; break; // Case case 3: dayString = "Wednesday"; break; // Case case 4: dayString = "Thursday"; break; // Case case 5: dayString = "Friday"; break; // Case case 6: dayString = "Saturday"; break; // Case case 7: dayString = "Sunday"; break; // Default case default: dayString = "Invalid day"; } System.out.println(dayString); }}
Friday
A break statement is optional. If we omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For instance, let us consider the updated version of the above program, it also displays whether a day is a weekday or a weekend day.
Example:
Java
// Java Program to Demonstrate Switch Case// with Multiple Cases Without Break Statements // Classpublic class GFG { // main driver method public static void main(String[] args) { int day = 2; String dayType; String dayString; // Switch case switch (day) { // Case case 1: dayString = "Monday"; break; // Case case 2: dayString = "Tuesday"; break; // Case case 3: dayString = "Wednesday"; break; case 4: dayString = "Thursday"; break; case 5: dayString = "Friday"; break; case 6: dayString = "Saturday"; break; case 7: dayString = "Sunday"; break; default: dayString = "Invalid day"; } switch (day) { // Multiple cases without break statements case 1: case 2: case 3: case 4: case 5: dayType = "Weekday"; break; case 6: case 7: dayType = "Weekend"; break; default: dayType = "Invalid daytype"; } System.out.println(dayString + " is a " + dayType); }}
Tuesday is a Weekday
We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch.
Example:
Java
// Java Program to Demonstrate// Nested Switch Case Statement // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String Branch = "CSE"; int year = 2; // Switch case switch (year) { // Case case 1: System.out.println( "elective courses : Advance english, Algebra"); // Break statement to hault execution here // itself if case is matched break; // Case case 2: // Switch inside a switch // Nested Switch switch (Branch) { // Nested case case "CSE": case "CCE": System.out.println( "elective courses : Machine Learning, Big Data"); break; // Case case "ECE": System.out.println( "elective courses : Antenna Engineering"); break; // default case // It will execute if above cases does not // execute default: // Print statement System.out.println( "Elective courses : Optimization"); } } }}
elective courses : Machine Learning, Big Data
Example:
Java
// Java Program to Illustrate Use of Enum// in Switch Statement // Classpublic class GFG { // Enum public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat } // Main driver method public static void main(String args[]) { // Enum Day[] DayNow = Day.values(); // Iterating using for each loop for (Day Now : DayNow) { // Switch case switch (Now) { // Case 1 case Sun: System.out.println("Sunday"); // break statement that hault further // execution once case is satisfied break; // Case 2 case Mon: System.out.println("Monday"); break; // Case 3 case Tue: System.out.println("Tuesday"); break; // Case 4 case Wed: System.out.println("Wednesday"); break; // Case 5 case Thu: System.out.println("Thursday"); break; // Case 6 case Fri: System.out.println("Friday"); break; // Case 7 case Sat: System.out.println("Saturday"); break; } } }}
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
harikesh409
Akanksha_Rai
vrk-19
sahilkansal09
nishkarshgandhi
solankimayank
java-basics
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Inheritance in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 506,
"s": 52,
"text": "The switch statement is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions. It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. It basically tests the equality of variables against multiple values."
},
{
"code": null,
"e": 724,
"s": 506,
"text": "Note: Java switch expression must be of byte, short, int, long(with its Wrapper type), enums and string. Beginning with JDK7, it also works with enumerated types (Enums in java), the String class, and Wrapper classes."
},
{
"code": null,
"e": 1399,
"s": 724,
"text": "There can be any number of cases just imposing condition check but remember duplicate case/s values are not allowed.The value for a case must be of the same data type as the variable in the switch.The value for a case must be constant or literal. Variables are not allowed.The break statement is used inside the switch to terminate a statement sequence.The break statement is optional. If omitted, execution will continue on into the next case.The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement."
},
{
"code": null,
"e": 1516,
"s": 1399,
"text": "There can be any number of cases just imposing condition check but remember duplicate case/s values are not allowed."
},
{
"code": null,
"e": 1598,
"s": 1516,
"text": "The value for a case must be of the same data type as the variable in the switch."
},
{
"code": null,
"e": 1675,
"s": 1598,
"text": "The value for a case must be constant or literal. Variables are not allowed."
},
{
"code": null,
"e": 1756,
"s": 1675,
"text": "The break statement is used inside the switch to terminate a statement sequence."
},
{
"code": null,
"e": 1848,
"s": 1756,
"text": "The break statement is optional. If omitted, execution will continue on into the next case."
},
{
"code": null,
"e": 2079,
"s": 1848,
"text": "The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement."
},
{
"code": null,
"e": 2100,
"s": 2079,
"text": "Syntax: Switch-case "
},
{
"code": null,
"e": 2564,
"s": 2100,
"text": "// switch statement \nswitch(expression)\n{\n // case statements\n // values must be of same type of expression\n case value1 :\n // Statements\n break; // break is optional\n \n case value2 :\n // Statements\n break; // break is optional\n \n // We can have any number of case statements\n // below is default statement, used when none of the cases is true. \n // No break is needed in the default case.\n default : \n // Statements\n}"
},
{
"code": null,
"e": 2755,
"s": 2564,
"text": "Note: Java switch statement is a fall through statement that means it executes all statements if break keyword is not used, so it is highly essential to use break keyword inside each case. "
},
{
"code": null,
"e": 2764,
"s": 2755,
"text": "Chapters"
},
{
"code": null,
"e": 2791,
"s": 2764,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 2841,
"s": 2791,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 2864,
"s": 2841,
"text": "captions off, selected"
},
{
"code": null,
"e": 2872,
"s": 2864,
"text": "English"
},
{
"code": null,
"e": 2896,
"s": 2872,
"text": "This is a modal window."
},
{
"code": null,
"e": 2965,
"s": 2896,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 2987,
"s": 2965,
"text": "End of dialog window."
},
{
"code": null,
"e": 3195,
"s": 2987,
"text": "Example: Consider the following java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of the day, using the switch statement."
},
{
"code": null,
"e": 3200,
"s": 3195,
"text": "Java"
},
{
"code": "// Java program to Demonstrate Switch Case// with Primitive(int) Data Type // Classpublic class GFG { // Main driver method public static void main(String[] args) { int day = 5; String dayString; // Switch statement with int data type switch (day) { // Case case 1: dayString = \"Monday\"; break; // Case case 2: dayString = \"Tuesday\"; break; // Case case 3: dayString = \"Wednesday\"; break; // Case case 4: dayString = \"Thursday\"; break; // Case case 5: dayString = \"Friday\"; break; // Case case 6: dayString = \"Saturday\"; break; // Case case 7: dayString = \"Sunday\"; break; // Default case default: dayString = \"Invalid day\"; } System.out.println(dayString); }}",
"e": 4229,
"s": 3200,
"text": null
},
{
"code": null,
"e": 4236,
"s": 4229,
"text": "Friday"
},
{
"code": null,
"e": 4558,
"s": 4236,
"text": "A break statement is optional. If we omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For instance, let us consider the updated version of the above program, it also displays whether a day is a weekday or a weekend day."
},
{
"code": null,
"e": 4567,
"s": 4558,
"text": "Example:"
},
{
"code": null,
"e": 4572,
"s": 4567,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Switch Case// with Multiple Cases Without Break Statements // Classpublic class GFG { // main driver method public static void main(String[] args) { int day = 2; String dayType; String dayString; // Switch case switch (day) { // Case case 1: dayString = \"Monday\"; break; // Case case 2: dayString = \"Tuesday\"; break; // Case case 3: dayString = \"Wednesday\"; break; case 4: dayString = \"Thursday\"; break; case 5: dayString = \"Friday\"; break; case 6: dayString = \"Saturday\"; break; case 7: dayString = \"Sunday\"; break; default: dayString = \"Invalid day\"; } switch (day) { // Multiple cases without break statements case 1: case 2: case 3: case 4: case 5: dayType = \"Weekday\"; break; case 6: case 7: dayType = \"Weekend\"; break; default: dayType = \"Invalid daytype\"; } System.out.println(dayString + \" is a \" + dayType); }}",
"e": 5885,
"s": 4572,
"text": null
},
{
"code": null,
"e": 5906,
"s": 5885,
"text": "Tuesday is a Weekday"
},
{
"code": null,
"e": 6157,
"s": 5906,
"text": "We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch."
},
{
"code": null,
"e": 6166,
"s": 6157,
"text": "Example:"
},
{
"code": null,
"e": 6171,
"s": 6166,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate// Nested Switch Case Statement // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String Branch = \"CSE\"; int year = 2; // Switch case switch (year) { // Case case 1: System.out.println( \"elective courses : Advance english, Algebra\"); // Break statement to hault execution here // itself if case is matched break; // Case case 2: // Switch inside a switch // Nested Switch switch (Branch) { // Nested case case \"CSE\": case \"CCE\": System.out.println( \"elective courses : Machine Learning, Big Data\"); break; // Case case \"ECE\": System.out.println( \"elective courses : Antenna Engineering\"); break; // default case // It will execute if above cases does not // execute default: // Print statement System.out.println( \"Elective courses : Optimization\"); } } }}",
"e": 7489,
"s": 6171,
"text": null
},
{
"code": null,
"e": 7535,
"s": 7489,
"text": "elective courses : Machine Learning, Big Data"
},
{
"code": null,
"e": 7544,
"s": 7535,
"text": "Example:"
},
{
"code": null,
"e": 7549,
"s": 7544,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Use of Enum// in Switch Statement // Classpublic class GFG { // Enum public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat } // Main driver method public static void main(String args[]) { // Enum Day[] DayNow = Day.values(); // Iterating using for each loop for (Day Now : DayNow) { // Switch case switch (Now) { // Case 1 case Sun: System.out.println(\"Sunday\"); // break statement that hault further // execution once case is satisfied break; // Case 2 case Mon: System.out.println(\"Monday\"); break; // Case 3 case Tue: System.out.println(\"Tuesday\"); break; // Case 4 case Wed: System.out.println(\"Wednesday\"); break; // Case 5 case Thu: System.out.println(\"Thursday\"); break; // Case 6 case Fri: System.out.println(\"Friday\"); break; // Case 7 case Sat: System.out.println(\"Saturday\"); break; } } }}",
"e": 8885,
"s": 7549,
"text": null
},
{
"code": null,
"e": 8942,
"s": 8885,
"text": "Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday"
},
{
"code": null,
"e": 9365,
"s": 8942,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9377,
"s": 9365,
"text": "harikesh409"
},
{
"code": null,
"e": 9390,
"s": 9377,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9397,
"s": 9390,
"text": "vrk-19"
},
{
"code": null,
"e": 9411,
"s": 9397,
"text": "sahilkansal09"
},
{
"code": null,
"e": 9427,
"s": 9411,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 9441,
"s": 9427,
"text": "solankimayank"
},
{
"code": null,
"e": 9453,
"s": 9441,
"text": "java-basics"
},
{
"code": null,
"e": 9458,
"s": 9453,
"text": "Java"
},
{
"code": null,
"e": 9477,
"s": 9458,
"text": "School Programming"
},
{
"code": null,
"e": 9482,
"s": 9477,
"text": "Java"
},
{
"code": null,
"e": 9580,
"s": 9482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9624,
"s": 9580,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9660,
"s": 9624,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 9685,
"s": 9660,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9736,
"s": 9685,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 9767,
"s": 9736,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 9785,
"s": 9767,
"text": "Python Dictionary"
},
{
"code": null,
"e": 9810,
"s": 9785,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9826,
"s": 9810,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 9849,
"s": 9826,
"text": "Introduction To PYTHON"
}
] |
Reverse an array in groups of given size | Set 3 (Single traversal) | 13 Aug, 2021
Given an array, reverse every sub-array formed by consecutive k elements.
Examples:
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3. Output: [3, 2, 1, 6, 5, 4, 9, 8, 7, 10]Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 5. Output: [5, 4, 3, 2, 1, 7, 6]
Approach:
We will use two pointers technique to solve this problem.First, we will initialize our 1st pointer d with value k-1 (d = k-1) and a variable m with value 2 (m = 2).Now, we will iterate the array with our 2nd pointer i and check If i < d, Swap (arr[i], arr[d]) and decrement d by 1. Otherwise,Make d = k * m – 1, i = k * (m – 1) – 1 and m = m + 1.
We will use two pointers technique to solve this problem.
First, we will initialize our 1st pointer d with value k-1 (d = k-1) and a variable m with value 2 (m = 2).
Now, we will iterate the array with our 2nd pointer i and check If i < d, Swap (arr[i], arr[d]) and decrement d by 1. Otherwise,Make d = k * m – 1, i = k * (m – 1) – 1 and m = m + 1.
If i < d, Swap (arr[i], arr[d]) and decrement d by 1. Otherwise,
Make d = k * m – 1, i = k * (m – 1) – 1 and m = m + 1.
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
Javascript
// C++ program to reverse every sub-array// formed by consecutive k elements#include<bits/stdc++.h>using namespace std; // Function to reverse every sub-array// formed by consecutive k elementsvoid ReverseInGroup(int arr[], int n, int k){ if(n < k) { k = n; } // Initialize variables int d = k - 1, m = 2; int i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); ReverseInGroup(arr, n, k); for(int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // This code is contributed by Code_Mech
// C program to reverse every sub-array// formed by consecutive k elements#include<stdio.h> // Function to reverse every sub-array// formed by consecutive k elementsvoid ReverseInGroup(int arr[], int n, int k){ if(n<k) { k=n; } // Initialize variables int d = k-1, m=2; int i = 0; for (i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d>=n) { d = n; } i = k * (m - 1)-1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return; } // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); ReverseInGroup(arr, n, k); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0;}
// Java program to reverse every sub-array// formed by consecutive k elementsclass GFG{ // Function to reverse every sub-array// formed by consecutive k elementsstatic void ReverseInGroup(int arr[], int n, int k){ if(n < k) { k = n; } // Initialize variables int d = k - 1, m = 2; int i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int k = 3; int n = arr.length; ReverseInGroup(arr, n, k); for(int i = 0; i < n; i++) System.out.printf("%d ", arr[i]);}} // This code is contributed by sapnasingh4991
# Python3 program to reverse# every sub-array formed by# consecutive k elements # Function to reverse every# sub-array formed by consecutive# k elementsdef ReverseInGroup(arr, n, k): if(n < k): k = n # Initialize variables d = k - 1 m = 2 i = 0 while i < n: if (i >= d): # Update the # variables d = k * (m) if(d >= n): d = n i = k * (m - 1) - 1 m += 1 else: arr[i], arr[d] = (arr[d], arr[i]) d = d - 1 i += 1 return # Driver codeif __name__ == "__main__": arr = [1, 2, 3, 4, 5, 6, 7] k = 3 n = len(arr) ReverseInGroup(arr, n, k) for i in range(n): print(arr[i], end = " ") # This code is contributed by Chitranayal
// C# program to reverse every sub-array// formed by consecutive k elementsusing System;class GFG{ // Function to reverse every sub-array// formed by consecutive k elementsstatic void ReverseInGroup(int []arr, int n, int k){ if(n < k) { k = n; } // Initialize variables int d = k - 1, m = 2; int i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver codepublic static void Main(){ int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int k = 3; int n = arr.Length; ReverseInGroup(arr, n, k); for(int i = 0; i < n; i++) Console.Write(arr[i] + " ");}} // This code is contributed by Code_Mech
<script>// Javascript program to reverse every sub-array// formed by consecutive k elements // Function to reverse every sub-array// formed by consecutive k elementsfunction ReverseInGroup(arr, n, k){ if(n < k) { k = n; } // Initialize variables let d = k - 1, m = 2; let i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { let t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver code let arr = [ 1, 2, 3, 4, 5, 6, 7 ]; let k = 3; let n = arr.length; ReverseInGroup(arr, n, k); for(let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by _saurabh_jaiswal</script>
3 2 1 6 5 4 7
Time Complexity: O(N) Auxiliary Space: O(1)
sapnasingh4991
Code_Mech
ukasp
_saurabh_jaiswal
pankajsharmagfg
Arrays
Data Structures
Data Structures
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 127,
"s": 53,
"text": "Given an array, reverse every sub-array formed by consecutive k elements."
},
{
"code": null,
"e": 138,
"s": 127,
"text": "Examples: "
},
{
"code": null,
"e": 303,
"s": 138,
"text": "Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3. Output: [3, 2, 1, 6, 5, 4, 9, 8, 7, 10]Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 5. Output: [5, 4, 3, 2, 1, 7, 6]"
},
{
"code": null,
"e": 314,
"s": 303,
"text": "Approach: "
},
{
"code": null,
"e": 661,
"s": 314,
"text": "We will use two pointers technique to solve this problem.First, we will initialize our 1st pointer d with value k-1 (d = k-1) and a variable m with value 2 (m = 2).Now, we will iterate the array with our 2nd pointer i and check If i < d, Swap (arr[i], arr[d]) and decrement d by 1. Otherwise,Make d = k * m – 1, i = k * (m – 1) – 1 and m = m + 1."
},
{
"code": null,
"e": 719,
"s": 661,
"text": "We will use two pointers technique to solve this problem."
},
{
"code": null,
"e": 827,
"s": 719,
"text": "First, we will initialize our 1st pointer d with value k-1 (d = k-1) and a variable m with value 2 (m = 2)."
},
{
"code": null,
"e": 1010,
"s": 827,
"text": "Now, we will iterate the array with our 2nd pointer i and check If i < d, Swap (arr[i], arr[d]) and decrement d by 1. Otherwise,Make d = k * m – 1, i = k * (m – 1) – 1 and m = m + 1."
},
{
"code": null,
"e": 1075,
"s": 1010,
"text": "If i < d, Swap (arr[i], arr[d]) and decrement d by 1. Otherwise,"
},
{
"code": null,
"e": 1130,
"s": 1075,
"text": "Make d = k * m – 1, i = k * (m – 1) – 1 and m = m + 1."
},
{
"code": null,
"e": 1182,
"s": 1130,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 1186,
"s": 1182,
"text": "C++"
},
{
"code": null,
"e": 1188,
"s": 1186,
"text": "C"
},
{
"code": null,
"e": 1193,
"s": 1188,
"text": "Java"
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Python3"
},
{
"code": null,
"e": 1204,
"s": 1201,
"text": "C#"
},
{
"code": null,
"e": 1215,
"s": 1204,
"text": "Javascript"
},
{
"code": "// C++ program to reverse every sub-array// formed by consecutive k elements#include<bits/stdc++.h>using namespace std; // Function to reverse every sub-array// formed by consecutive k elementsvoid ReverseInGroup(int arr[], int n, int k){ if(n < k) { k = n; } // Initialize variables int d = k - 1, m = 2; int i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); ReverseInGroup(arr, n, k); for(int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;} // This code is contributed by Code_Mech",
"e": 2225,
"s": 1215,
"text": null
},
{
"code": "// C program to reverse every sub-array// formed by consecutive k elements#include<stdio.h> // Function to reverse every sub-array// formed by consecutive k elementsvoid ReverseInGroup(int arr[], int n, int k){ if(n<k) { k=n; } // Initialize variables int d = k-1, m=2; int i = 0; for (i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d>=n) { d = n; } i = k * (m - 1)-1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return; } // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); ReverseInGroup(arr, n, k); for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;}",
"e": 3218,
"s": 2225,
"text": null
},
{
"code": "// Java program to reverse every sub-array// formed by consecutive k elementsclass GFG{ // Function to reverse every sub-array// formed by consecutive k elementsstatic void ReverseInGroup(int arr[], int n, int k){ if(n < k) { k = n; } // Initialize variables int d = k - 1, m = 2; int i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int k = 3; int n = arr.length; ReverseInGroup(arr, n, k); for(int i = 0; i < n; i++) System.out.printf(\"%d \", arr[i]);}} // This code is contributed by sapnasingh4991",
"e": 4270,
"s": 3218,
"text": null
},
{
"code": "# Python3 program to reverse# every sub-array formed by# consecutive k elements # Function to reverse every# sub-array formed by consecutive# k elementsdef ReverseInGroup(arr, n, k): if(n < k): k = n # Initialize variables d = k - 1 m = 2 i = 0 while i < n: if (i >= d): # Update the # variables d = k * (m) if(d >= n): d = n i = k * (m - 1) - 1 m += 1 else: arr[i], arr[d] = (arr[d], arr[i]) d = d - 1 i += 1 return # Driver codeif __name__ == \"__main__\": arr = [1, 2, 3, 4, 5, 6, 7] k = 3 n = len(arr) ReverseInGroup(arr, n, k) for i in range(n): print(arr[i], end = \" \") # This code is contributed by Chitranayal",
"e": 5130,
"s": 4270,
"text": null
},
{
"code": "// C# program to reverse every sub-array// formed by consecutive k elementsusing System;class GFG{ // Function to reverse every sub-array// formed by consecutive k elementsstatic void ReverseInGroup(int []arr, int n, int k){ if(n < k) { k = n; } // Initialize variables int d = k - 1, m = 2; int i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { int t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver codepublic static void Main(){ int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int k = 3; int n = arr.Length; ReverseInGroup(arr, n, k); for(int i = 0; i < n; i++) Console.Write(arr[i] + \" \");}} // This code is contributed by Code_Mech",
"e": 6194,
"s": 5130,
"text": null
},
{
"code": "<script>// Javascript program to reverse every sub-array// formed by consecutive k elements // Function to reverse every sub-array// formed by consecutive k elementsfunction ReverseInGroup(arr, n, k){ if(n < k) { k = n; } // Initialize variables let d = k - 1, m = 2; let i = 0; for(i = 0; i < n; i++) { if (i >= d) { // Update the variables d = k * (m); if(d >= n) { d = n; } i = k * (m - 1) - 1; m++; } else { let t = arr[i]; arr[i] = arr[d]; arr[d] = t; } d = d - 1; } return;} // Driver code let arr = [ 1, 2, 3, 4, 5, 6, 7 ]; let k = 3; let n = arr.length; ReverseInGroup(arr, n, k); for(let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by _saurabh_jaiswal</script>",
"e": 7158,
"s": 6194,
"text": null
},
{
"code": null,
"e": 7172,
"s": 7158,
"text": "3 2 1 6 5 4 7"
},
{
"code": null,
"e": 7219,
"s": 7174,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 7234,
"s": 7219,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Code_Mech"
},
{
"code": null,
"e": 7250,
"s": 7244,
"text": "ukasp"
},
{
"code": null,
"e": 7267,
"s": 7250,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 7283,
"s": 7267,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 7290,
"s": 7283,
"text": "Arrays"
},
{
"code": null,
"e": 7306,
"s": 7290,
"text": "Data Structures"
},
{
"code": null,
"e": 7322,
"s": 7306,
"text": "Data Structures"
},
{
"code": null,
"e": 7329,
"s": 7322,
"text": "Arrays"
},
{
"code": null,
"e": 7427,
"s": 7329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7459,
"s": 7427,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7506,
"s": 7459,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7531,
"s": 7506,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7562,
"s": 7531,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7620,
"s": 7562,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 7645,
"s": 7620,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 7694,
"s": 7645,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 7732,
"s": 7694,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 7764,
"s": 7732,
"text": "Introduction to Data Structures"
}
] |
Haskell - Modules | If you have worked on Java, then you would know how all the classes are bound into a folder called package. Similarly, Haskell can be considered as a collection of modules.
Haskell is a functional language and everything is denoted as an expression, hence a Module can be called as a collection of similar or related types of functions.
You can import a function from one module into another module. All the "import" statements should come first before you start defining other functions. In this chapter, we will learn the different features of Haskell modules.
List provides some wonderful functions to work with list type data. Once you import the List module, you have a wide range of functions at your disposal.
In the following example, we have used some important functions available under the List module.
import Data.List
main = do
putStrLn("Different methods of List Module")
print(intersperse '.' "Tutorialspoint.com")
print(intercalate " " ["Lets","Start","with","Haskell"])
print(splitAt 7 "HaskellTutorial")
print (sort [8,5,3,2,1,6,4,2])
Here, we have many functions without even defining them. That is because these functions are available in the List module. After importing the List module, the Haskell compiler made all these functions available in the global namespace. Hence, we could use these functions.
Our code will yield the following output −
Different methods of List Module
"T.u.t.o.r.i.a.l.s.p.o.i.n.t...c.o.m"
"Lets Start with Haskell"
("Haskell","Tutorial")
[1,2,2,3,4,5,6,8]
The Char module has plenty of predefined functions to work with the Character type. Take a look at the following code block −
import Data.Char
main = do
putStrLn("Different methods of Char Module")
print(toUpper 'a')
print(words "Let us study tonight")
print(toLower 'A')
Here, the functions toUpper and toLower are already defined inside the Char module. It will produce the following output −
Different methods of Char Module
'A'
["Let","us","study","tonight"]
'a'
Map is an unsorted value-added pair type data type. It is a widely used module with many useful functions. The following example shows how you can use a predefined function available in the Map module.
import Data.Map (Map)
import qualified Data.Map as Map --required for GHCI
myMap :: Integer -> Map Integer [Integer]
myMap n = Map.fromList (map makePair [1..n])
where makePair x = (x, [x])
main = print(myMap 3)
It will produce the following output −
fromList [(1,[1]),(2,[2]),(3,[3])]
The Set module has some very useful predefined functions to manipulate mathematical data. A set is implemented as a binary tree, so all the elements in a set must be unique.
Take a look at the following example code
import qualified Data.Set as Set
text1 = "Hey buddy"
text2 = "This tutorial is for Haskell"
main = do
let set1 = Set.fromList text1
set2 = Set.fromList text2
print(set1)
print(set2)
Here, we are modifying a String into a Set. It will produce the following output. Observe that the output set has no repetition of characters.
fromList " Hbdeuy"
fromList " HTaefhiklorstu"
Let’s see how we can create a custom module that can be called at other programs. To implement this custom module, we will create a separate file called "custom.hs" along with our "main.hs".
Let us create the custom module and define a few functions in it.
module Custom (
showEven,
showBoolean
) where
showEven:: Int-> Bool
showEven x = do
if x 'rem' 2 == 0
then True
else False
showBoolean :: Bool->Int
showBoolean c = do
if c == True
then 1
else 0
Our Custom module is ready. Now, let us import it into a program.
import Custom
main = do
print(showEven 4)
print(showBoolean True)
Our code will generate the following output −
True
1
The showEven function returns True, as "4" is an even number. The showBoolean function returns "1" as the Boolean function that we passed into the function is "True". | [
{
"code": null,
"e": 2222,
"s": 2049,
"text": "If you have worked on Java, then you would know how all the classes are bound into a folder called package. Similarly, Haskell can be considered as a collection of modules."
},
{
"code": null,
"e": 2386,
"s": 2222,
"text": "Haskell is a functional language and everything is denoted as an expression, hence a Module can be called as a collection of similar or related types of functions."
},
{
"code": null,
"e": 2612,
"s": 2386,
"text": "You can import a function from one module into another module. All the \"import\" statements should come first before you start defining other functions. In this chapter, we will learn the different features of Haskell modules."
},
{
"code": null,
"e": 2766,
"s": 2612,
"text": "List provides some wonderful functions to work with list type data. Once you import the List module, you have a wide range of functions at your disposal."
},
{
"code": null,
"e": 2863,
"s": 2766,
"text": "In the following example, we have used some important functions available under the List module."
},
{
"code": null,
"e": 3126,
"s": 2863,
"text": "import Data.List \n\nmain = do \n putStrLn(\"Different methods of List Module\") \n print(intersperse '.' \"Tutorialspoint.com\") \n print(intercalate \" \" [\"Lets\",\"Start\",\"with\",\"Haskell\"]) \n print(splitAt 7 \"HaskellTutorial\") \n print (sort [8,5,3,2,1,6,4,2])"
},
{
"code": null,
"e": 3400,
"s": 3126,
"text": "Here, we have many functions without even defining them. That is because these functions are available in the List module. After importing the List module, the Haskell compiler made all these functions available in the global namespace. Hence, we could use these functions."
},
{
"code": null,
"e": 3443,
"s": 3400,
"text": "Our code will yield the following output −"
},
{
"code": null,
"e": 3582,
"s": 3443,
"text": "Different methods of List Module\n\"T.u.t.o.r.i.a.l.s.p.o.i.n.t...c.o.m\"\n\"Lets Start with Haskell\"\n(\"Haskell\",\"Tutorial\")\n[1,2,2,3,4,5,6,8]\n"
},
{
"code": null,
"e": 3708,
"s": 3582,
"text": "The Char module has plenty of predefined functions to work with the Character type. Take a look at the following code block −"
},
{
"code": null,
"e": 3873,
"s": 3708,
"text": "import Data.Char \n\nmain = do \n putStrLn(\"Different methods of Char Module\") \n print(toUpper 'a') \n print(words \"Let us study tonight\") \n print(toLower 'A')"
},
{
"code": null,
"e": 3996,
"s": 3873,
"text": "Here, the functions toUpper and toLower are already defined inside the Char module. It will produce the following output −"
},
{
"code": null,
"e": 4069,
"s": 3996,
"text": "Different methods of Char Module\n'A'\n[\"Let\",\"us\",\"study\",\"tonight\"]\n'a'\n"
},
{
"code": null,
"e": 4271,
"s": 4069,
"text": "Map is an unsorted value-added pair type data type. It is a widely used module with many useful functions. The following example shows how you can use a predefined function available in the Map module."
},
{
"code": null,
"e": 4496,
"s": 4271,
"text": "import Data.Map (Map) \nimport qualified Data.Map as Map --required for GHCI \n\nmyMap :: Integer -> Map Integer [Integer] \nmyMap n = Map.fromList (map makePair [1..n]) \n where makePair x = (x, [x]) \n\nmain = print(myMap 3)"
},
{
"code": null,
"e": 4535,
"s": 4496,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4572,
"s": 4535,
"text": "fromList [(1,[1]),(2,[2]),(3,[3])] \n"
},
{
"code": null,
"e": 4746,
"s": 4572,
"text": "The Set module has some very useful predefined functions to manipulate mathematical data. A set is implemented as a binary tree, so all the elements in a set must be unique."
},
{
"code": null,
"e": 4788,
"s": 4746,
"text": "Take a look at the following example code"
},
{
"code": null,
"e": 5008,
"s": 4788,
"text": "import qualified Data.Set as Set \n\ntext1 = \"Hey buddy\" \ntext2 = \"This tutorial is for Haskell\" \n\nmain = do \n let set1 = Set.fromList text1 \n set2 = Set.fromList text2 \n print(set1) \n print(set2) "
},
{
"code": null,
"e": 5151,
"s": 5008,
"text": "Here, we are modifying a String into a Set. It will produce the following output. Observe that the output set has no repetition of characters."
},
{
"code": null,
"e": 5198,
"s": 5151,
"text": "fromList \" Hbdeuy\"\nfromList \" HTaefhiklorstu\"\n"
},
{
"code": null,
"e": 5389,
"s": 5198,
"text": "Let’s see how we can create a custom module that can be called at other programs. To implement this custom module, we will create a separate file called \"custom.hs\" along with our \"main.hs\"."
},
{
"code": null,
"e": 5455,
"s": 5389,
"text": "Let us create the custom module and define a few functions in it."
},
{
"code": null,
"e": 5678,
"s": 5455,
"text": "module Custom ( \n showEven, \n showBoolean \n) where \n\nshowEven:: Int-> Bool \nshowEven x = do \n\nif x 'rem' 2 == 0 \n then True \nelse False \nshowBoolean :: Bool->Int \nshowBoolean c = do \n\nif c == True \n then 1 \nelse 0 "
},
{
"code": null,
"e": 5744,
"s": 5678,
"text": "Our Custom module is ready. Now, let us import it into a program."
},
{
"code": null,
"e": 5821,
"s": 5744,
"text": "import Custom \n\nmain = do \n print(showEven 4) \n print(showBoolean True) "
},
{
"code": null,
"e": 5867,
"s": 5821,
"text": "Our code will generate the following output −"
},
{
"code": null,
"e": 5875,
"s": 5867,
"text": "True\n1\n"
}
] |
Python modf() Method | Python number method modf() returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.
Following is the syntax for modf() method −
import math
math.modf( x )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This is a numeric expression.
x − This is a numeric expression.
This method returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.
The following example shows the usage of modf() method.
#!/usr/bin/python
import math # This will import math module
print "math.modf(100.12) : ", math.modf(100.12)
print "math.modf(100.72) : ", math.modf(100.72)
print "math.modf(119L) : ", math.modf(119L)
print "math.modf(math.pi) : ", math.modf(math.pi)
When we run above program, it produces following result −
math.modf(100.12) : (0.12000000000000455, 100.0)
math.modf(100.72) : (0.71999999999999886, 100.0)
math.modf(119L) : (0.0, 119.0)
math.modf(math.pi) : (0.14159265358979312, 3.0)
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": 2417,
"s": 2244,
"text": "Python number method modf() returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float."
},
{
"code": null,
"e": 2461,
"s": 2417,
"text": "Following is the syntax for modf() method −"
},
{
"code": null,
"e": 2489,
"s": 2461,
"text": "import math\n\nmath.modf( x )"
},
{
"code": null,
"e": 2636,
"s": 2489,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2670,
"s": 2636,
"text": "x − This is a numeric expression."
},
{
"code": null,
"e": 2704,
"s": 2670,
"text": "x − This is a numeric expression."
},
{
"code": null,
"e": 2860,
"s": 2704,
"text": "This method returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float."
},
{
"code": null,
"e": 2916,
"s": 2860,
"text": "The following example shows the usage of modf() method."
},
{
"code": null,
"e": 3170,
"s": 2916,
"text": "#!/usr/bin/python\nimport math # This will import math module\n\nprint \"math.modf(100.12) : \", math.modf(100.12)\nprint \"math.modf(100.72) : \", math.modf(100.72)\nprint \"math.modf(119L) : \", math.modf(119L)\nprint \"math.modf(math.pi) : \", math.modf(math.pi)"
},
{
"code": null,
"e": 3228,
"s": 3170,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3412,
"s": 3228,
"text": "math.modf(100.12) : (0.12000000000000455, 100.0)\nmath.modf(100.72) : (0.71999999999999886, 100.0)\nmath.modf(119L) : (0.0, 119.0)\nmath.modf(math.pi) : (0.14159265358979312, 3.0)\n"
},
{
"code": null,
"e": 3449,
"s": 3412,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3465,
"s": 3449,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3498,
"s": 3465,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3517,
"s": 3498,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3552,
"s": 3517,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3574,
"s": 3552,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3608,
"s": 3574,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3636,
"s": 3608,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3671,
"s": 3636,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3685,
"s": 3671,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3718,
"s": 3685,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3735,
"s": 3718,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3742,
"s": 3735,
"text": " Print"
},
{
"code": null,
"e": 3753,
"s": 3742,
"text": " Add Notes"
}
] |
C Program to calculate the Round Trip Time (RTT) | Given an Url address of any website; the task is to calculate the round trip time of a website.
Round Trip Time(RTT) is the total time or the length of a time which is taken to send a signal plus the time taken to receive the acknowledgement of that signal to be received. This time also consist of the propagation times between two points of a signal.
An end user can determine his/her round trip time from an IP address by pinging that address.
The Round Trip time’ result depends upon the following reasons −
The Transmission medium.
The presence of Interface in the circuit.
Number of nodes from the source to the destination.
Amount of traffic.
Physical Distance from the source to the destination.
Nature of the transmission medium(wireless, fiber optic, etc.).
Number of requests.
Presence of interface in the circuit.
Generally the duration of Round Trip Time will be in milliseconds and we displaying output in Seconds.
Input: www.tutorialspoint.com
Output: Time taken:0.3676435947418213
Input: www.indiatoday.in
Output: Time taken:0.4621298224721691
Approach we will be using to solve the given problem −
Take the input string of the URL whose RTT(Round Trip Time) we want to calculate.
Record the time before requesting the URL and store it into a variable.
Send the request.
Record the time after receiving acknowledgement.
Compare both the times we will get the RTT.
Start
Step 1 -> import time
Step 2 -> import requests
Step 3 -> define a function def roundtriptime(url):
Set t1 = time.time()
Set req = requests.get(url)
Set t2 = time.time()
Set t = str(t2-t1)
Print Time taken
Step 4 -> Initialize url = "http://www.tutorialspoint.com"
Step 5 -> Call function roundtriptime(url)
Stop
import time
import requests
# Function to calculate the roundtriptime
def roundtriptime(url):
# time when the signal is sent
t1 = time.time()
req = requests.get(url)
# time when the acknowledgement
# is received
t2 = time.time()
# total time taken
t = str(t2-t1)
print("Time taken:" + t)
# url address
url = "http://www.tutorialspoint.com"
roundtriptime(url)
Time taken:0.3676435947418213 | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "Given an Url address of any website; the task is to calculate the round trip time of a website."
},
{
"code": null,
"e": 1415,
"s": 1158,
"text": "Round Trip Time(RTT) is the total time or the length of a time which is taken to send a signal plus the time taken to receive the acknowledgement of that signal to be received. This time also consist of the propagation times between two points of a signal."
},
{
"code": null,
"e": 1509,
"s": 1415,
"text": "An end user can determine his/her round trip time from an IP address by pinging that address."
},
{
"code": null,
"e": 1574,
"s": 1509,
"text": "The Round Trip time’ result depends upon the following reasons −"
},
{
"code": null,
"e": 1599,
"s": 1574,
"text": "The Transmission medium."
},
{
"code": null,
"e": 1641,
"s": 1599,
"text": "The presence of Interface in the circuit."
},
{
"code": null,
"e": 1693,
"s": 1641,
"text": "Number of nodes from the source to the destination."
},
{
"code": null,
"e": 1712,
"s": 1693,
"text": "Amount of traffic."
},
{
"code": null,
"e": 1766,
"s": 1712,
"text": "Physical Distance from the source to the destination."
},
{
"code": null,
"e": 1830,
"s": 1766,
"text": "Nature of the transmission medium(wireless, fiber optic, etc.)."
},
{
"code": null,
"e": 1850,
"s": 1830,
"text": "Number of requests."
},
{
"code": null,
"e": 1888,
"s": 1850,
"text": "Presence of interface in the circuit."
},
{
"code": null,
"e": 1991,
"s": 1888,
"text": "Generally the duration of Round Trip Time will be in milliseconds and we displaying output in Seconds."
},
{
"code": null,
"e": 2122,
"s": 1991,
"text": "Input: www.tutorialspoint.com\nOutput: Time taken:0.3676435947418213\nInput: www.indiatoday.in\nOutput: Time taken:0.4621298224721691"
},
{
"code": null,
"e": 2177,
"s": 2122,
"text": "Approach we will be using to solve the given problem −"
},
{
"code": null,
"e": 2259,
"s": 2177,
"text": "Take the input string of the URL whose RTT(Round Trip Time) we want to calculate."
},
{
"code": null,
"e": 2331,
"s": 2259,
"text": "Record the time before requesting the URL and store it into a variable."
},
{
"code": null,
"e": 2349,
"s": 2331,
"text": "Send the request."
},
{
"code": null,
"e": 2398,
"s": 2349,
"text": "Record the time after receiving acknowledgement."
},
{
"code": null,
"e": 2442,
"s": 2398,
"text": "Compare both the times we will get the RTT."
},
{
"code": null,
"e": 2806,
"s": 2442,
"text": "Start\n Step 1 -> import time\n Step 2 -> import requests\n Step 3 -> define a function def roundtriptime(url):\n Set t1 = time.time()\n Set req = requests.get(url)\n Set t2 = time.time()\n Set t = str(t2-t1)\n Print Time taken\n Step 4 -> Initialize url = \"http://www.tutorialspoint.com\"\n Step 5 -> Call function roundtriptime(url)\nStop"
},
{
"code": null,
"e": 3222,
"s": 2806,
"text": "import time\nimport requests\n# Function to calculate the roundtriptime\ndef roundtriptime(url):\n # time when the signal is sent\n t1 = time.time()\n req = requests.get(url)\n # time when the acknowledgement\n # is received\n t2 = time.time()\n # total time taken\n t = str(t2-t1)\n print(\"Time taken:\" + t)\n # url address\n url = \"http://www.tutorialspoint.com\"\n roundtriptime(url)"
},
{
"code": null,
"e": 3252,
"s": 3222,
"text": "Time taken:0.3676435947418213"
}
] |
Ultimate Beginners Guide to Collecting Text for Natural Language Processing (NLP) with Python — Twitter, Reddit, Genius and More | by Eric Kleppen | Towards Data Science | I’ve been fascinated by Natural Language Processing (NLP) since I got into data science a little over a year ago. Thanks to advancements in transfer learning, there has been some explosive progress in the field, and NLP products like Alexa and Siri have become household names. Since my background is technical writing and rhetorical theory, I was immediately drawn to projects involving text like sentiment analysis and topic extraction because I wanted to develop an understanding of how machine learning can provide insight into written language. One of my first data science projects was using Google’s Universal Sentence Encoder to produce wine recommendations.
I always wanted a guide like this one, breaking down how to extract data from popular social media platforms. With increasing accessibility to powerful pre-trained language models like BERT and ELMo, it is important to understand where to find and extract data. Luckily, social media is an abundant resource for collecting NLP data sets, and is easily accessible with a few lines of Python. At the end of the article, I also include a list of popular Kaggle NLP datasets, and link to Google Dataset Search, the new search engine.
This article teaches you how to extract data from Twitter, Reddit, and Genius. I assume you already know some Python libraries Pandas and SQLite.
Before getting into the code, it is important to stress the value of an API Key. If you’re new to managing API keys, make sure to save them into a config.py file instead of hard-coding them in your app. Make sure not to include them in any code share online. API keys can be very valuable, and sometimes very expensive and must be protected. If you’re worried your key has been leaked, most providers allow you to regenerate them.
Add the config file to your gitignore file to prevent it from being pushed to your repo too!
Twitter provides a plethora of data that is easy to access through their API. With the Tweepy Python library, easily pull a constant stream of tweets based on the desired topics. Twitter is great for mining trends and sentiment,
For this tutorial, you will need to register an app with Twitter to get API Keys. Check out the official Twitter documentation if you’re not familiar with their developer portal!
Use pip to install Tweepy and unidecode.
pip install tweepypip install unidecode
Save the following keys to a config file:
Connecting Tweepy to Twitter uses OAuth1. If you’re brand new to API authentication, check out the official Tweepy Authentication Tutorial.
To save the data from the incoming stream, I find it easiest to save it to an SQLite database. If you’re not familiar with SQL tables or need a refresher, check this free site for examples or check out my SQL tutorial.
The function unidecode() takes Unicode data and tries to represent it in ASCII characters.
#import dependenciesimport tweepyfrom tweepy import OAuthHandlerfrom tweepy.streaming import StreamListenerimport jsonfrom unidecode import unidecodeimport timeimport datetime#import the API keys from the config file.from config import con_key, con_sec, a_token, a_secret sqlite3conn = sqlite3.connect("twitterStream.sqlite")c = conn.cursor()
I need to create the table to store the wine data. I use SQLite because it is lightweight and server-less. Plus I like keeping all the data in once place!
def create_table(): c.execute("CREATE TABLE IF NOT EXISTS Tweets(timestamp REAL, tweet TEXT)") conn.commit()create_table()
Notice I use IF NOT EXISTS to make sure the table doesn’t already exist in the database. Remember to commit the transaction using the conn.commit() call.
Here is some boilerplate code to pull the tweet and a timestamp from the streamed twitter data and insert it into the database.
class Listener(StreamListener): def on_data(self, data): try: data = json.loads(data) tweet = unidecode(data['text']) time_ms = data['timestamp_ms'] #print(tweet, time_ms) c.execute("INSERT INTO Tweets (timestamp, tweet) VALUES (?, ?)", (time_ms, tweet)) conn.commit() time.sleep(2) except KeyError as e: print(str(e)) return(True) def on_error(self, status_code): if status_code == 420: #returning False in on_error disconnects the stream return Falsewhile True: try: auth = OAuthHandler(con_key, con_sec) auth.set_access_token(a_token, a_secret) twitterStream = tweepy.Stream(auth, Listener()) twitterStream.filter(track=['DataScience']) except Exception as e: print(str(e)) time.sleep(4)
Notice I slow the stream using time.sleep().Notice the code is wrapped in a try/except to prevent potential hiccups from disrupting the stream. Additionally, the documentation recommends using an on_error() function to act as a circuit-breaker if the app is making too many requests.Notice I wrap the stream object in a while condition. That way, it stops if it hits the 420 error.Notice the twitterstream.filter uses track to find keywords in tweets. If you want to follow a specific user’s tweets, use .filter(follow=[“”]).
Extract the data from the SQLite database
sql = '''select tweet from Tweets where tweet not like 'RT %' order by timestamp desc'''tweet_df = pd.read_sql(sql, conn)tweet_df
Like Twitter, the social network Reddit contains a jaw dropping amount of information that is easy to scrape. It is a social network that works like an internet forum allowing users to post about whatever topic they want. Users form communities called subreddits, and they up-vote or down-vote posts in their communities to decide what gets viewed first and what sinks to the bottom.
I’ll explain how to get a Reddit API key and how to extract data from Reddit using the PRAW library. Although Reddit has an API, the Python Reddit API Wrapper, or PRAW for short, offers a simplified experience. PRAW supports Python 3.5+
A user account to Reddit is required to use the API. It is completely free and only requires an email address!
https://www.reddit.com
If there is a way to get here using the new Reddit UI, leave me a comment! If it is your first time, follow these steps to get an API key after signing into Reddit. If you already have a key, use this link to go to your apps page.
Click the User Account droplist. User options display.
Click Visit Old Reddit from the user options. The page will change and the URL will become https://old.reddit.com/
Click the preferences link next to the logout button.Click the apps tab on the PREFERENCES screen.Click the are you a developer? create am app... button.
Enter a name.Select the type of app.Enter a Description.Use http://localhost:8080 as the redirect uri.Click create app after populating the fields.
The API information required to connect will display. I’ll walk through connecting to the API using PRAW when I get into code.
Congratulations on getting set up to scrape Reddit data!
The recommended way to install PRAW is to use pip. The install the following packages to create the dashboard.
pip install praw
Start by importing the libraries and the config file:
import prawimport pandas as pd from config import cid, csec, ua
Create a read-only Reddit instance. That means I don’t need to enter Reddit credentials used to post responses or create new threads; the connection only reads data.
PRAW uses OAuth authentication to connect to the Reddit API.
#create a reddit connectionreddit = praw.Reddit(client_id= cid, client_secret= csec, user_agent= ua)
Here is a list of examples I think would be fun to explore:
news, datascience, learnmachinelearning, gaming, funny, politics
Use the Subreddit class in PRAW to retrieve the data from the desired subreddit. It is possible to order the data based on the follow Reddit options:
hot — order by the posts getting the most traffic
new — order by the newest posts in the thread
top — order by the most up-voted posts
rising — order by the posts gaining popularity
If you want to include multiple subreddits, use a + symbol:
#single subreddit new 5subreddit = reddit.subreddit('news').new(limit = 5)#multiple subreddits top 5subreddit = reddit.subreddit('news' + 'datascience').top(limit = 5)
This returns an object that holds the data in an attribute. The attribute is like a key in a dictionary.
The data is linked to an attributed owned by the object. If the attribute is the Key, the data is the Value. The attributes are dynamically generated, so it is best to check what is available using Python’s built-in vars() function.
Use this boilerplate code to see all the attributes owned by object representing the reddit post. It is a LONG list!
subreddit = reddit.subreddit('news').new(limit = 1)for post in subreddit: pprint.pprint(vars(post))
Notice in the list the attributes of interest:
title — Returns post title.score — Returns number of up-votes or down-votes.num_comments — Returns the number of comments on the thread.selftext — Returns the body of the post.created — Returns a timestamp for the post.pinned — Indicates whether the thread was pinned.total_awards_received — Returns number of awards received by the post.
Now that the attributes have been identified, load them data into a pandas DataFrame or save them to an SQLite database like in the Twitter example. In this example, I’ll save it to a pandas DataFrame.
#list for df conversionposts = []#return 100 new posts from wallstreetbetsnew_bets = reddit.subreddit('wallstreetbets').new(limit=100)#return the important attributesfor post in new_bets: posts.append([post.title, post.score, post.num_comments, post.selftext, post.created, post.pinned, post.total_awards_received])#create a dataframeposts = pd.DataFrame(posts,columns=['title', 'score', 'comments', 'post', 'created', 'pinned', 'total awards'])#return top 3 df rowsposts.head(3)
I have always been a fan of music, particularly heavy metal. In heavy metal, the lyrics can sometimes be quite difficult to understand, so I go to Genius to decipher them. The website Genius.com is a platform for annotating lyrics, and collecting trivia about music, albums and artists. Genius allows users to register an API Client.
https://genius.com/api-clients
Either Sign up or Sign in. Click the Developers link.Click Create an API Client.Enter an App Name.Enter a website URL if you have one, otherwise http://127.0.0.1 will work.Click Save. The API Client will display.Click Generate Access Token to generate an access token.
Surprisingly, due to legal reasons, the Genius API does not provide a way to download song lyrics. It is possible to search lyrics, but not download them. Lucky for everyone, Medium author Ben Wallace has provided us with a convenient wrapper for scraping the lyrics. Find his original code on GitHub too:
github.com
I have modified his wrapper to make it easier to download an artist’s complete works rather than code the albums I want to include, and I added an Artist column to store the artist name.
The wrapper uses the API to get the URLs linking to the lyrics. From there, BeautifulSoup is used to parse the HTML for each URL. The process results in a dataframe that contains the Title, URL, Artist, Album and Lyrics:
The wrapper is a class named GeniusArtistDataCollect(). Use it to connect to the API and retrieve song lyrics for a specified artist. In the example, I use one of my favorite metal bands, The Black Dahlia Murder.
To use GeniusArtistDataCollect(), instantiate it, passing in the Client Access Token and the Artist name.
g = GeniusArtistDataCollect(token, 'The Black Dahlia Murder')
Call get_artists_songs() from the GeniusArtistDataCollect object. This will return as a pandas DataFrame.
songs_df = g.get_artist_songs()
Here is the modified wrapper I use in the example:
import osimport reimport requestsimport pandas as pdimport urllib.requestfrom bs4 import BeautifulSoupfrom config import tokenclass GeniusArtistDataCollect: """A wrapper class that is able to retrieve, clean, and organize all the album songs of a given artist Uses the Genius API and webscraping techniques to get the data."""def __init__(self, client_access_token, artist_name): """ Instantiate a GeniusArtistDataCollect object :param client_access_token: str - Token to access the Genius API. Create one at https://genius.com/developers :param artist_name: str - The name of the artist of interest THIS HAS BEEN REMOVED :param albums: list - A list of all the artist's albums to be collected """self.client_access_token = client_access_tokenself.artist_name = artist_name#self.albums = albumsself.base_url = 'https://api.genius.com/'self.headers = {'Authorization': 'Bearer ' + self.client_access_token}self.artist_songs = Nonedef search(self, query): """Makes a search request in the Genius API based on the query parameter. Returns a JSON response."""request_url = self.base_url + 'search' data = {'q': query} response = requests.get(request_url, data=data, headers=self.headers).json()return responsedef get_artist_songs(self): """Gets the songs of self.artist_name and places in a pandas.DataFrame"""# Search for the artist and get their id search_artist = self.search(self.artist_name) artist_id = str(search_artist['response']['hits'][0]['result']['primary_artist']['id'])print("ID: " + artist_id)# Initialize DataFrame df = pd.DataFrame(columns=['Title', 'URL'])# Iterate through all the pages of the artist's songs more_pages = True page = 1 i = 0 while more_pages:print("page: " + str(page))# Make a request to get the songs of an artist on a given page request_url = self.base_url + 'artists/' + artist_id + '/songs' + '?per_page=50&page=' + str(page) response = requests.get(request_url, headers=self.headers).json()print(response)# For each song which the given artist is the primary_artist of the song, add the song title and # Genius URL to the DataFrame for song in response['response']['songs']:if str(song['primary_artist']['id']) == artist_id:title = song['title'] url = song['url']df.loc[i] = [title, url] i += 1page += 1if response['response']['next_page'] is None: more_pages = False# Get the HTML, Album Name, and Song Lyrics from helper methods in the class df['Artist'] = self.artist_name df['html'] = df['URL'].apply(self.get_song_html) df['Album'] = df['html'].apply(self.get_album_from_html) #df['InAnAlbum'] = df['Album'].apply(lambda a: self.is_track_in_an_album(a, self.albums)) #df = df[df['InAnAlbum'] == True] df['Lyrics'] = df.apply(lambda row: self.get_lyrics(row.html), axis=1)del df['html']self.artist_songs = dfreturn self.artist_songsdef get_song_html(self, url): """Scrapes the entire HTML of the url parameter"""request = urllib.request.Request(url) request.add_header("Authorization", "Bearer " + self.client_access_token) request.add_header("User-Agent", "curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)") page = urllib.request.urlopen(request) html = BeautifulSoup(page, "html")print("Scraped: " + url) return htmldef get_lyrics(self, html): """Scrapes the html parameter to get the song lyrics on a Genius page in one, large String object"""lyrics = html.find("div", class_="lyrics")all_words = ''# Clean lyrics for line in lyrics.get_text(): all_words += line# Remove identifiers like chorus, verse, etc all_words = re.sub(r'[\(\[].*?[\)\]]', '', all_words)# remove empty lines, extra spaces, and special characters all_words = os.linesep.join([s for s in all_words.splitlines() if s]) all_words = all_words.replace('\r', '') all_words = all_words.replace('\n', ' ') all_words = all_words.replace(' ', ' ')return all_wordsdef get_album_from_html(self, html): """Scrapes the html parameter to get the album name of the song on a Genius page"""parse = html.findAll("span")album = ''for i in range(len(parse)): if parse[i].text == 'Album': i += 1 album = parse[i].text.strip() breakreturn album
The Genius Lyrics example uses Beautiful Soup to scrape the lyrics from the website. Web scraping is a useful technique that makes it easy to collect a variety of data. I walk through an additional web scraping example in a previous article. Check it out if you want more practice!
towardsdatascience.com
Although I haven’t yet used his methods, Medium writer Will Koehrsen has a walk through for scraping and parsing Wikipedia. Check out his work!
towardsdatascience.com
Although I think it is fun to collect and create my own datasets, Kaggle and Google’s Dataset Search offer convenient ways to find structured and labeled data. Kaggle is a popular competitive Data Science platform. Below is a list of popular datasets used for NLP projects.
https://www.kaggle.com/datasetshttps://datasetsearch.research.google.com/
Determine whether news story is from the Onion or not:
https://www.kaggle.com/chrisfilo/onion-or-not
Youtube rankings and descriptions:
https://www.kaggle.com/datasnaek/youtube-new
Netflix shows and descriptions:
https://www.kaggle.com/shivamb/netflix-shows
Wine Reviews. I use this in several articles and projects:
https://www.kaggle.com/zynicide/wine-reviews
A collection of amazon food reviews:
https://www.kaggle.com/snap/amazon-fine-food-reviews
News headlines for fake news detection:
https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection
Corpus for Entity Recognition tasks.
https://www.kaggle.com/abhinavwalia95/entity-annotated-corpus
Twitter Airline Sentiment tweets for sentiment analysis
https://www.kaggle.com/crowdflower/twitter-airline-sentiment
Yelp review dataset
https://www.kaggle.com/yelp-dataset/yelp-dataset
As NLP becomes more mainstream, it is important to understand how to easily collect rich, text-based datasets. Getting into Natural Language Processing can be tough, so I wanted to share a guide that simplifies ways to collect text data. With a few lines of Python, the astounding amount of data available on Reddit, Twitter, and Genius everyone’s fingertips! Thanks for reading, and check out my other NLP related articles if you want to use the data you know how to collect:
If you enjoyed this, follow me on Medium for more
Get FULL ACCESS and help support my content by subscribing
Let’s connect on LinkedIn
Analyze Data using Python? Check out my website
— Eric Kleppen | [
{
"code": null,
"e": 838,
"s": 171,
"text": "I’ve been fascinated by Natural Language Processing (NLP) since I got into data science a little over a year ago. Thanks to advancements in transfer learning, there has been some explosive progress in the field, and NLP products like Alexa and Siri have become household names. Since my background is technical writing and rhetorical theory, I was immediately drawn to projects involving text like sentiment analysis and topic extraction because I wanted to develop an understanding of how machine learning can provide insight into written language. One of my first data science projects was using Google’s Universal Sentence Encoder to produce wine recommendations."
},
{
"code": null,
"e": 1368,
"s": 838,
"text": "I always wanted a guide like this one, breaking down how to extract data from popular social media platforms. With increasing accessibility to powerful pre-trained language models like BERT and ELMo, it is important to understand where to find and extract data. Luckily, social media is an abundant resource for collecting NLP data sets, and is easily accessible with a few lines of Python. At the end of the article, I also include a list of popular Kaggle NLP datasets, and link to Google Dataset Search, the new search engine."
},
{
"code": null,
"e": 1514,
"s": 1368,
"text": "This article teaches you how to extract data from Twitter, Reddit, and Genius. I assume you already know some Python libraries Pandas and SQLite."
},
{
"code": null,
"e": 1945,
"s": 1514,
"text": "Before getting into the code, it is important to stress the value of an API Key. If you’re new to managing API keys, make sure to save them into a config.py file instead of hard-coding them in your app. Make sure not to include them in any code share online. API keys can be very valuable, and sometimes very expensive and must be protected. If you’re worried your key has been leaked, most providers allow you to regenerate them."
},
{
"code": null,
"e": 2038,
"s": 1945,
"text": "Add the config file to your gitignore file to prevent it from being pushed to your repo too!"
},
{
"code": null,
"e": 2267,
"s": 2038,
"text": "Twitter provides a plethora of data that is easy to access through their API. With the Tweepy Python library, easily pull a constant stream of tweets based on the desired topics. Twitter is great for mining trends and sentiment,"
},
{
"code": null,
"e": 2446,
"s": 2267,
"text": "For this tutorial, you will need to register an app with Twitter to get API Keys. Check out the official Twitter documentation if you’re not familiar with their developer portal!"
},
{
"code": null,
"e": 2487,
"s": 2446,
"text": "Use pip to install Tweepy and unidecode."
},
{
"code": null,
"e": 2527,
"s": 2487,
"text": "pip install tweepypip install unidecode"
},
{
"code": null,
"e": 2569,
"s": 2527,
"text": "Save the following keys to a config file:"
},
{
"code": null,
"e": 2709,
"s": 2569,
"text": "Connecting Tweepy to Twitter uses OAuth1. If you’re brand new to API authentication, check out the official Tweepy Authentication Tutorial."
},
{
"code": null,
"e": 2928,
"s": 2709,
"text": "To save the data from the incoming stream, I find it easiest to save it to an SQLite database. If you’re not familiar with SQL tables or need a refresher, check this free site for examples or check out my SQL tutorial."
},
{
"code": null,
"e": 3019,
"s": 2928,
"text": "The function unidecode() takes Unicode data and tries to represent it in ASCII characters."
},
{
"code": null,
"e": 3362,
"s": 3019,
"text": "#import dependenciesimport tweepyfrom tweepy import OAuthHandlerfrom tweepy.streaming import StreamListenerimport jsonfrom unidecode import unidecodeimport timeimport datetime#import the API keys from the config file.from config import con_key, con_sec, a_token, a_secret sqlite3conn = sqlite3.connect(\"twitterStream.sqlite\")c = conn.cursor()"
},
{
"code": null,
"e": 3517,
"s": 3362,
"text": "I need to create the table to store the wine data. I use SQLite because it is lightweight and server-less. Plus I like keeping all the data in once place!"
},
{
"code": null,
"e": 3646,
"s": 3517,
"text": "def create_table(): c.execute(\"CREATE TABLE IF NOT EXISTS Tweets(timestamp REAL, tweet TEXT)\") conn.commit()create_table()"
},
{
"code": null,
"e": 3800,
"s": 3646,
"text": "Notice I use IF NOT EXISTS to make sure the table doesn’t already exist in the database. Remember to commit the transaction using the conn.commit() call."
},
{
"code": null,
"e": 3928,
"s": 3800,
"text": "Here is some boilerplate code to pull the tweet and a timestamp from the streamed twitter data and insert it into the database."
},
{
"code": null,
"e": 4881,
"s": 3928,
"text": "class Listener(StreamListener): def on_data(self, data): try: data = json.loads(data) tweet = unidecode(data['text']) time_ms = data['timestamp_ms'] #print(tweet, time_ms) c.execute(\"INSERT INTO Tweets (timestamp, tweet) VALUES (?, ?)\", (time_ms, tweet)) conn.commit() time.sleep(2) except KeyError as e: print(str(e)) return(True) def on_error(self, status_code): if status_code == 420: #returning False in on_error disconnects the stream return Falsewhile True: try: auth = OAuthHandler(con_key, con_sec) auth.set_access_token(a_token, a_secret) twitterStream = tweepy.Stream(auth, Listener()) twitterStream.filter(track=['DataScience']) except Exception as e: print(str(e)) time.sleep(4)"
},
{
"code": null,
"e": 5407,
"s": 4881,
"text": "Notice I slow the stream using time.sleep().Notice the code is wrapped in a try/except to prevent potential hiccups from disrupting the stream. Additionally, the documentation recommends using an on_error() function to act as a circuit-breaker if the app is making too many requests.Notice I wrap the stream object in a while condition. That way, it stops if it hits the 420 error.Notice the twitterstream.filter uses track to find keywords in tweets. If you want to follow a specific user’s tweets, use .filter(follow=[“”])."
},
{
"code": null,
"e": 5449,
"s": 5407,
"text": "Extract the data from the SQLite database"
},
{
"code": null,
"e": 5610,
"s": 5449,
"text": "sql = '''select tweet from Tweets where tweet not like 'RT %' order by timestamp desc'''tweet_df = pd.read_sql(sql, conn)tweet_df"
},
{
"code": null,
"e": 5994,
"s": 5610,
"text": "Like Twitter, the social network Reddit contains a jaw dropping amount of information that is easy to scrape. It is a social network that works like an internet forum allowing users to post about whatever topic they want. Users form communities called subreddits, and they up-vote or down-vote posts in their communities to decide what gets viewed first and what sinks to the bottom."
},
{
"code": null,
"e": 6231,
"s": 5994,
"text": "I’ll explain how to get a Reddit API key and how to extract data from Reddit using the PRAW library. Although Reddit has an API, the Python Reddit API Wrapper, or PRAW for short, offers a simplified experience. PRAW supports Python 3.5+"
},
{
"code": null,
"e": 6342,
"s": 6231,
"text": "A user account to Reddit is required to use the API. It is completely free and only requires an email address!"
},
{
"code": null,
"e": 6365,
"s": 6342,
"text": "https://www.reddit.com"
},
{
"code": null,
"e": 6596,
"s": 6365,
"text": "If there is a way to get here using the new Reddit UI, leave me a comment! If it is your first time, follow these steps to get an API key after signing into Reddit. If you already have a key, use this link to go to your apps page."
},
{
"code": null,
"e": 6651,
"s": 6596,
"text": "Click the User Account droplist. User options display."
},
{
"code": null,
"e": 6766,
"s": 6651,
"text": "Click Visit Old Reddit from the user options. The page will change and the URL will become https://old.reddit.com/"
},
{
"code": null,
"e": 6920,
"s": 6766,
"text": "Click the preferences link next to the logout button.Click the apps tab on the PREFERENCES screen.Click the are you a developer? create am app... button."
},
{
"code": null,
"e": 7068,
"s": 6920,
"text": "Enter a name.Select the type of app.Enter a Description.Use http://localhost:8080 as the redirect uri.Click create app after populating the fields."
},
{
"code": null,
"e": 7195,
"s": 7068,
"text": "The API information required to connect will display. I’ll walk through connecting to the API using PRAW when I get into code."
},
{
"code": null,
"e": 7252,
"s": 7195,
"text": "Congratulations on getting set up to scrape Reddit data!"
},
{
"code": null,
"e": 7363,
"s": 7252,
"text": "The recommended way to install PRAW is to use pip. The install the following packages to create the dashboard."
},
{
"code": null,
"e": 7380,
"s": 7363,
"text": "pip install praw"
},
{
"code": null,
"e": 7434,
"s": 7380,
"text": "Start by importing the libraries and the config file:"
},
{
"code": null,
"e": 7498,
"s": 7434,
"text": "import prawimport pandas as pd from config import cid, csec, ua"
},
{
"code": null,
"e": 7664,
"s": 7498,
"text": "Create a read-only Reddit instance. That means I don’t need to enter Reddit credentials used to post responses or create new threads; the connection only reads data."
},
{
"code": null,
"e": 7725,
"s": 7664,
"text": "PRAW uses OAuth authentication to connect to the Reddit API."
},
{
"code": null,
"e": 7866,
"s": 7725,
"text": "#create a reddit connectionreddit = praw.Reddit(client_id= cid, client_secret= csec, user_agent= ua)"
},
{
"code": null,
"e": 7926,
"s": 7866,
"text": "Here is a list of examples I think would be fun to explore:"
},
{
"code": null,
"e": 7991,
"s": 7926,
"text": "news, datascience, learnmachinelearning, gaming, funny, politics"
},
{
"code": null,
"e": 8141,
"s": 7991,
"text": "Use the Subreddit class in PRAW to retrieve the data from the desired subreddit. It is possible to order the data based on the follow Reddit options:"
},
{
"code": null,
"e": 8191,
"s": 8141,
"text": "hot — order by the posts getting the most traffic"
},
{
"code": null,
"e": 8237,
"s": 8191,
"text": "new — order by the newest posts in the thread"
},
{
"code": null,
"e": 8276,
"s": 8237,
"text": "top — order by the most up-voted posts"
},
{
"code": null,
"e": 8323,
"s": 8276,
"text": "rising — order by the posts gaining popularity"
},
{
"code": null,
"e": 8383,
"s": 8323,
"text": "If you want to include multiple subreddits, use a + symbol:"
},
{
"code": null,
"e": 8551,
"s": 8383,
"text": "#single subreddit new 5subreddit = reddit.subreddit('news').new(limit = 5)#multiple subreddits top 5subreddit = reddit.subreddit('news' + 'datascience').top(limit = 5)"
},
{
"code": null,
"e": 8656,
"s": 8551,
"text": "This returns an object that holds the data in an attribute. The attribute is like a key in a dictionary."
},
{
"code": null,
"e": 8889,
"s": 8656,
"text": "The data is linked to an attributed owned by the object. If the attribute is the Key, the data is the Value. The attributes are dynamically generated, so it is best to check what is available using Python’s built-in vars() function."
},
{
"code": null,
"e": 9006,
"s": 8889,
"text": "Use this boilerplate code to see all the attributes owned by object representing the reddit post. It is a LONG list!"
},
{
"code": null,
"e": 9109,
"s": 9006,
"text": "subreddit = reddit.subreddit('news').new(limit = 1)for post in subreddit: pprint.pprint(vars(post))"
},
{
"code": null,
"e": 9156,
"s": 9109,
"text": "Notice in the list the attributes of interest:"
},
{
"code": null,
"e": 9495,
"s": 9156,
"text": "title — Returns post title.score — Returns number of up-votes or down-votes.num_comments — Returns the number of comments on the thread.selftext — Returns the body of the post.created — Returns a timestamp for the post.pinned — Indicates whether the thread was pinned.total_awards_received — Returns number of awards received by the post."
},
{
"code": null,
"e": 9697,
"s": 9495,
"text": "Now that the attributes have been identified, load them data into a pandas DataFrame or save them to an SQLite database like in the Twitter example. In this example, I’ll save it to a pandas DataFrame."
},
{
"code": null,
"e": 10180,
"s": 9697,
"text": "#list for df conversionposts = []#return 100 new posts from wallstreetbetsnew_bets = reddit.subreddit('wallstreetbets').new(limit=100)#return the important attributesfor post in new_bets: posts.append([post.title, post.score, post.num_comments, post.selftext, post.created, post.pinned, post.total_awards_received])#create a dataframeposts = pd.DataFrame(posts,columns=['title', 'score', 'comments', 'post', 'created', 'pinned', 'total awards'])#return top 3 df rowsposts.head(3)"
},
{
"code": null,
"e": 10514,
"s": 10180,
"text": "I have always been a fan of music, particularly heavy metal. In heavy metal, the lyrics can sometimes be quite difficult to understand, so I go to Genius to decipher them. The website Genius.com is a platform for annotating lyrics, and collecting trivia about music, albums and artists. Genius allows users to register an API Client."
},
{
"code": null,
"e": 10545,
"s": 10514,
"text": "https://genius.com/api-clients"
},
{
"code": null,
"e": 10814,
"s": 10545,
"text": "Either Sign up or Sign in. Click the Developers link.Click Create an API Client.Enter an App Name.Enter a website URL if you have one, otherwise http://127.0.0.1 will work.Click Save. The API Client will display.Click Generate Access Token to generate an access token."
},
{
"code": null,
"e": 11120,
"s": 10814,
"text": "Surprisingly, due to legal reasons, the Genius API does not provide a way to download song lyrics. It is possible to search lyrics, but not download them. Lucky for everyone, Medium author Ben Wallace has provided us with a convenient wrapper for scraping the lyrics. Find his original code on GitHub too:"
},
{
"code": null,
"e": 11131,
"s": 11120,
"text": "github.com"
},
{
"code": null,
"e": 11318,
"s": 11131,
"text": "I have modified his wrapper to make it easier to download an artist’s complete works rather than code the albums I want to include, and I added an Artist column to store the artist name."
},
{
"code": null,
"e": 11539,
"s": 11318,
"text": "The wrapper uses the API to get the URLs linking to the lyrics. From there, BeautifulSoup is used to parse the HTML for each URL. The process results in a dataframe that contains the Title, URL, Artist, Album and Lyrics:"
},
{
"code": null,
"e": 11752,
"s": 11539,
"text": "The wrapper is a class named GeniusArtistDataCollect(). Use it to connect to the API and retrieve song lyrics for a specified artist. In the example, I use one of my favorite metal bands, The Black Dahlia Murder."
},
{
"code": null,
"e": 11858,
"s": 11752,
"text": "To use GeniusArtistDataCollect(), instantiate it, passing in the Client Access Token and the Artist name."
},
{
"code": null,
"e": 11920,
"s": 11858,
"text": "g = GeniusArtistDataCollect(token, 'The Black Dahlia Murder')"
},
{
"code": null,
"e": 12026,
"s": 11920,
"text": "Call get_artists_songs() from the GeniusArtistDataCollect object. This will return as a pandas DataFrame."
},
{
"code": null,
"e": 12058,
"s": 12026,
"text": "songs_df = g.get_artist_songs()"
},
{
"code": null,
"e": 12109,
"s": 12058,
"text": "Here is the modified wrapper I use in the example:"
},
{
"code": null,
"e": 16634,
"s": 12109,
"text": "import osimport reimport requestsimport pandas as pdimport urllib.requestfrom bs4 import BeautifulSoupfrom config import tokenclass GeniusArtistDataCollect: \"\"\"A wrapper class that is able to retrieve, clean, and organize all the album songs of a given artist Uses the Genius API and webscraping techniques to get the data.\"\"\"def __init__(self, client_access_token, artist_name): \"\"\" Instantiate a GeniusArtistDataCollect object :param client_access_token: str - Token to access the Genius API. Create one at https://genius.com/developers :param artist_name: str - The name of the artist of interest THIS HAS BEEN REMOVED :param albums: list - A list of all the artist's albums to be collected \"\"\"self.client_access_token = client_access_tokenself.artist_name = artist_name#self.albums = albumsself.base_url = 'https://api.genius.com/'self.headers = {'Authorization': 'Bearer ' + self.client_access_token}self.artist_songs = Nonedef search(self, query): \"\"\"Makes a search request in the Genius API based on the query parameter. Returns a JSON response.\"\"\"request_url = self.base_url + 'search' data = {'q': query} response = requests.get(request_url, data=data, headers=self.headers).json()return responsedef get_artist_songs(self): \"\"\"Gets the songs of self.artist_name and places in a pandas.DataFrame\"\"\"# Search for the artist and get their id search_artist = self.search(self.artist_name) artist_id = str(search_artist['response']['hits'][0]['result']['primary_artist']['id'])print(\"ID: \" + artist_id)# Initialize DataFrame df = pd.DataFrame(columns=['Title', 'URL'])# Iterate through all the pages of the artist's songs more_pages = True page = 1 i = 0 while more_pages:print(\"page: \" + str(page))# Make a request to get the songs of an artist on a given page request_url = self.base_url + 'artists/' + artist_id + '/songs' + '?per_page=50&page=' + str(page) response = requests.get(request_url, headers=self.headers).json()print(response)# For each song which the given artist is the primary_artist of the song, add the song title and # Genius URL to the DataFrame for song in response['response']['songs']:if str(song['primary_artist']['id']) == artist_id:title = song['title'] url = song['url']df.loc[i] = [title, url] i += 1page += 1if response['response']['next_page'] is None: more_pages = False# Get the HTML, Album Name, and Song Lyrics from helper methods in the class df['Artist'] = self.artist_name df['html'] = df['URL'].apply(self.get_song_html) df['Album'] = df['html'].apply(self.get_album_from_html) #df['InAnAlbum'] = df['Album'].apply(lambda a: self.is_track_in_an_album(a, self.albums)) #df = df[df['InAnAlbum'] == True] df['Lyrics'] = df.apply(lambda row: self.get_lyrics(row.html), axis=1)del df['html']self.artist_songs = dfreturn self.artist_songsdef get_song_html(self, url): \"\"\"Scrapes the entire HTML of the url parameter\"\"\"request = urllib.request.Request(url) request.add_header(\"Authorization\", \"Bearer \" + self.client_access_token) request.add_header(\"User-Agent\", \"curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)\") page = urllib.request.urlopen(request) html = BeautifulSoup(page, \"html\")print(\"Scraped: \" + url) return htmldef get_lyrics(self, html): \"\"\"Scrapes the html parameter to get the song lyrics on a Genius page in one, large String object\"\"\"lyrics = html.find(\"div\", class_=\"lyrics\")all_words = ''# Clean lyrics for line in lyrics.get_text(): all_words += line# Remove identifiers like chorus, verse, etc all_words = re.sub(r'[\\(\\[].*?[\\)\\]]', '', all_words)# remove empty lines, extra spaces, and special characters all_words = os.linesep.join([s for s in all_words.splitlines() if s]) all_words = all_words.replace('\\r', '') all_words = all_words.replace('\\n', ' ') all_words = all_words.replace(' ', ' ')return all_wordsdef get_album_from_html(self, html): \"\"\"Scrapes the html parameter to get the album name of the song on a Genius page\"\"\"parse = html.findAll(\"span\")album = ''for i in range(len(parse)): if parse[i].text == 'Album': i += 1 album = parse[i].text.strip() breakreturn album"
},
{
"code": null,
"e": 16916,
"s": 16634,
"text": "The Genius Lyrics example uses Beautiful Soup to scrape the lyrics from the website. Web scraping is a useful technique that makes it easy to collect a variety of data. I walk through an additional web scraping example in a previous article. Check it out if you want more practice!"
},
{
"code": null,
"e": 16939,
"s": 16916,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 17083,
"s": 16939,
"text": "Although I haven’t yet used his methods, Medium writer Will Koehrsen has a walk through for scraping and parsing Wikipedia. Check out his work!"
},
{
"code": null,
"e": 17106,
"s": 17083,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 17380,
"s": 17106,
"text": "Although I think it is fun to collect and create my own datasets, Kaggle and Google’s Dataset Search offer convenient ways to find structured and labeled data. Kaggle is a popular competitive Data Science platform. Below is a list of popular datasets used for NLP projects."
},
{
"code": null,
"e": 17454,
"s": 17380,
"text": "https://www.kaggle.com/datasetshttps://datasetsearch.research.google.com/"
},
{
"code": null,
"e": 17509,
"s": 17454,
"text": "Determine whether news story is from the Onion or not:"
},
{
"code": null,
"e": 17555,
"s": 17509,
"text": "https://www.kaggle.com/chrisfilo/onion-or-not"
},
{
"code": null,
"e": 17590,
"s": 17555,
"text": "Youtube rankings and descriptions:"
},
{
"code": null,
"e": 17635,
"s": 17590,
"text": "https://www.kaggle.com/datasnaek/youtube-new"
},
{
"code": null,
"e": 17667,
"s": 17635,
"text": "Netflix shows and descriptions:"
},
{
"code": null,
"e": 17712,
"s": 17667,
"text": "https://www.kaggle.com/shivamb/netflix-shows"
},
{
"code": null,
"e": 17771,
"s": 17712,
"text": "Wine Reviews. I use this in several articles and projects:"
},
{
"code": null,
"e": 17816,
"s": 17771,
"text": "https://www.kaggle.com/zynicide/wine-reviews"
},
{
"code": null,
"e": 17853,
"s": 17816,
"text": "A collection of amazon food reviews:"
},
{
"code": null,
"e": 17906,
"s": 17853,
"text": "https://www.kaggle.com/snap/amazon-fine-food-reviews"
},
{
"code": null,
"e": 17946,
"s": 17906,
"text": "News headlines for fake news detection:"
},
{
"code": null,
"e": 18021,
"s": 17946,
"text": "https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection"
},
{
"code": null,
"e": 18058,
"s": 18021,
"text": "Corpus for Entity Recognition tasks."
},
{
"code": null,
"e": 18120,
"s": 18058,
"text": "https://www.kaggle.com/abhinavwalia95/entity-annotated-corpus"
},
{
"code": null,
"e": 18176,
"s": 18120,
"text": "Twitter Airline Sentiment tweets for sentiment analysis"
},
{
"code": null,
"e": 18237,
"s": 18176,
"text": "https://www.kaggle.com/crowdflower/twitter-airline-sentiment"
},
{
"code": null,
"e": 18257,
"s": 18237,
"text": "Yelp review dataset"
},
{
"code": null,
"e": 18306,
"s": 18257,
"text": "https://www.kaggle.com/yelp-dataset/yelp-dataset"
},
{
"code": null,
"e": 18783,
"s": 18306,
"text": "As NLP becomes more mainstream, it is important to understand how to easily collect rich, text-based datasets. Getting into Natural Language Processing can be tough, so I wanted to share a guide that simplifies ways to collect text data. With a few lines of Python, the astounding amount of data available on Reddit, Twitter, and Genius everyone’s fingertips! Thanks for reading, and check out my other NLP related articles if you want to use the data you know how to collect:"
},
{
"code": null,
"e": 18833,
"s": 18783,
"text": "If you enjoyed this, follow me on Medium for more"
},
{
"code": null,
"e": 18892,
"s": 18833,
"text": "Get FULL ACCESS and help support my content by subscribing"
},
{
"code": null,
"e": 18918,
"s": 18892,
"text": "Let’s connect on LinkedIn"
},
{
"code": null,
"e": 18966,
"s": 18918,
"text": "Analyze Data using Python? Check out my website"
}
] |
PHP timestamp to HTML5 input type=datetime element | For HTML5 input time, in PHP:
echo date("Y-m-d\TH:i:s");
The output would be:
2018-28-03T19:12:49
HTML with Timestamp would be:
<input type="datetime" value="<?php echo date("Y-m-d\TH:i:s",$timestamp); ?>"/> | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "For HTML5 input time, in PHP:"
},
{
"code": null,
"e": 1119,
"s": 1092,
"text": "echo date(\"Y-m-d\\TH:i:s\");"
},
{
"code": null,
"e": 1140,
"s": 1119,
"text": "The output would be:"
},
{
"code": null,
"e": 1160,
"s": 1140,
"text": "2018-28-03T19:12:49"
},
{
"code": null,
"e": 1190,
"s": 1160,
"text": "HTML with Timestamp would be:"
},
{
"code": null,
"e": 1270,
"s": 1190,
"text": "<input type=\"datetime\" value=\"<?php echo date(\"Y-m-d\\TH:i:s\",$timestamp); ?>\"/>"
}
] |
Using final with Inheritance in Java - GeeksforGeeks | 16 Mar, 2022
Prerequisite – Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword.
Using final with inheritance
During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes. Note that it is not necessary to declare final methods in the initial stage of inheritance(base class always). We can declare a final method in any subclass for which we want that if any other class extends this subclass, then it must follow the same implementation of the method as in that subclass.
Java
// Java program to illustrate// use of final with inheritance // base classabstract class Shape{ private double width; private double height; // Shape class parameterized constructor public Shape(double width, double height) { this.width = width; this.height = height; } // getWidth method is declared as final // so any class extending // Shape can't override it public final double getWidth() { return width; } // getHeight method is declared as final // so any class extending Shape // can not override it public final double getHeight() { return height; } // method getArea() declared abstract because // it upon its subclasses to provide // complete implementation abstract double getArea();} // derived class oneclass Rectangle extends Shape{ // Rectangle class parameterized constructor public Rectangle(double width, double height) { // calling Shape class constructor super(width, height); } // getArea method is overridden and declared // as final so any class extending // Rectangle can't override it @Override final double getArea() { return this.getHeight() * this.getWidth(); } } //derived class twoclass Square extends Shape{ // Square class parameterized constructor public Square(double side) { // calling Shape class constructor super(side, side); } // getArea method is overridden and declared as // final so any class extending // Square can't override it @Override final double getArea() { return this.getHeight() * this.getWidth(); } } // Driver classpublic class Test{ public static void main(String[] args) { // creating Rectangle object Shape s1 = new Rectangle(10, 20); // creating Square object Shape s2 = new Square(10); // getting width and height of s1 System.out.println("width of s1 : "+ s1.getWidth()); System.out.println("height of s1 : "+ s1.getHeight()); // getting width and height of s2 System.out.println("width of s2 : "+ s2.getWidth()); System.out.println("height of s2 : "+ s2.getHeight()); //getting area of s1 System.out.println("area of s1 : "+ s1.getArea()); //getting area of s2 System.out.println("area of s2 : "+ s2.getArea()); }}
Output:
width of s1 : 10.0
height of s1 : 20.0
width of s2 : 10.0
height of s2 : 10.0
area of s1 : 200.0
area of s2 : 100.0
Using final to Prevent Inheritance
When a class is declared as final then it cannot be subclassed i.e. no other class can extend it. This is particularly useful, for example, when creating an immutable class like the predefined String class. The following fragment illustrates the final keyword with a class:
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Note :
Declaring a class as final implicitly declares all of its methods as final, too.
It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. For more on abstract classes, refer abstract classes in java
Using final to Prevent Overriding
When a method is declared as final then it cannot be overridden by subclasses. The Object class does this—a number of its methods are final. The following fragment illustrates the final keyword with a method:
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Normally, Java resolves calls to methods dynamically, at run time. This is called late or dynamic binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early or static binding. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
bhuwnesharora
ruhelaa48
chhabradhanvi
java-inheritance
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java | [
{
"code": null,
"e": 23017,
"s": 22989,
"text": "\n16 Mar, 2022"
},
{
"code": null,
"e": 23207,
"s": 23017,
"text": "Prerequisite – Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. "
},
{
"code": null,
"e": 23236,
"s": 23207,
"text": "Using final with inheritance"
},
{
"code": null,
"e": 23701,
"s": 23236,
"text": "During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes. Note that it is not necessary to declare final methods in the initial stage of inheritance(base class always). We can declare a final method in any subclass for which we want that if any other class extends this subclass, then it must follow the same implementation of the method as in that subclass. "
},
{
"code": null,
"e": 23706,
"s": 23701,
"text": "Java"
},
{
"code": "// Java program to illustrate// use of final with inheritance // base classabstract class Shape{ private double width; private double height; // Shape class parameterized constructor public Shape(double width, double height) { this.width = width; this.height = height; } // getWidth method is declared as final // so any class extending // Shape can't override it public final double getWidth() { return width; } // getHeight method is declared as final // so any class extending Shape // can not override it public final double getHeight() { return height; } // method getArea() declared abstract because // it upon its subclasses to provide // complete implementation abstract double getArea();} // derived class oneclass Rectangle extends Shape{ // Rectangle class parameterized constructor public Rectangle(double width, double height) { // calling Shape class constructor super(width, height); } // getArea method is overridden and declared // as final so any class extending // Rectangle can't override it @Override final double getArea() { return this.getHeight() * this.getWidth(); } } //derived class twoclass Square extends Shape{ // Square class parameterized constructor public Square(double side) { // calling Shape class constructor super(side, side); } // getArea method is overridden and declared as // final so any class extending // Square can't override it @Override final double getArea() { return this.getHeight() * this.getWidth(); } } // Driver classpublic class Test{ public static void main(String[] args) { // creating Rectangle object Shape s1 = new Rectangle(10, 20); // creating Square object Shape s2 = new Square(10); // getting width and height of s1 System.out.println(\"width of s1 : \"+ s1.getWidth()); System.out.println(\"height of s1 : \"+ s1.getHeight()); // getting width and height of s2 System.out.println(\"width of s2 : \"+ s2.getWidth()); System.out.println(\"height of s2 : \"+ s2.getHeight()); //getting area of s1 System.out.println(\"area of s1 : \"+ s1.getArea()); //getting area of s2 System.out.println(\"area of s2 : \"+ s2.getArea()); }}",
"e": 26184,
"s": 23706,
"text": null
},
{
"code": null,
"e": 26194,
"s": 26184,
"text": "Output: "
},
{
"code": null,
"e": 26310,
"s": 26194,
"text": "width of s1 : 10.0\nheight of s1 : 20.0\nwidth of s2 : 10.0\nheight of s2 : 10.0\narea of s1 : 200.0\narea of s2 : 100.0"
},
{
"code": null,
"e": 26347,
"s": 26312,
"text": "Using final to Prevent Inheritance"
},
{
"code": null,
"e": 26622,
"s": 26347,
"text": "When a class is declared as final then it cannot be subclassed i.e. no other class can extend it. This is particularly useful, for example, when creating an immutable class like the predefined String class. The following fragment illustrates the final keyword with a class: "
},
{
"code": null,
"e": 26757,
"s": 26622,
"text": "final class A\n{\n // methods and fields\n}\n// The following class is illegal.\nclass B extends A \n{ \n // ERROR! Can't subclass A\n}"
},
{
"code": null,
"e": 26766,
"s": 26757,
"text": "Note : "
},
{
"code": null,
"e": 26847,
"s": 26766,
"text": "Declaring a class as final implicitly declares all of its methods as final, too."
},
{
"code": null,
"e": 27084,
"s": 26847,
"text": "It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. For more on abstract classes, refer abstract classes in java"
},
{
"code": null,
"e": 27120,
"s": 27086,
"text": "Using final to Prevent Overriding"
},
{
"code": null,
"e": 27331,
"s": 27120,
"text": "When a method is declared as final then it cannot be overridden by subclasses. The Object class does this—a number of its methods are final. The following fragment illustrates the final keyword with a method: "
},
{
"code": null,
"e": 27557,
"s": 27331,
"text": "class A \n{\n final void m1() \n {\n System.out.println(\"This is a final method.\");\n }\n}\n\nclass B extends A \n{\n void m1()\n { \n // ERROR! Can't override.\n System.out.println(\"Illegal!\");\n }\n}"
},
{
"code": null,
"e": 28225,
"s": 27557,
"text": "Normally, Java resolves calls to methods dynamically, at run time. This is called late or dynamic binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early or static binding. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28239,
"s": 28225,
"text": "bhuwnesharora"
},
{
"code": null,
"e": 28249,
"s": 28239,
"text": "ruhelaa48"
},
{
"code": null,
"e": 28263,
"s": 28249,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 28280,
"s": 28263,
"text": "java-inheritance"
},
{
"code": null,
"e": 28285,
"s": 28280,
"text": "Java"
},
{
"code": null,
"e": 28290,
"s": 28285,
"text": "Java"
},
{
"code": null,
"e": 28388,
"s": 28290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28397,
"s": 28388,
"text": "Comments"
},
{
"code": null,
"e": 28410,
"s": 28397,
"text": "Old Comments"
},
{
"code": null,
"e": 28425,
"s": 28410,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28469,
"s": 28425,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28491,
"s": 28469,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28516,
"s": 28491,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28552,
"s": 28516,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 28582,
"s": 28552,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28613,
"s": 28582,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28645,
"s": 28613,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28663,
"s": 28645,
"text": "ArrayList in Java"
}
] |
How to Run Scrapy From a Script. Forget about scrapy’s framework and... | by Aaron S | Towards Data Science | Scrapy is a great framework to use for scraping projects. However, did you know there is a way to run Scrapy straight from a script?
Looking at the documentation, there are two ways to run Scrapy. Using the Scrapy API or the framework.
Why you would use scrapy from a scriptUnderstand the basic script every time you want access scrapy from an individual scriptUnderstand how to specify customised scrapy settingsUnderstand how to specify HTTP requests for scrapy to invokeUnderstand how to process those HTTP responses using scrapy under one script.
Why you would use scrapy from a script
Understand the basic script every time you want access scrapy from an individual script
Understand how to specify customised scrapy settings
Understand how to specify HTTP requests for scrapy to invoke
Understand how to process those HTTP responses using scrapy under one script.
Scrapy can be used for a heavy-duty scraping work, however, there are a lot of projects that are quite small and don’t require the need for using the whole scrapy framework. This is where using scrapy in a python script comes in. No need to use the whole framework you can do it all from a python script.
Let’s see what the basics of this look like before fleshing out some of the necessary settings to scrape.
The key to running scrapy in a python script is the CrawlerProcess class. This is a class of the Crawler module. It provides the engine to run scrapy within a python script. Within the CrawlerProcess class code, python’s twisted framework is imported.
Twisted is a python framework that is used for input and output processes like HTTP requests for example. Now it does this through what’s called a twister event reactor. Scrapy is built on top of twisted! We won’t go into too much detail here but needless to say, the CrawlerProcess class imports a twisted reactor which listens for events like multiple HTTP requests. This is at the heart of how scrapy works.
CrawlerProcess assumes that a twisted reactor is NOT used by anything else, like for example another spider. With that, we have the code below.
import scrapyfrom scrapy.crawler import CrawlerProcessclass TestSpider(scrapy.Spider): name = 'test'if __name__ == "__main__": process = CrawlerProcess() process.crawl(TestSpider) process.start()
Now for us to use the scrapy framework, we must create our spider, this is done by creating a class which inherits from scrapy.Spider. scrapy.Spider is the most basic spider that we must derive from in all scrapy projects. With this, we have to give this spider a name for it to run/ Spiders will require a couple of functions and an URL to scrape but for this example, we will omit this for the moment.Now you see if __name__ == “__main__”. This is used as a best practice in python. When we write a script you want to it to be able to run the code but also be able to import that code somewhere else. Please see here for further discussion on this point.We instantiate the class CrawlerProcess first to get access to the functions we want. CrawlerProcess has two functions we are interested in, crawl and startWe use crawl to start the spider we created. We then use the start function to start a twisted reactor, the engine that processes and listens to our HTTP requests we want.
Now for us to use the scrapy framework, we must create our spider, this is done by creating a class which inherits from scrapy.Spider. scrapy.Spider is the most basic spider that we must derive from in all scrapy projects. With this, we have to give this spider a name for it to run/ Spiders will require a couple of functions and an URL to scrape but for this example, we will omit this for the moment.
Now you see if __name__ == “__main__”. This is used as a best practice in python. When we write a script you want to it to be able to run the code but also be able to import that code somewhere else. Please see here for further discussion on this point.
We instantiate the class CrawlerProcess first to get access to the functions we want. CrawlerProcess has two functions we are interested in, crawl and start
We use crawl to start the spider we created. We then use the start function to start a twisted reactor, the engine that processes and listens to our HTTP requests we want.
The scrapy framework provides a list of settings that it will use automatically, however for working with the Scrapy API we have to provide the settings explicitly. The settings we define is how we can customise our spiders. The spider.Spider class has a variable called custom_settings. Now this variable can be used to override the settings scrapy automatically uses. We have to create a dictionary of our settings to do this as the custom_settings variable is set to none using scrapy.
You may want to use some or most of the settings scrapy provides, in which case you could copy them from there. Alternatively, a list of the built-in settings can be found here.
class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 }
We have shown how to create a spider and define the settings, but we haven’t specified any URLs to scrape, or how we want to specify the requests to the website we want to get data from. For example, parameters, headers and user-agents.When we create spider we also start a method called start_requests(). This will create the requests for any URL we want. Now there are two ways to use this method.
1) By defining the start_urls attribute 2) We implement our function called start_requests
The shortest way is by defining start_urls. We define it as a list of URLs we want to get, by specifying this variable we automatically use start_requests() to go through each one of our URLs.
class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 } start_urls = ['URL1','URL2']
However notice how if we do this, we can’t specify our headers, parameters or anything else we want to go along with the request? This is where implementing our start_requests method comes in.
First, we define our variables we want to go along with the request. We then implement our start_requests method so we can make use of the headers and parameters we want, as well as where we want to the response to go.
class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 } headers = {} params = {} def start_requests(self): yield scrapy.Requests(url, headers=headers, params=params)
Here we access the Requests method which when given an URL will make the HTTP requests and return a response defined as the response variable.
You will notice how we didn’t specify a callback? That is we didn’t specify where scrapy should send the response to the requests we just told it to get for us.
Let’s fix that, by default scrapy expects the callback method to be the parse function but it could be anything we want it to be.
class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 } headers = {} params = {} def start_requests(self): yield scrapy.Requests(url, headers=headers, params=params,callback = self.parse) def parse(self,response): print(response.body)
Here we have defined the function parse which accepts a response variable, remember this is created when we ask scrapy to do the HTTP requests. We then ask scrapy to print the response body.
With that, we now have the basics of running scrapy in a python script. We can use all the same methods but we just have to do a bit of configuring beforehand.
Why might you use the scrapy framework ? When is importing scrapy in a python script useful?What does the CrawlerProcess class do?Can you recall the basic script used to start scrapy within a python script?How do you add scrapy settings in your python script?Why might you use a start_requests function instead of start_urls ?
Why might you use the scrapy framework ? When is importing scrapy in a python script useful?
What does the CrawlerProcess class do?
Can you recall the basic script used to start scrapy within a python script?
How do you add scrapy settings in your python script?
Why might you use a start_requests function instead of start_urls ?
Please see here for further details about what I’m up to project-wise on my blog and other posts.For more tech/coding related content please sign up to my newsletter here
I’d be grateful for any comments or if you want to collaborate or need help with python please do get in touch.If you want to get in contact with me, please do so here [email protected]. | [
{
"code": null,
"e": 180,
"s": 47,
"text": "Scrapy is a great framework to use for scraping projects. However, did you know there is a way to run Scrapy straight from a script?"
},
{
"code": null,
"e": 283,
"s": 180,
"text": "Looking at the documentation, there are two ways to run Scrapy. Using the Scrapy API or the framework."
},
{
"code": null,
"e": 598,
"s": 283,
"text": "Why you would use scrapy from a scriptUnderstand the basic script every time you want access scrapy from an individual scriptUnderstand how to specify customised scrapy settingsUnderstand how to specify HTTP requests for scrapy to invokeUnderstand how to process those HTTP responses using scrapy under one script."
},
{
"code": null,
"e": 637,
"s": 598,
"text": "Why you would use scrapy from a script"
},
{
"code": null,
"e": 725,
"s": 637,
"text": "Understand the basic script every time you want access scrapy from an individual script"
},
{
"code": null,
"e": 778,
"s": 725,
"text": "Understand how to specify customised scrapy settings"
},
{
"code": null,
"e": 839,
"s": 778,
"text": "Understand how to specify HTTP requests for scrapy to invoke"
},
{
"code": null,
"e": 917,
"s": 839,
"text": "Understand how to process those HTTP responses using scrapy under one script."
},
{
"code": null,
"e": 1222,
"s": 917,
"text": "Scrapy can be used for a heavy-duty scraping work, however, there are a lot of projects that are quite small and don’t require the need for using the whole scrapy framework. This is where using scrapy in a python script comes in. No need to use the whole framework you can do it all from a python script."
},
{
"code": null,
"e": 1328,
"s": 1222,
"text": "Let’s see what the basics of this look like before fleshing out some of the necessary settings to scrape."
},
{
"code": null,
"e": 1580,
"s": 1328,
"text": "The key to running scrapy in a python script is the CrawlerProcess class. This is a class of the Crawler module. It provides the engine to run scrapy within a python script. Within the CrawlerProcess class code, python’s twisted framework is imported."
},
{
"code": null,
"e": 1991,
"s": 1580,
"text": "Twisted is a python framework that is used for input and output processes like HTTP requests for example. Now it does this through what’s called a twister event reactor. Scrapy is built on top of twisted! We won’t go into too much detail here but needless to say, the CrawlerProcess class imports a twisted reactor which listens for events like multiple HTTP requests. This is at the heart of how scrapy works."
},
{
"code": null,
"e": 2135,
"s": 1991,
"text": "CrawlerProcess assumes that a twisted reactor is NOT used by anything else, like for example another spider. With that, we have the code below."
},
{
"code": null,
"e": 2337,
"s": 2135,
"text": "import scrapyfrom scrapy.crawler import CrawlerProcessclass TestSpider(scrapy.Spider): name = 'test'if __name__ == \"__main__\": process = CrawlerProcess() process.crawl(TestSpider) process.start()"
},
{
"code": null,
"e": 3321,
"s": 2337,
"text": "Now for us to use the scrapy framework, we must create our spider, this is done by creating a class which inherits from scrapy.Spider. scrapy.Spider is the most basic spider that we must derive from in all scrapy projects. With this, we have to give this spider a name for it to run/ Spiders will require a couple of functions and an URL to scrape but for this example, we will omit this for the moment.Now you see if __name__ == “__main__”. This is used as a best practice in python. When we write a script you want to it to be able to run the code but also be able to import that code somewhere else. Please see here for further discussion on this point.We instantiate the class CrawlerProcess first to get access to the functions we want. CrawlerProcess has two functions we are interested in, crawl and startWe use crawl to start the spider we created. We then use the start function to start a twisted reactor, the engine that processes and listens to our HTTP requests we want."
},
{
"code": null,
"e": 3725,
"s": 3321,
"text": "Now for us to use the scrapy framework, we must create our spider, this is done by creating a class which inherits from scrapy.Spider. scrapy.Spider is the most basic spider that we must derive from in all scrapy projects. With this, we have to give this spider a name for it to run/ Spiders will require a couple of functions and an URL to scrape but for this example, we will omit this for the moment."
},
{
"code": null,
"e": 3979,
"s": 3725,
"text": "Now you see if __name__ == “__main__”. This is used as a best practice in python. When we write a script you want to it to be able to run the code but also be able to import that code somewhere else. Please see here for further discussion on this point."
},
{
"code": null,
"e": 4136,
"s": 3979,
"text": "We instantiate the class CrawlerProcess first to get access to the functions we want. CrawlerProcess has two functions we are interested in, crawl and start"
},
{
"code": null,
"e": 4308,
"s": 4136,
"text": "We use crawl to start the spider we created. We then use the start function to start a twisted reactor, the engine that processes and listens to our HTTP requests we want."
},
{
"code": null,
"e": 4797,
"s": 4308,
"text": "The scrapy framework provides a list of settings that it will use automatically, however for working with the Scrapy API we have to provide the settings explicitly. The settings we define is how we can customise our spiders. The spider.Spider class has a variable called custom_settings. Now this variable can be used to override the settings scrapy automatically uses. We have to create a dictionary of our settings to do this as the custom_settings variable is set to none using scrapy."
},
{
"code": null,
"e": 4975,
"s": 4797,
"text": "You may want to use some or most of the settings scrapy provides, in which case you could copy them from there. Alternatively, a list of the built-in settings can be found here."
},
{
"code": null,
"e": 5069,
"s": 4975,
"text": "class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 }"
},
{
"code": null,
"e": 5469,
"s": 5069,
"text": "We have shown how to create a spider and define the settings, but we haven’t specified any URLs to scrape, or how we want to specify the requests to the website we want to get data from. For example, parameters, headers and user-agents.When we create spider we also start a method called start_requests(). This will create the requests for any URL we want. Now there are two ways to use this method."
},
{
"code": null,
"e": 5560,
"s": 5469,
"text": "1) By defining the start_urls attribute 2) We implement our function called start_requests"
},
{
"code": null,
"e": 5753,
"s": 5560,
"text": "The shortest way is by defining start_urls. We define it as a list of URLs we want to get, by specifying this variable we automatically use start_requests() to go through each one of our URLs."
},
{
"code": null,
"e": 5879,
"s": 5753,
"text": "class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 } start_urls = ['URL1','URL2']"
},
{
"code": null,
"e": 6072,
"s": 5879,
"text": "However notice how if we do this, we can’t specify our headers, parameters or anything else we want to go along with the request? This is where implementing our start_requests method comes in."
},
{
"code": null,
"e": 6291,
"s": 6072,
"text": "First, we define our variables we want to go along with the request. We then implement our start_requests method so we can make use of the headers and parameters we want, as well as where we want to the response to go."
},
{
"code": null,
"e": 6512,
"s": 6291,
"text": "class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 } headers = {} params = {} def start_requests(self): yield scrapy.Requests(url, headers=headers, params=params)"
},
{
"code": null,
"e": 6655,
"s": 6512,
"text": "Here we access the Requests method which when given an URL will make the HTTP requests and return a response defined as the response variable."
},
{
"code": null,
"e": 6816,
"s": 6655,
"text": "You will notice how we didn’t specify a callback? That is we didn’t specify where scrapy should send the response to the requests we just told it to get for us."
},
{
"code": null,
"e": 6946,
"s": 6816,
"text": "Let’s fix that, by default scrapy expects the callback method to be the parse function but it could be anything we want it to be."
},
{
"code": null,
"e": 7244,
"s": 6946,
"text": "class TestSpider(scrapy.Spider): name = 'test' custom_settings = { 'DOWNLOD_DELAY': 1 } headers = {} params = {} def start_requests(self): yield scrapy.Requests(url, headers=headers, params=params,callback = self.parse) def parse(self,response): print(response.body)"
},
{
"code": null,
"e": 7435,
"s": 7244,
"text": "Here we have defined the function parse which accepts a response variable, remember this is created when we ask scrapy to do the HTTP requests. We then ask scrapy to print the response body."
},
{
"code": null,
"e": 7595,
"s": 7435,
"text": "With that, we now have the basics of running scrapy in a python script. We can use all the same methods but we just have to do a bit of configuring beforehand."
},
{
"code": null,
"e": 7922,
"s": 7595,
"text": "Why might you use the scrapy framework ? When is importing scrapy in a python script useful?What does the CrawlerProcess class do?Can you recall the basic script used to start scrapy within a python script?How do you add scrapy settings in your python script?Why might you use a start_requests function instead of start_urls ?"
},
{
"code": null,
"e": 8015,
"s": 7922,
"text": "Why might you use the scrapy framework ? When is importing scrapy in a python script useful?"
},
{
"code": null,
"e": 8054,
"s": 8015,
"text": "What does the CrawlerProcess class do?"
},
{
"code": null,
"e": 8131,
"s": 8054,
"text": "Can you recall the basic script used to start scrapy within a python script?"
},
{
"code": null,
"e": 8185,
"s": 8131,
"text": "How do you add scrapy settings in your python script?"
},
{
"code": null,
"e": 8253,
"s": 8185,
"text": "Why might you use a start_requests function instead of start_urls ?"
},
{
"code": null,
"e": 8424,
"s": 8253,
"text": "Please see here for further details about what I’m up to project-wise on my blog and other posts.For more tech/coding related content please sign up to my newsletter here"
}
] |
\def - Tex Command | \def - Used for defining your own commands.
{ \def\myCommandName{ <replacement text> } }
\def command is used to define your own commands (control sequences, macros, definitions); must appear (within math delimiters) before it is used;
\def\myHearts{\color{purple}{\heartsuit}\kern-2.5pt\color{green}{\heartsuit}}
\myHearts\myHearts
♡♡♡♡
\def\myHearts#1#2{\color{#1}{\heartsuit}\kern-2.5pt\color{#2}{\heartsuit}}
\myHearts{red}{blue}
♡♡
\def\myHearts{\color{purple}{\heartsuit}\kern-2.5pt\color{green}{\heartsuit}}
\myHearts\myHearts
♡♡♡♡
\def\myHearts{\color{purple}{\heartsuit}\kern-2.5pt\color{green}{\heartsuit}}
\myHearts\myHearts
\def\myHearts#1#2{\color{#1}{\heartsuit}\kern-2.5pt\color{#2}{\heartsuit}}
\myHearts{red}{blue}
♡♡
\def\myHearts#1#2{\color{#1}{\heartsuit}\kern-2.5pt\color{#2}{\heartsuit}}
\myHearts{red}{blue}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8030,
"s": 7986,
"text": "\\def - Used for defining your own commands."
},
{
"code": null,
"e": 8075,
"s": 8030,
"text": "{ \\def\\myCommandName{ <replacement text> } }"
},
{
"code": null,
"e": 8222,
"s": 8075,
"text": "\\def command is used to define your own commands (control sequences, macros, definitions); must appear (within math delimiters) before it is used;"
},
{
"code": null,
"e": 8433,
"s": 8222,
"text": "\n\\def\\myHearts{\\color{purple}{\\heartsuit}\\kern-2.5pt\\color{green}{\\heartsuit}}\n\\myHearts\\myHearts\n\n\n♡♡♡♡\n\n\n\\def\\myHearts#1#2{\\color{#1}{\\heartsuit}\\kern-2.5pt\\color{#2}{\\heartsuit}}\n\\myHearts{red}{blue}\n\n\n♡♡\n\n\n"
},
{
"code": null,
"e": 8539,
"s": 8433,
"text": "\\def\\myHearts{\\color{purple}{\\heartsuit}\\kern-2.5pt\\color{green}{\\heartsuit}}\n\\myHearts\\myHearts\n\n\n♡♡♡♡\n\n"
},
{
"code": null,
"e": 8637,
"s": 8539,
"text": "\\def\\myHearts{\\color{purple}{\\heartsuit}\\kern-2.5pt\\color{green}{\\heartsuit}}\n\\myHearts\\myHearts\n"
},
{
"code": null,
"e": 8740,
"s": 8637,
"text": "\\def\\myHearts#1#2{\\color{#1}{\\heartsuit}\\kern-2.5pt\\color{#2}{\\heartsuit}}\n\\myHearts{red}{blue}\n\n\n♡♡\n\n"
},
{
"code": null,
"e": 8837,
"s": 8740,
"text": "\\def\\myHearts#1#2{\\color{#1}{\\heartsuit}\\kern-2.5pt\\color{#2}{\\heartsuit}}\n\\myHearts{red}{blue}\n"
},
{
"code": null,
"e": 8869,
"s": 8837,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8882,
"s": 8869,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8915,
"s": 8882,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8928,
"s": 8915,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8960,
"s": 8928,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8996,
"s": 8960,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 9031,
"s": 8996,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9048,
"s": 9031,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 9081,
"s": 9048,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9095,
"s": 9081,
"text": " Daniel Stern"
},
{
"code": null,
"e": 9127,
"s": 9095,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 9142,
"s": 9127,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 9149,
"s": 9142,
"text": " Print"
},
{
"code": null,
"e": 9160,
"s": 9149,
"text": " Add Notes"
}
] |
Logging in SAP using command line | sapshcut.exe command can be used to log in to SAP from command line as shown in below example:
Add the directory that contains the sapshcut.exe command to your system or user path. The sapshcut.exe command is installed as part of the SAP client into the following directory: C:\Program Files\SAP\FrontEnd\SAPguiTo add additional directories to the system or user path on Windows systems, select Control Panel > System > Advanced > Environment Variables.The .bat file must be named sapshcut.bat must be located in your default path preceding the sapshcut.exe file.The following parameters are passed to the sapshcut.bat file when called from a predefined Launch definition −
%1
keyword "-command"
%2
transaction_name, for example: SM13
%3
keyword "-system"
%4
SAP_system_identifier, for example: TV1
%5
keyword "-client"
%6
client_number, for example: 100
The following example shows a sample sapshcut.cmd file. In this example, you use a different user ID and password when sapshcut is run through the Application Launch for the system TV1. All other SAP systems use the default logon parameters.
@echo off set sapshcut="C:\Program Files\SAP\FrontEnd\SAPgui\sapshcut.exe"
if "%4" == "TV1" (
%sapshcut% %* -user=myid -password=mypwd
) else (
%sapshcut% %*
) | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "sapshcut.exe command can be used to log in to SAP from command line as shown in below example:"
},
{
"code": null,
"e": 1737,
"s": 1157,
"text": "Add the directory that contains the sapshcut.exe command to your system or user path. The sapshcut.exe command is installed as part of the SAP client into the following directory: C:\\Program Files\\SAP\\FrontEnd\\SAPguiTo add additional directories to the system or user path on Windows systems, select Control Panel > System > Advanced > Environment Variables.The .bat file must be named sapshcut.bat must be located in your default path preceding the sapshcut.exe file.The following parameters are passed to the sapshcut.bat file when called from a predefined Launch definition −"
},
{
"code": null,
"e": 1923,
"s": 1737,
"text": "%1\nkeyword \"-command\"\n\n%2\ntransaction_name, for example: SM13\n\n%3\nkeyword \"-system\"\n\n%4\nSAP_system_identifier, for example: TV1\n\n%5\n\nkeyword \"-client\"\n%6\nclient_number, for example: 100"
},
{
"code": null,
"e": 2165,
"s": 1923,
"text": "The following example shows a sample sapshcut.cmd file. In this example, you use a different user ID and password when sapshcut is run through the Application Launch for the system TV1. All other SAP systems use the default logon parameters."
},
{
"code": null,
"e": 2331,
"s": 2165,
"text": "@echo off set sapshcut=\"C:\\Program Files\\SAP\\FrontEnd\\SAPgui\\sapshcut.exe\"\nif \"%4\" == \"TV1\" (\n %sapshcut% %* -user=myid -password=mypwd\n) else (\n %sapshcut% %*\n)"
}
] |
Find closest smaller value for every element in array in C++ | Here we will see how to find the closest value for every element in an array. If an element x has the next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1.
To solve this, we will use the settings in C++ STL. The set is implemented using the binary tree approach. In binary tree always the in-order successor is the next larger element. So we can get the element in O(log n) time.
Live Demo
#include<iostream>
#include<set>
using namespace std;
void nearestGreatest(int arr[], int n) {
set<int> tempSet;
for (int i = 0; i < n; i++)
tempSet.insert(arr[i]);
for (int i = 0; i < n; i++) {
auto next_greater = tempSet.upper_bound(arr[i]);
if (next_greater == tempSet.end())
cout << -1 << " ";
else
cout << *next_greater << " ";
}
}
int main() {
int arr[] = {10, 5, 11, 6, 20, 12};
int n = sizeof(arr) / sizeof(arr[0]);
nearestGreatest(arr, n);
}
11 6 12 10 -1 20 | [
{
"code": null,
"e": 1499,
"s": 1062,
"text": "Here we will see how to find the closest value for every element in an array. If an element x has the next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1."
},
{
"code": null,
"e": 1723,
"s": 1499,
"text": "To solve this, we will use the settings in C++ STL. The set is implemented using the binary tree approach. In binary tree always the in-order successor is the next larger element. So we can get the element in O(log n) time."
},
{
"code": null,
"e": 1734,
"s": 1723,
"text": " Live Demo"
},
{
"code": null,
"e": 2248,
"s": 1734,
"text": "#include<iostream>\n#include<set>\nusing namespace std;\nvoid nearestGreatest(int arr[], int n) {\n set<int> tempSet;\n for (int i = 0; i < n; i++)\n tempSet.insert(arr[i]);\n for (int i = 0; i < n; i++) {\n auto next_greater = tempSet.upper_bound(arr[i]);\n if (next_greater == tempSet.end())\n cout << -1 << \" \";\n else\n cout << *next_greater << \" \";\n }\n}\nint main() {\n int arr[] = {10, 5, 11, 6, 20, 12};\n int n = sizeof(arr) / sizeof(arr[0]);\n nearestGreatest(arr, n);\n}"
},
{
"code": null,
"e": 2265,
"s": 2248,
"text": "11 6 12 10 -1 20"
}
] |
C# | String Concat with examples | Set-3 - GeeksforGeeks | 01 Feb, 2019
String.Concat Method is used to concatenate one or more instances of String or the String representations of the values of one or more instances of Object. It always returns a concatenated string.This method can be overloaded by passing different types and number of parameters to it. There are total 11 methods in the overload list of the Concat method in which first 6 are discussed in Set-1 & Set-2 and remaining are discussed in Set-3 and Set-4.
This method is used to concatenate the string representations of the elements in a specified Object array.
Note: If an array contains a null object, then String.Empty is used in place of a null object.
Syntax:
public static string Concat (params object[] arg);
Here, arg is an object array that contains the elements to concatenate.
Return Value: The return type of this method is System.String. This method returns the concatenated string that represents the values of the elements present in arg.
Exception:
If the value of the given arg is null then this method will give ArgumentNullException.
If the array is out of memory, then this method will give OutOfMemoryException.
Example:
// C# program to illustrate // the Concat(object[]) Methodusing System; // class declarationclass EmptyA { } class GFG { // Main method public static void Main() { // creating object of EmptyA class EmptyA g1 = new EmptyA(); string strA = " GeeksforGeeks "; object[] ob = {21, " Hello!", strA, g1}; // print elements of object array // using Concat(object[]) Method Console.WriteLine("Elements of object array : {0}", string.Concat(ob)); }}
Output:
Elements of object array : 21 Hello! GeeksforGeeks EmptyA
This method is used to create the string representation of a specified object.
Syntax:
public static string Concat (object argA);
Here, argA is the object to represent, or null.
Return Value: The return type of this method is System.String. This method returns the concatenated string that represents the values of the elements present in argA, or Empty if the argA is null.
Example:
// C# program to illustrate the// Concat(object) Methodusing System; class GFG { // Main method public static void Main() { // string string strA = "Geeks"; // assigning string to object object ob = strA; // object array Object[] objs = new Object[] {"1", "2"}; // using Concat(object) method Console.WriteLine("Concatenate 1, 2, and 3 objects:"); Console.WriteLine("1: {0}", String.Concat(ob)); Console.WriteLine("2: {0}", String.Concat(ob, ob)); Console.WriteLine("3: {0}", String.Concat(ob, ob, ob)); Console.WriteLine("Concatenate two element object array: {0}", String.Concat(objs)); }}
Output:
Concatenate 1, 2, and 3 objects:
1: Geeks
2: GeeksGeeks
3: GeeksGeeksGeeks
Concatenate two element object array: 12
This method is used to Concatenates the string representations of two specified objects.
Syntax:
public static string Concat (object argA, object argB);
Parameters:
argA: First object to concatenate.argB: Second object to concatenate.
Return Value: The return type of this method is System.String. The concatenated string is the representation of each value present in the parameter list.
Example:
// C# program to illustrate// Concat(object, object) Methodusing System; class GFG { // Main method public static void Main() { // string string strA = "50"; // object object ob = strA; // object array Object[] objs = new Object[] {"34", "87"}; // Concatenating two objects // using Concat(object, object) method Console.WriteLine("Concatenate two objects: {0}", String.Concat(ob, ob)); Console.WriteLine("Concatenate two element object array: {0}", String.Concat(objs)); }}
Output:
Concatenate two objects: 5050
Concatenate two element object array: 3487
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.concat?view=netframework-4.7.2
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24752,
"s": 24302,
"text": "String.Concat Method is used to concatenate one or more instances of String or the String representations of the values of one or more instances of Object. It always returns a concatenated string.This method can be overloaded by passing different types and number of parameters to it. There are total 11 methods in the overload list of the Concat method in which first 6 are discussed in Set-1 & Set-2 and remaining are discussed in Set-3 and Set-4."
},
{
"code": null,
"e": 24859,
"s": 24752,
"text": "This method is used to concatenate the string representations of the elements in a specified Object array."
},
{
"code": null,
"e": 24954,
"s": 24859,
"text": "Note: If an array contains a null object, then String.Empty is used in place of a null object."
},
{
"code": null,
"e": 24962,
"s": 24954,
"text": "Syntax:"
},
{
"code": null,
"e": 25013,
"s": 24962,
"text": "public static string Concat (params object[] arg);"
},
{
"code": null,
"e": 25085,
"s": 25013,
"text": "Here, arg is an object array that contains the elements to concatenate."
},
{
"code": null,
"e": 25251,
"s": 25085,
"text": "Return Value: The return type of this method is System.String. This method returns the concatenated string that represents the values of the elements present in arg."
},
{
"code": null,
"e": 25262,
"s": 25251,
"text": "Exception:"
},
{
"code": null,
"e": 25350,
"s": 25262,
"text": "If the value of the given arg is null then this method will give ArgumentNullException."
},
{
"code": null,
"e": 25430,
"s": 25350,
"text": "If the array is out of memory, then this method will give OutOfMemoryException."
},
{
"code": null,
"e": 25439,
"s": 25430,
"text": "Example:"
},
{
"code": "// C# program to illustrate // the Concat(object[]) Methodusing System; // class declarationclass EmptyA { } class GFG { // Main method public static void Main() { // creating object of EmptyA class EmptyA g1 = new EmptyA(); string strA = \" GeeksforGeeks \"; object[] ob = {21, \" Hello!\", strA, g1}; // print elements of object array // using Concat(object[]) Method Console.WriteLine(\"Elements of object array : {0}\", string.Concat(ob)); }}",
"e": 26002,
"s": 25439,
"text": null
},
{
"code": null,
"e": 26010,
"s": 26002,
"text": "Output:"
},
{
"code": null,
"e": 26068,
"s": 26010,
"text": "Elements of object array : 21 Hello! GeeksforGeeks EmptyA"
},
{
"code": null,
"e": 26147,
"s": 26068,
"text": "This method is used to create the string representation of a specified object."
},
{
"code": null,
"e": 26155,
"s": 26147,
"text": "Syntax:"
},
{
"code": null,
"e": 26198,
"s": 26155,
"text": "public static string Concat (object argA);"
},
{
"code": null,
"e": 26246,
"s": 26198,
"text": "Here, argA is the object to represent, or null."
},
{
"code": null,
"e": 26443,
"s": 26246,
"text": "Return Value: The return type of this method is System.String. This method returns the concatenated string that represents the values of the elements present in argA, or Empty if the argA is null."
},
{
"code": null,
"e": 26452,
"s": 26443,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Concat(object) Methodusing System; class GFG { // Main method public static void Main() { // string string strA = \"Geeks\"; // assigning string to object object ob = strA; // object array Object[] objs = new Object[] {\"1\", \"2\"}; // using Concat(object) method Console.WriteLine(\"Concatenate 1, 2, and 3 objects:\"); Console.WriteLine(\"1: {0}\", String.Concat(ob)); Console.WriteLine(\"2: {0}\", String.Concat(ob, ob)); Console.WriteLine(\"3: {0}\", String.Concat(ob, ob, ob)); Console.WriteLine(\"Concatenate two element object array: {0}\", String.Concat(objs)); }}",
"e": 27159,
"s": 26452,
"text": null
},
{
"code": null,
"e": 27167,
"s": 27159,
"text": "Output:"
},
{
"code": null,
"e": 27284,
"s": 27167,
"text": "Concatenate 1, 2, and 3 objects:\n1: Geeks\n2: GeeksGeeks\n3: GeeksGeeksGeeks\nConcatenate two element object array: 12\n"
},
{
"code": null,
"e": 27373,
"s": 27284,
"text": "This method is used to Concatenates the string representations of two specified objects."
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Syntax:"
},
{
"code": null,
"e": 27437,
"s": 27381,
"text": "public static string Concat (object argA, object argB);"
},
{
"code": null,
"e": 27449,
"s": 27437,
"text": "Parameters:"
},
{
"code": null,
"e": 27519,
"s": 27449,
"text": "argA: First object to concatenate.argB: Second object to concatenate."
},
{
"code": null,
"e": 27673,
"s": 27519,
"text": "Return Value: The return type of this method is System.String. The concatenated string is the representation of each value present in the parameter list."
},
{
"code": null,
"e": 27682,
"s": 27673,
"text": "Example:"
},
{
"code": "// C# program to illustrate// Concat(object, object) Methodusing System; class GFG { // Main method public static void Main() { // string string strA = \"50\"; // object object ob = strA; // object array Object[] objs = new Object[] {\"34\", \"87\"}; // Concatenating two objects // using Concat(object, object) method Console.WriteLine(\"Concatenate two objects: {0}\", String.Concat(ob, ob)); Console.WriteLine(\"Concatenate two element object array: {0}\", String.Concat(objs)); }}",
"e": 28371,
"s": 27682,
"text": null
},
{
"code": null,
"e": 28379,
"s": 28371,
"text": "Output:"
},
{
"code": null,
"e": 28453,
"s": 28379,
"text": "Concatenate two objects: 5050\nConcatenate two element object array: 3487\n"
},
{
"code": null,
"e": 28553,
"s": 28453,
"text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.concat?view=netframework-4.7.2"
},
{
"code": null,
"e": 28567,
"s": 28553,
"text": "CSharp-string"
},
{
"code": null,
"e": 28570,
"s": 28567,
"text": "C#"
},
{
"code": null,
"e": 28668,
"s": 28570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28686,
"s": 28668,
"text": "Destructors in C#"
},
{
"code": null,
"e": 28709,
"s": 28686,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28737,
"s": 28709,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28777,
"s": 28737,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28820,
"s": 28777,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28842,
"s": 28820,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28859,
"s": 28842,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28875,
"s": 28859,
"text": "C# | List Class"
},
{
"code": null,
"e": 28925,
"s": 28875,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
Python List extend() Method - GeeksforGeeks | 05 Aug, 2021
The Python’s List extend() method iterates over an iterable like string, list, tuple, etc., and adds each element of the iterable to the end of List. The length of the list increases by the number of elements present in the iterable.
Syntax: list.extend(iterable)
Parameters:
iterable: Any iterable (list, set, tuple, etc.)
Returns:
The extend() method modifies the original list. It doesn’t return any value.
Python
# my_listmy_list = ['geeks', 'for'] # Another listanother_list = [6, 0, 4, 1] # Using extend() methodmy_list.extend(another_list) print my_list
Output:
['geeks', 'for', 6, 0, 4, 1]
Python
# My Listmy_list = ['geeks', 'for', 'geeks'] # My Tuplemy_tuple = ('DSA', 'Java') # My Setmy_set = {'Flutter', 'Android'} # Append tuple to the listmy_list.extend(my_tuple) print(my_list) # Append set to the listmy_list.extend(my_set) print(my_list)
Output:
['geeks', 'for', 'geeks', 'DSA', 'Java']
['geeks', 'for', 'geeks', 'DSA', 'Java', 'Android', 'Flutter']
A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string.
Python
# My listmy_list = ['geeks', 'for', 6, 0, 4, 1] # My stringmy_list.extend('geeks') print my_list
Output:
['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']
nikhilaggarwal3
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 24135,
"s": 23901,
"text": "The Python’s List extend() method iterates over an iterable like string, list, tuple, etc., and adds each element of the iterable to the end of List. The length of the list increases by the number of elements present in the iterable."
},
{
"code": null,
"e": 24165,
"s": 24135,
"text": "Syntax: list.extend(iterable)"
},
{
"code": null,
"e": 24177,
"s": 24165,
"text": "Parameters:"
},
{
"code": null,
"e": 24225,
"s": 24177,
"text": "iterable: Any iterable (list, set, tuple, etc.)"
},
{
"code": null,
"e": 24234,
"s": 24225,
"text": "Returns:"
},
{
"code": null,
"e": 24311,
"s": 24234,
"text": "The extend() method modifies the original list. It doesn’t return any value."
},
{
"code": null,
"e": 24318,
"s": 24311,
"text": "Python"
},
{
"code": "# my_listmy_list = ['geeks', 'for'] # Another listanother_list = [6, 0, 4, 1] # Using extend() methodmy_list.extend(another_list) print my_list",
"e": 24465,
"s": 24318,
"text": null
},
{
"code": null,
"e": 24473,
"s": 24465,
"text": "Output:"
},
{
"code": null,
"e": 24502,
"s": 24473,
"text": "['geeks', 'for', 6, 0, 4, 1]"
},
{
"code": null,
"e": 24509,
"s": 24502,
"text": "Python"
},
{
"code": "# My Listmy_list = ['geeks', 'for', 'geeks'] # My Tuplemy_tuple = ('DSA', 'Java') # My Setmy_set = {'Flutter', 'Android'} # Append tuple to the listmy_list.extend(my_tuple) print(my_list) # Append set to the listmy_list.extend(my_set) print(my_list)",
"e": 24765,
"s": 24509,
"text": null
},
{
"code": null,
"e": 24773,
"s": 24765,
"text": "Output:"
},
{
"code": null,
"e": 24877,
"s": 24773,
"text": "['geeks', 'for', 'geeks', 'DSA', 'Java']\n['geeks', 'for', 'geeks', 'DSA', 'Java', 'Android', 'Flutter']"
},
{
"code": null,
"e": 24999,
"s": 24877,
"text": "A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string."
},
{
"code": null,
"e": 25006,
"s": 24999,
"text": "Python"
},
{
"code": "# My listmy_list = ['geeks', 'for', 6, 0, 4, 1] # My stringmy_list.extend('geeks') print my_list",
"e": 25105,
"s": 25006,
"text": null
},
{
"code": null,
"e": 25113,
"s": 25105,
"text": "Output:"
},
{
"code": null,
"e": 25167,
"s": 25113,
"text": "['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']"
},
{
"code": null,
"e": 25183,
"s": 25167,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 25195,
"s": 25183,
"text": "python-list"
},
{
"code": null,
"e": 25217,
"s": 25195,
"text": "python-list-functions"
},
{
"code": null,
"e": 25224,
"s": 25217,
"text": "Python"
},
{
"code": null,
"e": 25236,
"s": 25224,
"text": "python-list"
},
{
"code": null,
"e": 25334,
"s": 25236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25343,
"s": 25334,
"text": "Comments"
},
{
"code": null,
"e": 25356,
"s": 25343,
"text": "Old Comments"
},
{
"code": null,
"e": 25392,
"s": 25356,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 25431,
"s": 25392,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25454,
"s": 25431,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25505,
"s": 25454,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 25537,
"s": 25505,
"text": "Python Dictionary keys() method"
},
{
"code": null,
"e": 25553,
"s": 25537,
"text": "loops in python"
},
{
"code": null,
"e": 25594,
"s": 25553,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 25643,
"s": 25594,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 25676,
"s": 25643,
"text": "Python | Convert set into a list"
}
] |
Build a Text Generator Web App in under 50 Lines of Python | by Dev Sharma | Towards Data Science | We will be using OpenAI’s GPT-2 as the model and Panel as the web dashboard framework. This guide will be split into two parts. In the first part, we will load our model and write a predictions function. In the second, we will build the web application.
This tutorial assumes you already have Python 3.7+ installed and have some understanding of Language Models. Although the steps involved can be done outside of Jupyter, using a jupyter notebook is highly highly recommended.
We will be using PyTorch as our Deep Learning library of choice. Within PyTorch, we will use the transformers library to import the pre-trained OpenGPT-2 model. You can install these libraries by individually entering the following commands in your bash:
pip install torchpip install transformers
For our web application, we will be utilizing Panel, a great tool for easily creating servable dashboards from either jupyter notebooks or a regular python script. Use the following command to install panel:
pip install panel
OpenAI’s GPT is a type of transformer model which has received a lot of buzz about its capabilities to produce human-like text. If you have not experimented with it before, you are likely to come away with the same opinion at the end of this read.
First, we need to import the required packages.
import numpy as npimport torchimport torch.nn.functional as Ffrom transformers import GPT2Tokenizer, GPT2LMHeadModelfrom random import choice
Next, we will load the OpenGPT2 Tokenizer and the Language Model: (it may take a few minutes to download the pre-trained model if run for the first time)
tok = GPT2Tokenizer.from_pretrained("gpt2")model = GPT2LMHeadModel.from_pretrained("gpt2")
At this stage, most of the work in already done. Since our model is pre-trained, we don’t need to train it or make any modifications. We simply need to write a function which can input text to the model and generate a prediction.
def get_pred(text, model, tok, p=0.7): input_ids = torch.tensor(tok.encode(text)).unsqueeze(0) logits = model(input_ids)[0][:, -1] probs = F.softmax(logits, dim=-1).squeeze() idxs = torch.argsort(probs, descending=True) res, cumsum = [], 0. for idx in idxs: res.append(idx) cumsum += probs[idx] if cumsum > p: pred_idx = idxs.new_tensor([choice(res)]) break pred = tok.convert_ids_to_tokens(int(pred_idx)) return tok.convert_tokens_to_string(pred)
There is a lot happening in this function. So, let’s break it down. First, we are tokenizing and encoding the input text from input_ids. Then, we ask our model to generate a logits vector for the next word/token. After applying softmax and sorting these probabilities in descending order, we have a vector, idxs, which lists the indices of each token in our vocab in order by their respective probabilities.
At this stage, we could just pick the token which has the highest probability. However, we want to be able to mix up our results so the same input text can generate a variety of text. To do this, we will add an element of randomness where we choose a random token from a list of the most probable next tokens. This way, we are not selecting the same predicted token each time. To do this, we utilize Nucleus (Top-p) Sampling.
We perform this by looping through each probability until the sum of all the probabilities we have looped over is greater than p, an arbitrary number between 0 and 1. All the tokens iterated through until p is exceeded are stored in a list, res. Once, p is exceeded, we choose a token at random from this list. Remember that the list of probabilities that we are looping through contains indices ordered by their probability. Note that if p is higher, more tokens will be included in our list. Vice versa. Therefore, if you want the same result each time, you can set p to 0.
Now, let’s test out our pred function a few times:
Each time, there is a different result which is exactly what we expect. Our prediction function is now ready. Let’s build our web app!
If you are not familiar with Panel, it facilitates the process of creating web dashboards and apps. At a first glance, what you need to know is that it has three primary components:
Panels: containers which can contain one or more of panes (objects) such as text, image, graphs, widgets etc. (they can contain other panels as well)
Panes: any single object such as text, image, dataframe, etc.
Widgets: user adjustable items such as text input, sliders, buttons, checkboxes which can alter the behavior of panes
The next and final thing you need to know for our purpose is that there are multiple ways for us to define how different panes and widgets interact with each other. These are called “callbacks.” For example, if a certain button is pressed, how should the other panes be updated? We will be defining a callback function later on which does exactly this.
Our text generator app will have an input for a user to enter their desired text. Next, the user should be able to generate a new token with a press of a button. After which, new text will be generated with a predicted token from the function we defined in Part 1. Lastly, the user should be able to continue to generate new text on top of the already predicted tokens.
Let’s first import panel and create the text input widget:
import panel as pnpn.extension() # loading panel's extension for jupyter compatibility text_input = pn.widgets.TextInput()
Now, if we execute text_input in jupyter, we get the following:
Next, we want a pane which will store the whole text as we generate more and more tokens:
generated_text = pn.pane.Markdown(object=text_input.value)
Notice that we set the object of text to the value of text_input. We want the value of the generated_text to have the same value as the text_input since we will be predicting new text on top of the generated_text. As more tokens get added to our sequence, we will keep predicting over the generated_text until the user changes the text_input. In which case, the process will restart.
However, we are not quite done yet. Although generated_text will take the value of text_input at its initiation, it will not update itself if the text_input value changes. For this, we need to link these two objects together as so:
text_input.link(generated_text, value='object')
Here, we have formed a unidirectional link between text_input to generated_text. So whenever the value of the text_input changes, the value of generated_text is changed to the new value as well. See:
Now that we have both our text objects, let’s create our button widget:
button = pn.widgets.Button(name="Generate",button_type="primary")
Great, now that we have a button, we just have to link it to our desired behavior. For this we will be writing a callback function which will run every time the button is clicked:
def click_cb(event): pred = get_pred(generated_text.object, model, tok) generated_text.object += pred
Two things happen here. First, we pass generated_text as the input to the prediction function we wrote earlier which gives a new token. Second, this token is added to the generated_text. This process repeats each time there is a new click of the button.
Speaking of, we still have to tie the button click with the callback function. We can do that with:
button.on_click(click_cb)
We are now through creating all our widgets, panes and functions. We just need to put these objects in a panel and voila:
app = pn.Column(text_input, button, generated_text); app
Let’s add a title and a brief description and we are through!
title = pn.pane.Markdown("# **Text Generator**")desc = pn.pane.HTML("<marquee scrollamount='10'><b>Welcome to the text generator! In order to get started, simply enter some starting input text below, click generate a few times and watch it go!</b></marquee>")final_app = pn.Column(title, desc ,app)
Panel makes it very easy to serve the app. There are two methods which can be used to do this. The first one is the “.show()” command. This is used for debugging usually and it is used as below. This will launch a new window with our final_app panel running as a web application.
final_app.show()
In order to put it in a production environment, you need to use the “.servable()” method. However, if you run this similarly to the show method, nothing different will happen in your current notebook. Instead, you have to serve the notebook through your machine’s bash like this:
panel serve --show text_generation_app.ipynb
This will launch your app on a local port as long as you have the following code in your notebook:
final_app.servable()
Done.
By now, you have the capabilities to build your own text generation app. You can further build upon it by adding more panel components. You can even embed this app in your other projects. As always, you can find my code base on github. Note: the app in the title image is the advanced variation found in my tutorial notebook: text_generation_app.ipynb.
github.com
OpenAI GPT-2: Understanding Language Generation through Visualization
Getting Started with Panel
Visualize any Data Easily, from Notebooks to Dashboards | Scipy 2019 Tutorial | James Bednar (Video: first hour is about Panel)
Deploying Panel Apps on a Server | [
{
"code": null,
"e": 426,
"s": 172,
"text": "We will be using OpenAI’s GPT-2 as the model and Panel as the web dashboard framework. This guide will be split into two parts. In the first part, we will load our model and write a predictions function. In the second, we will build the web application."
},
{
"code": null,
"e": 650,
"s": 426,
"text": "This tutorial assumes you already have Python 3.7+ installed and have some understanding of Language Models. Although the steps involved can be done outside of Jupyter, using a jupyter notebook is highly highly recommended."
},
{
"code": null,
"e": 905,
"s": 650,
"text": "We will be using PyTorch as our Deep Learning library of choice. Within PyTorch, we will use the transformers library to import the pre-trained OpenGPT-2 model. You can install these libraries by individually entering the following commands in your bash:"
},
{
"code": null,
"e": 947,
"s": 905,
"text": "pip install torchpip install transformers"
},
{
"code": null,
"e": 1155,
"s": 947,
"text": "For our web application, we will be utilizing Panel, a great tool for easily creating servable dashboards from either jupyter notebooks or a regular python script. Use the following command to install panel:"
},
{
"code": null,
"e": 1173,
"s": 1155,
"text": "pip install panel"
},
{
"code": null,
"e": 1421,
"s": 1173,
"text": "OpenAI’s GPT is a type of transformer model which has received a lot of buzz about its capabilities to produce human-like text. If you have not experimented with it before, you are likely to come away with the same opinion at the end of this read."
},
{
"code": null,
"e": 1469,
"s": 1421,
"text": "First, we need to import the required packages."
},
{
"code": null,
"e": 1611,
"s": 1469,
"text": "import numpy as npimport torchimport torch.nn.functional as Ffrom transformers import GPT2Tokenizer, GPT2LMHeadModelfrom random import choice"
},
{
"code": null,
"e": 1765,
"s": 1611,
"text": "Next, we will load the OpenGPT2 Tokenizer and the Language Model: (it may take a few minutes to download the pre-trained model if run for the first time)"
},
{
"code": null,
"e": 1856,
"s": 1765,
"text": "tok = GPT2Tokenizer.from_pretrained(\"gpt2\")model = GPT2LMHeadModel.from_pretrained(\"gpt2\")"
},
{
"code": null,
"e": 2086,
"s": 1856,
"text": "At this stage, most of the work in already done. Since our model is pre-trained, we don’t need to train it or make any modifications. We simply need to write a function which can input text to the model and generate a prediction."
},
{
"code": null,
"e": 2601,
"s": 2086,
"text": "def get_pred(text, model, tok, p=0.7): input_ids = torch.tensor(tok.encode(text)).unsqueeze(0) logits = model(input_ids)[0][:, -1] probs = F.softmax(logits, dim=-1).squeeze() idxs = torch.argsort(probs, descending=True) res, cumsum = [], 0. for idx in idxs: res.append(idx) cumsum += probs[idx] if cumsum > p: pred_idx = idxs.new_tensor([choice(res)]) break pred = tok.convert_ids_to_tokens(int(pred_idx)) return tok.convert_tokens_to_string(pred)"
},
{
"code": null,
"e": 3009,
"s": 2601,
"text": "There is a lot happening in this function. So, let’s break it down. First, we are tokenizing and encoding the input text from input_ids. Then, we ask our model to generate a logits vector for the next word/token. After applying softmax and sorting these probabilities in descending order, we have a vector, idxs, which lists the indices of each token in our vocab in order by their respective probabilities."
},
{
"code": null,
"e": 3435,
"s": 3009,
"text": "At this stage, we could just pick the token which has the highest probability. However, we want to be able to mix up our results so the same input text can generate a variety of text. To do this, we will add an element of randomness where we choose a random token from a list of the most probable next tokens. This way, we are not selecting the same predicted token each time. To do this, we utilize Nucleus (Top-p) Sampling."
},
{
"code": null,
"e": 4011,
"s": 3435,
"text": "We perform this by looping through each probability until the sum of all the probabilities we have looped over is greater than p, an arbitrary number between 0 and 1. All the tokens iterated through until p is exceeded are stored in a list, res. Once, p is exceeded, we choose a token at random from this list. Remember that the list of probabilities that we are looping through contains indices ordered by their probability. Note that if p is higher, more tokens will be included in our list. Vice versa. Therefore, if you want the same result each time, you can set p to 0."
},
{
"code": null,
"e": 4062,
"s": 4011,
"text": "Now, let’s test out our pred function a few times:"
},
{
"code": null,
"e": 4197,
"s": 4062,
"text": "Each time, there is a different result which is exactly what we expect. Our prediction function is now ready. Let’s build our web app!"
},
{
"code": null,
"e": 4379,
"s": 4197,
"text": "If you are not familiar with Panel, it facilitates the process of creating web dashboards and apps. At a first glance, what you need to know is that it has three primary components:"
},
{
"code": null,
"e": 4529,
"s": 4379,
"text": "Panels: containers which can contain one or more of panes (objects) such as text, image, graphs, widgets etc. (they can contain other panels as well)"
},
{
"code": null,
"e": 4591,
"s": 4529,
"text": "Panes: any single object such as text, image, dataframe, etc."
},
{
"code": null,
"e": 4709,
"s": 4591,
"text": "Widgets: user adjustable items such as text input, sliders, buttons, checkboxes which can alter the behavior of panes"
},
{
"code": null,
"e": 5062,
"s": 4709,
"text": "The next and final thing you need to know for our purpose is that there are multiple ways for us to define how different panes and widgets interact with each other. These are called “callbacks.” For example, if a certain button is pressed, how should the other panes be updated? We will be defining a callback function later on which does exactly this."
},
{
"code": null,
"e": 5432,
"s": 5062,
"text": "Our text generator app will have an input for a user to enter their desired text. Next, the user should be able to generate a new token with a press of a button. After which, new text will be generated with a predicted token from the function we defined in Part 1. Lastly, the user should be able to continue to generate new text on top of the already predicted tokens."
},
{
"code": null,
"e": 5491,
"s": 5432,
"text": "Let’s first import panel and create the text input widget:"
},
{
"code": null,
"e": 5614,
"s": 5491,
"text": "import panel as pnpn.extension() # loading panel's extension for jupyter compatibility text_input = pn.widgets.TextInput()"
},
{
"code": null,
"e": 5678,
"s": 5614,
"text": "Now, if we execute text_input in jupyter, we get the following:"
},
{
"code": null,
"e": 5768,
"s": 5678,
"text": "Next, we want a pane which will store the whole text as we generate more and more tokens:"
},
{
"code": null,
"e": 5827,
"s": 5768,
"text": "generated_text = pn.pane.Markdown(object=text_input.value)"
},
{
"code": null,
"e": 6211,
"s": 5827,
"text": "Notice that we set the object of text to the value of text_input. We want the value of the generated_text to have the same value as the text_input since we will be predicting new text on top of the generated_text. As more tokens get added to our sequence, we will keep predicting over the generated_text until the user changes the text_input. In which case, the process will restart."
},
{
"code": null,
"e": 6443,
"s": 6211,
"text": "However, we are not quite done yet. Although generated_text will take the value of text_input at its initiation, it will not update itself if the text_input value changes. For this, we need to link these two objects together as so:"
},
{
"code": null,
"e": 6491,
"s": 6443,
"text": "text_input.link(generated_text, value='object')"
},
{
"code": null,
"e": 6691,
"s": 6491,
"text": "Here, we have formed a unidirectional link between text_input to generated_text. So whenever the value of the text_input changes, the value of generated_text is changed to the new value as well. See:"
},
{
"code": null,
"e": 6763,
"s": 6691,
"text": "Now that we have both our text objects, let’s create our button widget:"
},
{
"code": null,
"e": 6829,
"s": 6763,
"text": "button = pn.widgets.Button(name=\"Generate\",button_type=\"primary\")"
},
{
"code": null,
"e": 7009,
"s": 6829,
"text": "Great, now that we have a button, we just have to link it to our desired behavior. For this we will be writing a callback function which will run every time the button is clicked:"
},
{
"code": null,
"e": 7117,
"s": 7009,
"text": "def click_cb(event): pred = get_pred(generated_text.object, model, tok) generated_text.object += pred"
},
{
"code": null,
"e": 7371,
"s": 7117,
"text": "Two things happen here. First, we pass generated_text as the input to the prediction function we wrote earlier which gives a new token. Second, this token is added to the generated_text. This process repeats each time there is a new click of the button."
},
{
"code": null,
"e": 7471,
"s": 7371,
"text": "Speaking of, we still have to tie the button click with the callback function. We can do that with:"
},
{
"code": null,
"e": 7497,
"s": 7471,
"text": "button.on_click(click_cb)"
},
{
"code": null,
"e": 7619,
"s": 7497,
"text": "We are now through creating all our widgets, panes and functions. We just need to put these objects in a panel and voila:"
},
{
"code": null,
"e": 7676,
"s": 7619,
"text": "app = pn.Column(text_input, button, generated_text); app"
},
{
"code": null,
"e": 7738,
"s": 7676,
"text": "Let’s add a title and a brief description and we are through!"
},
{
"code": null,
"e": 8037,
"s": 7738,
"text": "title = pn.pane.Markdown(\"# **Text Generator**\")desc = pn.pane.HTML(\"<marquee scrollamount='10'><b>Welcome to the text generator! In order to get started, simply enter some starting input text below, click generate a few times and watch it go!</b></marquee>\")final_app = pn.Column(title, desc ,app)"
},
{
"code": null,
"e": 8317,
"s": 8037,
"text": "Panel makes it very easy to serve the app. There are two methods which can be used to do this. The first one is the “.show()” command. This is used for debugging usually and it is used as below. This will launch a new window with our final_app panel running as a web application."
},
{
"code": null,
"e": 8334,
"s": 8317,
"text": "final_app.show()"
},
{
"code": null,
"e": 8614,
"s": 8334,
"text": "In order to put it in a production environment, you need to use the “.servable()” method. However, if you run this similarly to the show method, nothing different will happen in your current notebook. Instead, you have to serve the notebook through your machine’s bash like this:"
},
{
"code": null,
"e": 8659,
"s": 8614,
"text": "panel serve --show text_generation_app.ipynb"
},
{
"code": null,
"e": 8758,
"s": 8659,
"text": "This will launch your app on a local port as long as you have the following code in your notebook:"
},
{
"code": null,
"e": 8779,
"s": 8758,
"text": "final_app.servable()"
},
{
"code": null,
"e": 8785,
"s": 8779,
"text": "Done."
},
{
"code": null,
"e": 9138,
"s": 8785,
"text": "By now, you have the capabilities to build your own text generation app. You can further build upon it by adding more panel components. You can even embed this app in your other projects. As always, you can find my code base on github. Note: the app in the title image is the advanced variation found in my tutorial notebook: text_generation_app.ipynb."
},
{
"code": null,
"e": 9149,
"s": 9138,
"text": "github.com"
},
{
"code": null,
"e": 9219,
"s": 9149,
"text": "OpenAI GPT-2: Understanding Language Generation through Visualization"
},
{
"code": null,
"e": 9246,
"s": 9219,
"text": "Getting Started with Panel"
},
{
"code": null,
"e": 9374,
"s": 9246,
"text": "Visualize any Data Easily, from Notebooks to Dashboards | Scipy 2019 Tutorial | James Bednar (Video: first hour is about Panel)"
}
] |
Ruby on Rails - Controller | The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services.
It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well.
It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well.
It manages caching, which can give applications orders-of-magnitude performance boosts.
It manages caching, which can give applications orders-of-magnitude performance boosts.
It manages helper modules, which extend the capabilities of the view templates without bulking up their code.
It manages helper modules, which extend the capabilities of the view templates without bulking up their code.
It manages sessions, giving users the impression of an ongoing interaction with our applications.
It manages sessions, giving users the impression of an ongoing interaction with our applications.
The process for creating a controller is very easy, and it's similar to the process we've already used for creating a model. We will create just one controller here −
library\> rails generate controller Book
Notice that you are capitalizing Book and using the singular form. This is a Rails paradigm that you should follow each time you create a controller.
This command accomplishes several tasks, of which the following are relevant here −
It creates a file called app/controllers/book_controller.rb
It creates a file called app/controllers/book_controller.rb
If you look at book_controller.rb, you will find it as follows −
class BookController < ApplicationController
end
Controller classes inherit from ApplicationController, which is the other file in the controllers folder: application.rb.
The ApplicationController contains code that can be run in all your controllers and it inherits from Rails ActionController::Base class.
You don't need to worry with the ApplicationController as of yet, so let's just define a few method stubs in book_controller.rb. Based on your requirement, you could define any number of functions in this file.
Modify the file to look like the following and save your changes. Note that it is upto you what name you want to give to these methods, but better to give relevant names.
class BookController < ApplicationController
def list
end
def show
end
def new
end
def create
end
def edit
end
def update
end
def delete
end
end
Now let us implement all the methods one by one.
The list method gives you a list of all the books in the database. This functionality will be achieved by the following lines of code. Edit the following lines in book_controller.rb file.
def list
@books = Book.all
end
The @books = Book.all line in the list method tells Rails to search the books table and store each row it finds in the @books instance object.
The show method displays only further details on a single book. This functionality will be achieved by the following lines of code.
def show
@book = Book.find(params[:id])
end
The show method's @book = Book.find(params[:id]) line tells Rails to find only the book that has the id defined in params[:id].
The params object is a container that enables you to pass values between method calls. For example, when you're on the page called by the list method, you can click a link for a specific book, and it passes the id of that book via the params object so that show can find the specific book.
The new method lets Rails know that you will create a new object. So just add the following code in this method.
def new
@book = Book.new
@subjects = Subject.all
end
The above method will be called when you will display a page to the user to take user input. Here second line grabs all the subjects from the database and puts them in an array called @subjects.
Once you take user input using HTML form, it is time to create a record into the database. To achieve this, edit the create method in the book_controller.rb to match the following −
def create
@book = Book.new(book_params)
if @book.save
redirect_to :action => 'list'
else
@subjects = Subject.all
render :action => 'new'
end
end
def book_params
params.require(:books).permit(:title, :price, :subject_id, :description)
end
The first line creates a new instance variable called @book that holds a Book object built from the data, the user submitted. The book_params method is used to collect all the fields from object :books. The data was passed from the new method to create using the params object.
The next line is a conditional statement that redirects the user to the list method if the object saves correctly to the database. If it doesn't save, the user is sent back to the new method. The redirect_to method is similar to performing a meta refresh on a web page: it automatically forwards you to your destination without any user interaction.
Then @subjects = Subject.all is required in case it does not save data successfully and it becomes similar case as with new option.
The edit method looks nearly identical to the show method. Both methods are used to retrieve a single object based on its id and display it on a page. The only difference is that the show method is not editable.
def edit
@book = Book.find(params[:id])
@subjects = Subject.all
end
This method will be called to display data on the screen to be modified by the user. The second line grabs all the subjects from the database and puts them in an array called @subjects.
This method will be called after the edit method, when the user modifies a data and wants to update the changes into the database. The update method is similar to the create method and will be used to update existing books in the database.
def update
@book = Book.find(params[:id])
if @book.update_attributes(book_param)
redirect_to :action => 'show', :id => @book
else
@subjects = Subject.all
render :action => 'edit'
end
end
def book_param
params.require(:book).permit(:title, :price, :subject_id, :description)
end
The update_attributes method is similar to the save method used by create but instead of creating a new row in the database, it overwrites the attributes of the existing row.
Then @subjects = Subject.all line is required in case it does not save the data successfully, then it becomes similar to edit option.
If you want to delete a record from the database then you will use this method. Implement this method as follows.
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
The first line finds the classified based on the parameter passed via the params object and then deletes it using the destroy method. The second line redirects the user to the list method using a redirect_to call.
Assume you want to give a facility to your users to browse all the books based on a given subject. So, you can create a method inside book_controller.rb to display all the subjects. Assume the method name is show_subjects −
def show_subjects
@subject = Subject.find(params[:id])
end
Finally your book_controller.rb file will look as follows −
class BooksController < ApplicationController
def list
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@subjects = Subject.all
end
def book_params
params.require(:books).permit(:title, :price, :subject_id, :description)
end
def create
@book = Book.new(book_params)
if @book.save
redirect_to :action => 'list'
else
@subjects = Subject.all
render :action => 'new'
end
end
def edit
@book = Book.find(params[:id])
@subjects = Subject.all
end
def book_param
params.require(:book).permit(:title, :price, :subject_id, :description)
end
def update
@book = Book.find(params[:id])
if @book.update_attributes(book_param)
redirect_to :action => 'show', :id => @book
else
@subjects = Subject.all
render :action => 'edit'
end
end
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
def show_subjects
@subject = Subject.find(params[:id])
end
end
Now save your controller file.
You have created almost all the methods, which will work on backend. Next we will define routes (URLs) for actions.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2317,
"s": 2103,
"text": "The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services."
},
{
"code": null,
"e": 2434,
"s": 2317,
"text": "It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well."
},
{
"code": null,
"e": 2551,
"s": 2434,
"text": "It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well."
},
{
"code": null,
"e": 2639,
"s": 2551,
"text": "It manages caching, which can give applications orders-of-magnitude performance boosts."
},
{
"code": null,
"e": 2727,
"s": 2639,
"text": "It manages caching, which can give applications orders-of-magnitude performance boosts."
},
{
"code": null,
"e": 2837,
"s": 2727,
"text": "It manages helper modules, which extend the capabilities of the view templates without bulking up their code."
},
{
"code": null,
"e": 2947,
"s": 2837,
"text": "It manages helper modules, which extend the capabilities of the view templates without bulking up their code."
},
{
"code": null,
"e": 3045,
"s": 2947,
"text": "It manages sessions, giving users the impression of an ongoing interaction with our applications."
},
{
"code": null,
"e": 3143,
"s": 3045,
"text": "It manages sessions, giving users the impression of an ongoing interaction with our applications."
},
{
"code": null,
"e": 3310,
"s": 3143,
"text": "The process for creating a controller is very easy, and it's similar to the process we've already used for creating a model. We will create just one controller here −"
},
{
"code": null,
"e": 3352,
"s": 3310,
"text": "library\\> rails generate controller Book\n"
},
{
"code": null,
"e": 3502,
"s": 3352,
"text": "Notice that you are capitalizing Book and using the singular form. This is a Rails paradigm that you should follow each time you create a controller."
},
{
"code": null,
"e": 3586,
"s": 3502,
"text": "This command accomplishes several tasks, of which the following are relevant here −"
},
{
"code": null,
"e": 3646,
"s": 3586,
"text": "It creates a file called app/controllers/book_controller.rb"
},
{
"code": null,
"e": 3706,
"s": 3646,
"text": "It creates a file called app/controllers/book_controller.rb"
},
{
"code": null,
"e": 3771,
"s": 3706,
"text": "If you look at book_controller.rb, you will find it as follows −"
},
{
"code": null,
"e": 3821,
"s": 3771,
"text": "class BookController < ApplicationController\nend\n"
},
{
"code": null,
"e": 3943,
"s": 3821,
"text": "Controller classes inherit from ApplicationController, which is the other file in the controllers folder: application.rb."
},
{
"code": null,
"e": 4080,
"s": 3943,
"text": "The ApplicationController contains code that can be run in all your controllers and it inherits from Rails ActionController::Base class."
},
{
"code": null,
"e": 4291,
"s": 4080,
"text": "You don't need to worry with the ApplicationController as of yet, so let's just define a few method stubs in book_controller.rb. Based on your requirement, you could define any number of functions in this file."
},
{
"code": null,
"e": 4462,
"s": 4291,
"text": "Modify the file to look like the following and save your changes. Note that it is upto you what name you want to give to these methods, but better to give relevant names."
},
{
"code": null,
"e": 4677,
"s": 4462,
"text": "class BookController < ApplicationController\n def list\n end\n \n def show\n end\n \n def new\n end\n \n def create\n end\n \n def edit\n end\n \n def update\n end\n \n def delete\n end\n \nend"
},
{
"code": null,
"e": 4726,
"s": 4677,
"text": "Now let us implement all the methods one by one."
},
{
"code": null,
"e": 4914,
"s": 4726,
"text": "The list method gives you a list of all the books in the database. This functionality will be achieved by the following lines of code. Edit the following lines in book_controller.rb file."
},
{
"code": null,
"e": 4948,
"s": 4914,
"text": "def list\n @books = Book.all\nend"
},
{
"code": null,
"e": 5091,
"s": 4948,
"text": "The @books = Book.all line in the list method tells Rails to search the books table and store each row it finds in the @books instance object."
},
{
"code": null,
"e": 5223,
"s": 5091,
"text": "The show method displays only further details on a single book. This functionality will be achieved by the following lines of code."
},
{
"code": null,
"e": 5271,
"s": 5223,
"text": "def show\n @book = Book.find(params[:id])\nend\n"
},
{
"code": null,
"e": 5399,
"s": 5271,
"text": "The show method's @book = Book.find(params[:id]) line tells Rails to find only the book that has the id defined in params[:id]."
},
{
"code": null,
"e": 5689,
"s": 5399,
"text": "The params object is a container that enables you to pass values between method calls. For example, when you're on the page called by the list method, you can click a link for a specific book, and it passes the id of that book via the params object so that show can find the specific book."
},
{
"code": null,
"e": 5802,
"s": 5689,
"text": "The new method lets Rails know that you will create a new object. So just add the following code in this method."
},
{
"code": null,
"e": 5861,
"s": 5802,
"text": "def new\n @book = Book.new\n @subjects = Subject.all\nend"
},
{
"code": null,
"e": 6056,
"s": 5861,
"text": "The above method will be called when you will display a page to the user to take user input. Here second line grabs all the subjects from the database and puts them in an array called @subjects."
},
{
"code": null,
"e": 6238,
"s": 6056,
"text": "Once you take user input using HTML form, it is time to create a record into the database. To achieve this, edit the create method in the book_controller.rb to match the following −"
},
{
"code": null,
"e": 6517,
"s": 6238,
"text": "def create\n @book = Book.new(book_params)\n\t\n if @book.save\n redirect_to :action => 'list'\n else\n @subjects = Subject.all\n render :action => 'new'\n end\n \nend\n\ndef book_params\n params.require(:books).permit(:title, :price, :subject_id, :description)\nend"
},
{
"code": null,
"e": 6795,
"s": 6517,
"text": "The first line creates a new instance variable called @book that holds a Book object built from the data, the user submitted. The book_params method is used to collect all the fields from object :books. The data was passed from the new method to create using the params object."
},
{
"code": null,
"e": 7145,
"s": 6795,
"text": "The next line is a conditional statement that redirects the user to the list method if the object saves correctly to the database. If it doesn't save, the user is sent back to the new method. The redirect_to method is similar to performing a meta refresh on a web page: it automatically forwards you to your destination without any user interaction."
},
{
"code": null,
"e": 7277,
"s": 7145,
"text": "Then @subjects = Subject.all is required in case it does not save data successfully and it becomes similar case as with new option."
},
{
"code": null,
"e": 7489,
"s": 7277,
"text": "The edit method looks nearly identical to the show method. Both methods are used to retrieve a single object based on its id and display it on a page. The only difference is that the show method is not editable."
},
{
"code": null,
"e": 7563,
"s": 7489,
"text": "def edit\n @book = Book.find(params[:id])\n @subjects = Subject.all\nend"
},
{
"code": null,
"e": 7749,
"s": 7563,
"text": "This method will be called to display data on the screen to be modified by the user. The second line grabs all the subjects from the database and puts them in an array called @subjects."
},
{
"code": null,
"e": 7989,
"s": 7749,
"text": "This method will be called after the edit method, when the user modifies a data and wants to update the changes into the database. The update method is similar to the create method and will be used to update existing books in the database."
},
{
"code": null,
"e": 8307,
"s": 7989,
"text": "def update\n @book = Book.find(params[:id])\n\t\n if @book.update_attributes(book_param)\n redirect_to :action => 'show', :id => @book\n else\n @subjects = Subject.all\n render :action => 'edit'\n end\n \nend\n\ndef book_param\n params.require(:book).permit(:title, :price, :subject_id, :description)\nend"
},
{
"code": null,
"e": 8482,
"s": 8307,
"text": "The update_attributes method is similar to the save method used by create but instead of creating a new row in the database, it overwrites the attributes of the existing row."
},
{
"code": null,
"e": 8616,
"s": 8482,
"text": "Then @subjects = Subject.all line is required in case it does not save the data successfully, then it becomes similar to edit option."
},
{
"code": null,
"e": 8730,
"s": 8616,
"text": "If you want to delete a record from the database then you will use this method. Implement this method as follows."
},
{
"code": null,
"e": 8812,
"s": 8730,
"text": "def delete\n Book.find(params[:id]).destroy\n redirect_to :action => 'list'\nend"
},
{
"code": null,
"e": 9026,
"s": 8812,
"text": "The first line finds the classified based on the parameter passed via the params object and then deletes it using the destroy method. The second line redirects the user to the list method using a redirect_to call."
},
{
"code": null,
"e": 9250,
"s": 9026,
"text": "Assume you want to give a facility to your users to browse all the books based on a given subject. So, you can create a method inside book_controller.rb to display all the subjects. Assume the method name is show_subjects −"
},
{
"code": null,
"e": 9312,
"s": 9250,
"text": "def show_subjects\n @subject = Subject.find(params[:id])\nend"
},
{
"code": null,
"e": 9372,
"s": 9312,
"text": "Finally your book_controller.rb file will look as follows −"
},
{
"code": null,
"e": 10534,
"s": 9372,
"text": "class BooksController < ApplicationController\n\n def list\n @books = Book.all\n end\n\n def show\n @book = Book.find(params[:id])\n end\n \n def new\n @book = Book.new\n @subjects = Subject.all\n end\n\n def book_params\n params.require(:books).permit(:title, :price, :subject_id, :description)\n end\n\n def create\n @book = Book.new(book_params)\n\n if @book.save\n redirect_to :action => 'list'\n else\n @subjects = Subject.all\n render :action => 'new'\n end\n end\n \n def edit\n @book = Book.find(params[:id])\n @subjects = Subject.all\n end\n \n def book_param\n params.require(:book).permit(:title, :price, :subject_id, :description)\n end\n \n def update\n @book = Book.find(params[:id])\n \n if @book.update_attributes(book_param)\n redirect_to :action => 'show', :id => @book\n else\n @subjects = Subject.all\n render :action => 'edit'\n end\n end\n \n def delete\n Book.find(params[:id]).destroy\n redirect_to :action => 'list'\n end\n \n def show_subjects\n @subject = Subject.find(params[:id])\n end\n\nend"
},
{
"code": null,
"e": 10565,
"s": 10534,
"text": "Now save your controller file."
},
{
"code": null,
"e": 10681,
"s": 10565,
"text": "You have created almost all the methods, which will work on backend. Next we will define routes (URLs) for actions."
},
{
"code": null,
"e": 10688,
"s": 10681,
"text": " Print"
},
{
"code": null,
"e": 10699,
"s": 10688,
"text": " Add Notes"
}
] |
Difference between PUT and POST HTTP requests - GeeksforGeeks | 31 Aug, 2021
PUT and POST requests have lots of similarities certainly when making an HTTP request and both can be meddled with so that one performs functions of the other. This article revolves around the major differences between PUT and POST Requests.
PUT is a request method supported by HTTP used by the World Wide Web. The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI. Example – Let’s try making a request to httpbin’s APIs for example purposes.
Python3
import requests # Making a PUT requestr = requests.put('https://httpbin.org/put', data={'key':'value'}) #check status code for response received# success code - 200print(r) # print content of requestprint(r.content)
save this file as request.py and through terminal run,
python request.py
Output
POST HTTP Request
POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form. Example – Let’s try making a request to httpbin’s APIs for example purposes.
Python3
import requests # Making a POST requestr = requests.post('https://httpbin.org/post', data={'key':'value'}) #check status code for response received# success code - 200print(r) # print content of requestprint(r.json())
save this file as request.py and through terminal run,
python request.py
Output –
Difference between PUT and POST methods
PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). Example –
PUT /article/{article-id}
POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. Example –
POST /articles
ManasChhabra2
ruhelaa48
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python | [
{
"code": null,
"e": 25855,
"s": 25827,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 26098,
"s": 25855,
"text": "PUT and POST requests have lots of similarities certainly when making an HTTP request and both can be meddled with so that one performs functions of the other. This article revolves around the major differences between PUT and POST Requests. "
},
{
"code": null,
"e": 26505,
"s": 26098,
"text": "PUT is a request method supported by HTTP used by the World Wide Web. The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI. Example – Let’s try making a request to httpbin’s APIs for example purposes. "
},
{
"code": null,
"e": 26513,
"s": 26505,
"text": "Python3"
},
{
"code": "import requests # Making a PUT requestr = requests.put('https://httpbin.org/put', data={'key':'value'}) #check status code for response received# success code - 200print(r) # print content of requestprint(r.content)",
"e": 26729,
"s": 26513,
"text": null
},
{
"code": null,
"e": 26786,
"s": 26729,
"text": "save this file as request.py and through terminal run, "
},
{
"code": null,
"e": 26804,
"s": 26786,
"text": "python request.py"
},
{
"code": null,
"e": 26813,
"s": 26804,
"text": "Output "
},
{
"code": null,
"e": 26832,
"s": 26813,
"text": " POST HTTP Request"
},
{
"code": null,
"e": 27214,
"s": 26832,
"text": "POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form. Example – Let’s try making a request to httpbin’s APIs for example purposes. "
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Python3"
},
{
"code": "import requests # Making a POST requestr = requests.post('https://httpbin.org/post', data={'key':'value'}) #check status code for response received# success code - 200print(r) # print content of requestprint(r.json())",
"e": 27440,
"s": 27222,
"text": null
},
{
"code": null,
"e": 27497,
"s": 27440,
"text": "save this file as request.py and through terminal run, "
},
{
"code": null,
"e": 27515,
"s": 27497,
"text": "python request.py"
},
{
"code": null,
"e": 27525,
"s": 27515,
"text": "Output – "
},
{
"code": null,
"e": 27566,
"s": 27525,
"text": " Difference between PUT and POST methods"
},
{
"code": null,
"e": 27859,
"s": 27566,
"text": "PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). Example – "
},
{
"code": null,
"e": 27885,
"s": 27859,
"text": "PUT /article/{article-id}"
},
{
"code": null,
"e": 28157,
"s": 27887,
"text": "POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. Example – "
},
{
"code": null,
"e": 28172,
"s": 28157,
"text": "POST /articles"
},
{
"code": null,
"e": 28190,
"s": 28176,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 28200,
"s": 28190,
"text": "ruhelaa48"
},
{
"code": null,
"e": 28216,
"s": 28200,
"text": "Python-requests"
},
{
"code": null,
"e": 28223,
"s": 28216,
"text": "Python"
},
{
"code": null,
"e": 28321,
"s": 28223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28339,
"s": 28321,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28371,
"s": 28339,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28393,
"s": 28371,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28435,
"s": 28393,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28461,
"s": 28435,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28490,
"s": 28461,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28527,
"s": 28490,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28569,
"s": 28527,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28611,
"s": 28569,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
Python | Print Alphabets till N - GeeksforGeeks | 26 Nov, 2019
Sometimes, while working with Python, we can have a problem in which we need to print specific number of alphabets in order. This can have application in school level programming. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + chr()This is brute force way to perform this task. In this, we iterate the elements till which we need to print and concatenate the strings accordingly after conversion to character using chr().
# Python3 code to demonstrate working of# Print Alphabets till N# Using loop # initialize N N = 20 # printing N print("Number of elements required : " + str(N)) # Print Alphabets till N# Using loopres = ""for idx in range(97, 97 + N): res = res + chr(idx) # printing resultprint("Alphabets till N are : " + str(res))
Number of elements required : 20
Alphabets till N are : abcdefghijklmnopqrst
Method #2 : Using string.ascii_lowercase + slicingCombination of above functionalities can also be used to perform this task. In this, we use inbuilt function to get extract the lowercase string and extract the N characters using slicing.
# Python3 code to demonstrate working of# Print Alphabets till N# Using string.ascii_lowercase + slicingimport string # initialize N N = 20 # printing N print("Number of elements required : " + str(N)) # Print Alphabets till N# Using string.ascii_lowercase + slicingres = string.ascii_lowercase[:N] # printing resultprint("Alphabets till N are : " + str(res))
Number of elements required : 20
Alphabets till N are : abcdefghijklmnopqrst
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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25672,
"s": 25644,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 25916,
"s": 25672,
"text": "Sometimes, while working with Python, we can have a problem in which we need to print specific number of alphabets in order. This can have application in school level programming. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 26136,
"s": 25916,
"text": "Method #1 : Using loop + chr()This is brute force way to perform this task. In this, we iterate the elements till which we need to print and concatenate the strings accordingly after conversion to character using chr()."
},
{
"code": "# Python3 code to demonstrate working of# Print Alphabets till N# Using loop # initialize N N = 20 # printing N print(\"Number of elements required : \" + str(N)) # Print Alphabets till N# Using loopres = \"\"for idx in range(97, 97 + N): res = res + chr(idx) # printing resultprint(\"Alphabets till N are : \" + str(res))",
"e": 26468,
"s": 26136,
"text": null
},
{
"code": null,
"e": 26546,
"s": 26468,
"text": "Number of elements required : 20\nAlphabets till N are : abcdefghijklmnopqrst\n"
},
{
"code": null,
"e": 26787,
"s": 26548,
"text": "Method #2 : Using string.ascii_lowercase + slicingCombination of above functionalities can also be used to perform this task. In this, we use inbuilt function to get extract the lowercase string and extract the N characters using slicing."
},
{
"code": "# Python3 code to demonstrate working of# Print Alphabets till N# Using string.ascii_lowercase + slicingimport string # initialize N N = 20 # printing N print(\"Number of elements required : \" + str(N)) # Print Alphabets till N# Using string.ascii_lowercase + slicingres = string.ascii_lowercase[:N] # printing resultprint(\"Alphabets till N are : \" + str(res))",
"e": 27155,
"s": 26787,
"text": null
},
{
"code": null,
"e": 27233,
"s": 27155,
"text": "Number of elements required : 20\nAlphabets till N are : abcdefghijklmnopqrst\n"
},
{
"code": null,
"e": 27256,
"s": 27233,
"text": "Python string-programs"
},
{
"code": null,
"e": 27263,
"s": 27256,
"text": "Python"
},
{
"code": null,
"e": 27279,
"s": 27263,
"text": "Python Programs"
},
{
"code": null,
"e": 27377,
"s": 27279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27409,
"s": 27377,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27451,
"s": 27409,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27493,
"s": 27451,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27549,
"s": 27493,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27576,
"s": 27549,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27598,
"s": 27576,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27637,
"s": 27598,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27683,
"s": 27637,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27721,
"s": 27683,
"text": "Python | Convert a list to dictionary"
}
] |
AngularJS | ng-click Directive - GeeksforGeeks | 28 Mar, 2019
The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can popup alert when button is clicked.
Syntax:
<element ng-click="expression"> Contents... </element>
Example 1: This example uses ng-click Directive to display an alert message after clicking the element.
<!DOCTYPE html><html> <head> <title>ng-click Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="geek" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-click Directive</h2> <div ng-controller="app"> <button> <a href="" ng-click="alert()"> Click Here </a> </button> </div> <script> var app = angular.module("geek", []); app.controller('app', ['$scope', function ($app) { $app.alert = function () { alert("This is an example of ng-click"); } }]); </script></body> </html>
Output:Before clicking the button:After clicking the button:
Example 2: This example uses ng-click Directive to display some content after clicking the element.
<!DOCTYPE html><html> <head> <title>ng-click Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-click Directive</h2> <form name="form"> <div ng-hide="isShow"> Enter Name: <input type="text" required ng-model="Name" /> <br><br> <input type="button" ng-disabled="form.$invalid" ng-click="isShow = true" value="Sign in" /> </div> <div ng-show="isShow"> Sign in successful.<br> <input type="button" ng-click="isShow = false;Name=''" value="Logout" /> </div> </form></body> </html>
Output:Before clicking the button:After clicking the button:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular | keyup event
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 29626,
"s": 29598,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 29810,
"s": 29626,
"text": "The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can popup alert when button is clicked."
},
{
"code": null,
"e": 29818,
"s": 29810,
"text": "Syntax:"
},
{
"code": null,
"e": 29873,
"s": 29818,
"text": "<element ng-click=\"expression\"> Contents... </element>"
},
{
"code": null,
"e": 29977,
"s": 29873,
"text": "Example 1: This example uses ng-click Directive to display an alert message after clicking the element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-click Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"geek\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-click Directive</h2> <div ng-controller=\"app\"> <button> <a href=\"\" ng-click=\"alert()\"> Click Here </a> </button> </div> <script> var app = angular.module(\"geek\", []); app.controller('app', ['$scope', function ($app) { $app.alert = function () { alert(\"This is an example of ng-click\"); } }]); </script></body> </html>",
"e": 30720,
"s": 29977,
"text": null
},
{
"code": null,
"e": 30781,
"s": 30720,
"text": "Output:Before clicking the button:After clicking the button:"
},
{
"code": null,
"e": 30881,
"s": 30781,
"text": "Example 2: This example uses ng-click Directive to display some content after clicking the element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-click Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-click Directive</h2> <form name=\"form\"> <div ng-hide=\"isShow\"> Enter Name: <input type=\"text\" required ng-model=\"Name\" /> <br><br> <input type=\"button\" ng-disabled=\"form.$invalid\" ng-click=\"isShow = true\" value=\"Sign in\" /> </div> <div ng-show=\"isShow\"> Sign in successful.<br> <input type=\"button\" ng-click=\"isShow = false;Name=''\" value=\"Logout\" /> </div> </form></body> </html>",
"e": 31722,
"s": 30881,
"text": null
},
{
"code": null,
"e": 31783,
"s": 31722,
"text": "Output:Before clicking the button:After clicking the button:"
},
{
"code": null,
"e": 31804,
"s": 31783,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 31814,
"s": 31804,
"text": "AngularJS"
},
{
"code": null,
"e": 31831,
"s": 31814,
"text": "Web Technologies"
},
{
"code": null,
"e": 31929,
"s": 31831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31949,
"s": 31929,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31971,
"s": 31949,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 32006,
"s": 31971,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32037,
"s": 32006,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 32072,
"s": 32037,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 32112,
"s": 32072,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32145,
"s": 32112,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32190,
"s": 32145,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32233,
"s": 32190,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Check if a word exists in a grid or not - GeeksforGeeks | 20 Jan, 2022
Given a 2D grid of characters and a word, the task is to check if that word exists in the grid or not. A word can be matched in 4 directions at any point.The 4 directions are, Horizontally Left and Right, Vertically Up and Down. Examples:
Input: grid[][] = {"axmy",
"bgdf",
"xeet",
"raks"};
Output: Yes
a x m y
b g d f
x e e t
r a k s
Input: grid[][] = {"axmy",
"brdf",
"xeet",
"rass"};
Output : No
Source: Microsoft Interview
Approach: The idea used here is described in the steps below:
Check every cell, if the cell has first character, then recur one by one and try all 4 directions from that cell for a match.
Mark the position in the grid as visited and recur in the 4 possible directions.
After recurring, again mark the position as unvisited.
Once all the letters in the word are matched, return true.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if the word// exists in the grid or not#include <bits/stdc++.h>using namespace std;#define r 4#define c 5 // Function to check if a word exists in a grid// starting from the first match in the grid// level: index till which pattern is matched// x, y: current position in 2D arraybool findmatch(char mat[r], string pat, int x, int y, int nrow, int ncol, int level){ int l = pat.length(); // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x][y] == pat[level]) { // Marking this cell as visited char temp = mat[x][y]; mat[x][y] = '#'; // finding subpattern in 4 directions bool res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x][y] = temp; return res; } else // Not matching then false return false;} // Function to check if the word exists in the grid or notbool checkMatch(char mat[r], string pat, int nrow, int ncol){ int l = pat.length(); // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i][j] == pat[0]) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false;} // Driver Codeint main(){ char grid[r] = { "axmy", "bgdf", "xeet", "raks" }; // Function to check if word exists or not if (checkMatch(grid, "geeks", r, c)) cout << "Yes"; else cout << "No"; return 0; }
// Java program to check if the word// exists in the grid or notclass GFG{ static final int r = 4;static final int c = 4; // Function to check if a word exists in a grid// starting from the first match in the grid// level: index till which pattern is matched// x, y: current position in 2D arraystatic boolean findmatch(char mat[][], String pat, int x, int y, int nrow, int ncol, int level){ int l = pat.length(); // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x][y] == pat.charAt(level)) { // Marking this cell as visited char temp = mat[x][y]; mat[x][y] = '#'; // finding subpattern in 4 directions boolean res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x][y] = temp; return res; } else // Not matching then false return false;} // Function to check if the word exists in the grid or notstatic boolean checkMatch(char mat[][], String pat, int nrow, int ncol){ int l = pat.length(); // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i][j] == pat.charAt(0)) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false;} // Driver Codepublic static void main(String[] args){ char grid[][] = { "axmy".toCharArray(), "bgdf".toCharArray(), "xeet".toCharArray(), "raks".toCharArray() }; // Function to check if word exists or not if (checkMatch(grid, "geeks", r, c)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by 29AjayKumar
# Python3 program to check if the word# exists in the grid or not r = 4c = 4 # Function to check if a word exists# in a grid starting from the first# match in the grid level: index till # which pattern is matched x, y: current# position in 2D arraydef findmatch(mat, pat, x, y, nrow, ncol, level) : l = len(pat) # Pattern matched if (level == l) : return True # Out of Boundary if (x < 0 or y < 0 or x >= nrow or y >= ncol) : return False # If grid matches with a letter # while recursion if (mat[x][y] == pat[level]) : # Marking this cell as visited temp = mat[x][y] mat[x].replace(mat[x][y], "#") # finding subpattern in 4 directions res = (findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1)) # marking this cell as unvisited again mat[x].replace(mat[x][y], temp) return res else : # Not matching then false return False # Function to check if the word# exists in the grid or notdef checkMatch(mat, pat, nrow, ncol) : l = len(pat) # if total characters in matrix is # less then pattern length if (l > nrow * ncol) : return False # Traverse in the grid for i in range(nrow) : for j in range(ncol) : # If first letter matches, then # recur and check if (mat[i][j] == pat[0]) : if (findmatch(mat, pat, i, j, nrow, ncol, 0)) : return True return False # Driver Codeif __name__ == "__main__" : grid = ["axmy", "bgdf", "xeet", "raks"] # Function to check if word # exists or not if (checkMatch(grid, "geeks", r, c)) : print("Yes") else : print("No") # This code is contributed by Ryuga
// C# program to check if the word// exists in the grid or notusing System; class GFG{ static readonly int r = 4;static readonly int c = 4; // Function to check if a word exists in a grid// starting from the first match in the grid// level: index till which pattern is matched// x, y: current position in 2D arraystatic bool findmatch(char [,]mat, String pat, int x, int y, int nrow, int ncol, int level){ int l = pat.Length; // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x, y] == pat[level]) { // Marking this cell as visited char temp = mat[x, y]; mat[x, y] = '#'; // finding subpattern in 4 directions bool res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x, y] = temp; return res; } else // Not matching then false return false;} // Function to check if the word exists in the grid or notstatic bool checkMatch(char [,]mat, String pat, int nrow, int ncol){ int l = pat.Length; // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i, j] == pat[0]) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false;} // Driver Codepublic static void Main(String[] args){ char [,]grid = { {'a','x','m','y'}, {'b','g','d','f'}, {'x','e','e','t'}, {'r','a','k','s'} }; // Function to check if word exists or not if (checkMatch(grid, "geeks", r, c)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to check if the word // exists in the grid or not let r = 4; let c = 4; // Function to check if a word exists in a grid // starting from the first match in the grid // level: index till which pattern is matched // x, y: current position in 2D array function findmatch(mat, pat, x, y, nrow, ncol, level) { let l = pat.length; // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x][y] == pat[level]) { // Marking this cell as visited let temp = mat[x][y]; mat[x][y] = '#'; // finding subpattern in 4 directions let res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x][y] = temp; return res; } else // Not matching then false return false; } // Function to check if the word exists in the grid or not function checkMatch(mat, pat, nrow, ncol) { let l = pat.length; // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (let i = 0; i < nrow; i++) { for (let j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i][j] == pat[0]) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false; } let grid = [ "axmy".split(''), "bgdf".split(''), "xeet".split(''), "raks".split('') ]; // Function to check if word exists or not if (checkMatch(grid, "geeks", r, c)) document.write("Yes"); else document.write("No"); </script>
Yes
YouTubeGeeksforGeeks500K subscribersCheck if a word exists in a grid or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UDQ_FgNbArA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
ankthon
29AjayKumar
decode2207
akshitsaxenaa09
sagar0719kumar
Memoization
Microsoft
Dynamic Programming
Pattern Searching
Recursion
Microsoft
Dynamic Programming
Recursion
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Palindromic Substring | Set 1
Subset Sum Problem | DP-25
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 24606,
"s": 24578,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 24847,
"s": 24606,
"text": "Given a 2D grid of characters and a word, the task is to check if that word exists in the grid or not. A word can be matched in 4 directions at any point.The 4 directions are, Horizontally Left and Right, Vertically Up and Down. Examples: "
},
{
"code": null,
"e": 25127,
"s": 24847,
"text": "Input: grid[][] = {\"axmy\",\n \"bgdf\",\n \"xeet\",\n \"raks\"};\nOutput: Yes\n\na x m y\nb g d f\nx e e t\nr a k s\n\nInput: grid[][] = {\"axmy\",\n \"brdf\",\n \"xeet\",\n \"rass\"};\nOutput : No"
},
{
"code": null,
"e": 25156,
"s": 25127,
"text": "Source: Microsoft Interview "
},
{
"code": null,
"e": 25220,
"s": 25156,
"text": "Approach: The idea used here is described in the steps below: "
},
{
"code": null,
"e": 25346,
"s": 25220,
"text": "Check every cell, if the cell has first character, then recur one by one and try all 4 directions from that cell for a match."
},
{
"code": null,
"e": 25427,
"s": 25346,
"text": "Mark the position in the grid as visited and recur in the 4 possible directions."
},
{
"code": null,
"e": 25482,
"s": 25427,
"text": "After recurring, again mark the position as unvisited."
},
{
"code": null,
"e": 25541,
"s": 25482,
"text": "Once all the letters in the word are matched, return true."
},
{
"code": null,
"e": 25594,
"s": 25541,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25598,
"s": 25594,
"text": "C++"
},
{
"code": null,
"e": 25603,
"s": 25598,
"text": "Java"
},
{
"code": null,
"e": 25611,
"s": 25603,
"text": "Python3"
},
{
"code": null,
"e": 25614,
"s": 25611,
"text": "C#"
},
{
"code": null,
"e": 25625,
"s": 25614,
"text": "Javascript"
},
{
"code": "// C++ program to check if the word// exists in the grid or not#include <bits/stdc++.h>using namespace std;#define r 4#define c 5 // Function to check if a word exists in a grid// starting from the first match in the grid// level: index till which pattern is matched// x, y: current position in 2D arraybool findmatch(char mat[r], string pat, int x, int y, int nrow, int ncol, int level){ int l = pat.length(); // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x][y] == pat[level]) { // Marking this cell as visited char temp = mat[x][y]; mat[x][y] = '#'; // finding subpattern in 4 directions bool res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x][y] = temp; return res; } else // Not matching then false return false;} // Function to check if the word exists in the grid or notbool checkMatch(char mat[r], string pat, int nrow, int ncol){ int l = pat.length(); // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i][j] == pat[0]) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false;} // Driver Codeint main(){ char grid[r] = { \"axmy\", \"bgdf\", \"xeet\", \"raks\" }; // Function to check if word exists or not if (checkMatch(grid, \"geeks\", r, c)) cout << \"Yes\"; else cout << \"No\"; return 0; }",
"e": 27784,
"s": 25625,
"text": null
},
{
"code": "// Java program to check if the word// exists in the grid or notclass GFG{ static final int r = 4;static final int c = 4; // Function to check if a word exists in a grid// starting from the first match in the grid// level: index till which pattern is matched// x, y: current position in 2D arraystatic boolean findmatch(char mat[][], String pat, int x, int y, int nrow, int ncol, int level){ int l = pat.length(); // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x][y] == pat.charAt(level)) { // Marking this cell as visited char temp = mat[x][y]; mat[x][y] = '#'; // finding subpattern in 4 directions boolean res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x][y] = temp; return res; } else // Not matching then false return false;} // Function to check if the word exists in the grid or notstatic boolean checkMatch(char mat[][], String pat, int nrow, int ncol){ int l = pat.length(); // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i][j] == pat.charAt(0)) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false;} // Driver Codepublic static void main(String[] args){ char grid[][] = { \"axmy\".toCharArray(), \"bgdf\".toCharArray(), \"xeet\".toCharArray(), \"raks\".toCharArray() }; // Function to check if word exists or not if (checkMatch(grid, \"geeks\", r, c)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 30140,
"s": 27784,
"text": null
},
{
"code": "# Python3 program to check if the word# exists in the grid or not r = 4c = 4 # Function to check if a word exists# in a grid starting from the first# match in the grid level: index till # which pattern is matched x, y: current# position in 2D arraydef findmatch(mat, pat, x, y, nrow, ncol, level) : l = len(pat) # Pattern matched if (level == l) : return True # Out of Boundary if (x < 0 or y < 0 or x >= nrow or y >= ncol) : return False # If grid matches with a letter # while recursion if (mat[x][y] == pat[level]) : # Marking this cell as visited temp = mat[x][y] mat[x].replace(mat[x][y], \"#\") # finding subpattern in 4 directions res = (findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1)) # marking this cell as unvisited again mat[x].replace(mat[x][y], temp) return res else : # Not matching then false return False # Function to check if the word# exists in the grid or notdef checkMatch(mat, pat, nrow, ncol) : l = len(pat) # if total characters in matrix is # less then pattern length if (l > nrow * ncol) : return False # Traverse in the grid for i in range(nrow) : for j in range(ncol) : # If first letter matches, then # recur and check if (mat[i][j] == pat[0]) : if (findmatch(mat, pat, i, j, nrow, ncol, 0)) : return True return False # Driver Codeif __name__ == \"__main__\" : grid = [\"axmy\", \"bgdf\", \"xeet\", \"raks\"] # Function to check if word # exists or not if (checkMatch(grid, \"geeks\", r, c)) : print(\"Yes\") else : print(\"No\") # This code is contributed by Ryuga",
"e": 32144,
"s": 30140,
"text": null
},
{
"code": "// C# program to check if the word// exists in the grid or notusing System; class GFG{ static readonly int r = 4;static readonly int c = 4; // Function to check if a word exists in a grid// starting from the first match in the grid// level: index till which pattern is matched// x, y: current position in 2D arraystatic bool findmatch(char [,]mat, String pat, int x, int y, int nrow, int ncol, int level){ int l = pat.Length; // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x, y] == pat[level]) { // Marking this cell as visited char temp = mat[x, y]; mat[x, y] = '#'; // finding subpattern in 4 directions bool res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x, y] = temp; return res; } else // Not matching then false return false;} // Function to check if the word exists in the grid or notstatic bool checkMatch(char [,]mat, String pat, int nrow, int ncol){ int l = pat.Length; // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i, j] == pat[0]) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false;} // Driver Codepublic static void Main(String[] args){ char [,]grid = { {'a','x','m','y'}, {'b','g','d','f'}, {'x','e','e','t'}, {'r','a','k','s'} }; // Function to check if word exists or not if (checkMatch(grid, \"geeks\", r, c)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 34458,
"s": 32144,
"text": null
},
{
"code": "<script> // JavaScript program to check if the word // exists in the grid or not let r = 4; let c = 4; // Function to check if a word exists in a grid // starting from the first match in the grid // level: index till which pattern is matched // x, y: current position in 2D array function findmatch(mat, pat, x, y, nrow, ncol, level) { let l = pat.length; // Pattern matched if (level == l) return true; // Out of Boundary if (x < 0 || y < 0 || x >= nrow || y >= ncol) return false; // If grid matches with a letter while // recursion if (mat[x][y] == pat[level]) { // Marking this cell as visited let temp = mat[x][y]; mat[x][y] = '#'; // finding subpattern in 4 directions let res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); // marking this cell // as unvisited again mat[x][y] = temp; return res; } else // Not matching then false return false; } // Function to check if the word exists in the grid or not function checkMatch(mat, pat, nrow, ncol) { let l = pat.length; // if total characters in matrix is // less then pattern length if (l > nrow * ncol) return false; // Traverse in the grid for (let i = 0; i < nrow; i++) { for (let j = 0; j < ncol; j++) { // If first letter matches, then recur and check if (mat[i][j] == pat[0]) if (findmatch(mat, pat, i, j, nrow, ncol, 0)) return true; } } return false; } let grid = [ \"axmy\".split(''), \"bgdf\".split(''), \"xeet\".split(''), \"raks\".split('') ]; // Function to check if word exists or not if (checkMatch(grid, \"geeks\", r, c)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 36775,
"s": 34458,
"text": null
},
{
"code": null,
"e": 36779,
"s": 36775,
"text": "Yes"
},
{
"code": null,
"e": 37620,
"s": 36781,
"text": "YouTubeGeeksforGeeks500K subscribersCheck if a word exists in a grid or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:15•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=UDQ_FgNbArA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 37628,
"s": 37620,
"text": "ankthon"
},
{
"code": null,
"e": 37640,
"s": 37628,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37651,
"s": 37640,
"text": "decode2207"
},
{
"code": null,
"e": 37667,
"s": 37651,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 37682,
"s": 37667,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 37694,
"s": 37682,
"text": "Memoization"
},
{
"code": null,
"e": 37704,
"s": 37694,
"text": "Microsoft"
},
{
"code": null,
"e": 37724,
"s": 37704,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37742,
"s": 37724,
"text": "Pattern Searching"
},
{
"code": null,
"e": 37752,
"s": 37742,
"text": "Recursion"
},
{
"code": null,
"e": 37762,
"s": 37752,
"text": "Microsoft"
},
{
"code": null,
"e": 37782,
"s": 37762,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37792,
"s": 37782,
"text": "Recursion"
},
{
"code": null,
"e": 37810,
"s": 37792,
"text": "Pattern Searching"
},
{
"code": null,
"e": 37908,
"s": 37810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37917,
"s": 37908,
"text": "Comments"
},
{
"code": null,
"e": 37930,
"s": 37917,
"text": "Old Comments"
},
{
"code": null,
"e": 37961,
"s": 37930,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 37994,
"s": 37961,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 38032,
"s": 37994,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 38059,
"s": 38032,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 38127,
"s": 38059,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 38163,
"s": 38127,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 38206,
"s": 38163,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 38244,
"s": 38206,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 38286,
"s": 38244,
"text": "Check if a string is substring of another"
}
] |
Binary Search (bisect) in Python - GeeksforGeeks | 04 Feb, 2022
Binary Search is a technique used to search element in a sorted list. In this article, we will looking at library functions to do Binary Search.Finding first occurrence of an element.
bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion point of x in a sorted list. Last two parameters are optional, they are used to search in sublist.
Python3
# Python code to demonstrate working# of binary search in libraryfrom bisect import bisect_left def BinarySearch(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return i else: return -1 a = [1, 2, 4, 4, 8]x = int(4)res = BinarySearch(a, x)if res == -1: print(x, "is absent")else: print("First occurrence of", x, "is present at", res)
First occurrence of 4 is present at 2
Finding greatest value smaller than x.
Python3
# Python code to demonstrate working# of binary search in libraryfrom bisect import bisect_left def BinarySearch(a, x): i = bisect_left(a, x) if i: return (i-1) else: return -1 # Driver codea = [1, 2, 4, 4, 8]x = int(7)res = BinarySearch(a, x)if res == -1: print("No value smaller than ", x)else: print("Largest value smaller than ", x, " is at index ", res)
Largest value smaller than 7 is at index 3
Finding rightmost occurrence
bisect.bisect_right(a, x, lo=0, hi=len(a)) Returns rightmost insertion point of x in a sorted list a. Last two parameters are optional, they are used to search in sublist.
Python3
# Python code to demonstrate working# of binary search in libraryfrom bisect import bisect_right def BinarySearch(a, x): i = bisect_right(a, x) if i != 0 and a[i-1] == x: return (i-1) else: return -1 a = [1, 2, 4, 4]x = int(4)res = BinarySearch(a, x)if res == -1: print(x, "is absent")else: print("Last occurrence of", x, "is present at", res)
Last occurrence of 4 is present at 3
Please refer Binary Search for writing your own Binary Search code.Reference : https://docs.python.org/3/library/bisect.html
hm32005
Binary Search
python searching-exercises
python-list
python-list-functions
Divide and Conquer
Python
Python Programs
Searching
python-list
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction
Median of two sorted arrays of different sizes
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Write a program to calculate pow(x,n)
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": 26343,
"s": 26315,
"text": "\n04 Feb, 2022"
},
{
"code": null,
"e": 26529,
"s": 26343,
"text": "Binary Search is a technique used to search element in a sorted list. In this article, we will looking at library functions to do Binary Search.Finding first occurrence of an element. "
},
{
"code": null,
"e": 26699,
"s": 26529,
"text": "bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion point of x in a sorted list. Last two parameters are optional, they are used to search in sublist."
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working# of binary search in libraryfrom bisect import bisect_left def BinarySearch(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return i else: return -1 a = [1, 2, 4, 4, 8]x = int(4)res = BinarySearch(a, x)if res == -1: print(x, \"is absent\")else: print(\"First occurrence of\", x, \"is present at\", res)",
"e": 27084,
"s": 26709,
"text": null
},
{
"code": null,
"e": 27122,
"s": 27084,
"text": "First occurrence of 4 is present at 2"
},
{
"code": null,
"e": 27165,
"s": 27124,
"text": "Finding greatest value smaller than x. "
},
{
"code": null,
"e": 27173,
"s": 27165,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working# of binary search in libraryfrom bisect import bisect_left def BinarySearch(a, x): i = bisect_left(a, x) if i: return (i-1) else: return -1 # Driver codea = [1, 2, 4, 4, 8]x = int(7)res = BinarySearch(a, x)if res == -1: print(\"No value smaller than \", x)else: print(\"Largest value smaller than \", x, \" is at index \", res)",
"e": 27562,
"s": 27173,
"text": null
},
{
"code": null,
"e": 27608,
"s": 27562,
"text": "Largest value smaller than 7 is at index 3"
},
{
"code": null,
"e": 27640,
"s": 27610,
"text": "Finding rightmost occurrence "
},
{
"code": null,
"e": 27812,
"s": 27640,
"text": "bisect.bisect_right(a, x, lo=0, hi=len(a)) Returns rightmost insertion point of x in a sorted list a. Last two parameters are optional, they are used to search in sublist."
},
{
"code": null,
"e": 27822,
"s": 27814,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working# of binary search in libraryfrom bisect import bisect_right def BinarySearch(a, x): i = bisect_right(a, x) if i != 0 and a[i-1] == x: return (i-1) else: return -1 a = [1, 2, 4, 4]x = int(4)res = BinarySearch(a, x)if res == -1: print(x, \"is absent\")else: print(\"Last occurrence of\", x, \"is present at\", res)",
"e": 28196,
"s": 27822,
"text": null
},
{
"code": null,
"e": 28233,
"s": 28196,
"text": "Last occurrence of 4 is present at 3"
},
{
"code": null,
"e": 28361,
"s": 28235,
"text": "Please refer Binary Search for writing your own Binary Search code.Reference : https://docs.python.org/3/library/bisect.html "
},
{
"code": null,
"e": 28369,
"s": 28361,
"text": "hm32005"
},
{
"code": null,
"e": 28383,
"s": 28369,
"text": "Binary Search"
},
{
"code": null,
"e": 28410,
"s": 28383,
"text": "python searching-exercises"
},
{
"code": null,
"e": 28422,
"s": 28410,
"text": "python-list"
},
{
"code": null,
"e": 28444,
"s": 28422,
"text": "python-list-functions"
},
{
"code": null,
"e": 28463,
"s": 28444,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 28470,
"s": 28463,
"text": "Python"
},
{
"code": null,
"e": 28486,
"s": 28470,
"text": "Python Programs"
},
{
"code": null,
"e": 28496,
"s": 28486,
"text": "Searching"
},
{
"code": null,
"e": 28508,
"s": 28496,
"text": "python-list"
},
{
"code": null,
"e": 28518,
"s": 28508,
"text": "Searching"
},
{
"code": null,
"e": 28537,
"s": 28518,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 28551,
"s": 28537,
"text": "Binary Search"
},
{
"code": null,
"e": 28649,
"s": 28551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28676,
"s": 28649,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 28720,
"s": 28676,
"text": "Divide and Conquer Algorithm | Introduction"
},
{
"code": null,
"e": 28767,
"s": 28720,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 28829,
"s": 28767,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 28867,
"s": 28829,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 28895,
"s": 28867,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28945,
"s": 28895,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28967,
"s": 28945,
"text": "Python map() function"
}
] |
How to Run PostgreSQL Using Docker | by Mahbub Zaman | Towards Data Science | PostgreSQL has been around for over 30 years. It was first developed in 1986 as part of the POSTGRES project at the University of California at Berkeley. Now it is the world’s most advanced open-source relational database. Running PostgreSQL on different machines can be challenging, but Docker makes it easier. From this post, you’ll learn how to run PostgreSQL inside a Docker container.
As a programmer or data scientist, you have to work with databases at some point in your career. Since Docker has become a popular DevOps tool in recent years, you may have to use PostgreSQL with Docker. Before we dive into the setup, read the post below if you want to know some basics of Docker.
towardsdatascience.com
First, we need to install Docker. We will use a Docker compose file, a SQL dump file containing bootstrap data, and macOS in this setup. You can download these two files separately. Just make sure to put both docker-compose.yml and infile in the same folder. Alternatively, you can get the repository from here. Now, let’s discuss docker-compose and SQL dump files briefly.
Docker Compose: It’s a YAML file, and we can define containers and their properties inside. These containers are called services. For example, if your application has multiple stacks, such as a web server and a database server, we can use a docker-compose file.
SQL-dump: A sql-dump contains SQL queries in plain text. PostgreSQL provides the command-line utility program pg_dump to create and read dump files.
Let’s break down the individual ingredients of the docker-compose.yml file.
version: '3.8'services:db: container_name: pg_container image: postgres restart: always environment: POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_DB: test_db ports: - "5432:5432" volumes: - $HOME/Desktop/PostgreSql-Snippets/infile:/infile - pg_data:/var/lib/postgresql/data/volumes: pg_data:
The first line defines the version of the Compose file, which is 3.8. There are other file formats — 1, 2, 2.x, and 3.x. Get more information on Compose file formats from Docker’s documentation here.
After that, we have the services hash, and it contains the services for an application. For our application, we only have one service called db.
Inside the db service, the first tag container_name is used to change the default container name to pg_container for our convenience. The second tag image is used to define the Docker image for the db service, and we are using the pre-built official image of PostgreSQL.
For the third tag restart, we have set the value always. What it does is it always automatically restarts the container by saving time. It restarts the container when either the Docker daemon restarts or the container itself is manually restarted. For example, every time you reboot your machine, you don’t have to manually start the container.
The fourth tag environment defines a set of environment variables. Later we will use these for database authentication purposes. Here we have POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB. Among these three variables, the only required one is the POSTGRES_PASSWORD. The default value of POSTGRES_USER is postgres, and for POSTGRES_DB it’s the value of POSTGRES_USER. You can read more about these variables from here.
The fifth tag is the ports tag and is used to define both host and container ports. It maps port 5432 on the host to port 5432 on the container.
Finally, the volumes tag is used to mount a folder from the host machine to the container. It comprises two fields separated by a colon, the first part is the path in the host machine and the second part is the path in the container. Remove this portion if you don’t want to mount the sql-dump into the container. The second line of volumes tag is used to store the database data, the first part is the name of the volume, and the second part is the path in the container where the database data is stored. But how do we know what’s that path exactly? We can determine the path by running the following command using the psql. We will discuss how to use psql later in this post.
show data_directory;
Remove the second line if you don’t want to back up your container’s database data. If you choose to remove both lines under the volumes tag, remove the volumes tag.
At the end of the docker-compose file, you can see that we have defined the volume pg_data under the volumes tag. It allows us to reuse the volume across multiple services. Read more about volumes tag here.
The moment of truth. Let’s run the following command from the same directory where the docker-compose.yml file is located. We can see that it starts and runs our entire app.
docker compose up
We can check if the container is running or not using the docker ps command on the host machine. As we can see, we have a running container called pg_container.
Moreover, we can see the image by running the docker images command.
Finally, we can see that a volume has been created by running the docker volume ls command.
What is psql? It’s a terminal-based interface to PostgreSQL, which allows us to run SQL queries interactively. First, let’s access our running container pg_container.
docker exec -it pg_container bash
I talked about how the above line works in the following article. Have a look.
towardsdatascience.com
Now we can connect to psql server using the hostname, database name, username, and password.
psql --host=pg_container --dbname=test_db --username=root
If you want to type less, use the following command. Find more options for PostgreSQL interactive terminal from here.
psql -h pg_container -d test_db -U root
Here, the password’s value is the root, which has been defined inside the docker-compose file earlier.
Now we can load the dump file into our test_db database. In this case, infile. It is accessible inside the container because we have mounted it from the host machine.
psql -h pg_container -d test_db -U root -f infile
If we run the PostgreSQL command \dt, we can see two tables called marks and students inside our database test_db.
Did we miss something? Not really, but yes! Since our data is backed up in the volume called postgresql-snippets_pg_data, we can remove the container without losing the database data. Let’s try that now. First, delete the container and then create it again.
docker rm pg_containerdocker compose up
Now after accessing the container and psql we can still see our data!
docker exec -it pg_container bashpsql -h pg_container -d test_db -U root\dt
In case you want to delete the backup volume, use the docker volume rm command. Read the documentation here.
docker volume rm postgresql-snippets_pg_data
Or you can use the docker-compose command. Read the documentation here.
docker-compose down --volumes
Great job! Now you know how to run a PostgreSQL database using Docker. Docker is one of the fascinating technology I came across. Not only it saves time, but it also helps you run an application on any machine. If you find this post helpful, check out the post below where I’ve talked about how to run MySQL and phpMyAdmin using Docker. | [
{
"code": null,
"e": 562,
"s": 172,
"text": "PostgreSQL has been around for over 30 years. It was first developed in 1986 as part of the POSTGRES project at the University of California at Berkeley. Now it is the world’s most advanced open-source relational database. Running PostgreSQL on different machines can be challenging, but Docker makes it easier. From this post, you’ll learn how to run PostgreSQL inside a Docker container."
},
{
"code": null,
"e": 860,
"s": 562,
"text": "As a programmer or data scientist, you have to work with databases at some point in your career. Since Docker has become a popular DevOps tool in recent years, you may have to use PostgreSQL with Docker. Before we dive into the setup, read the post below if you want to know some basics of Docker."
},
{
"code": null,
"e": 883,
"s": 860,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1257,
"s": 883,
"text": "First, we need to install Docker. We will use a Docker compose file, a SQL dump file containing bootstrap data, and macOS in this setup. You can download these two files separately. Just make sure to put both docker-compose.yml and infile in the same folder. Alternatively, you can get the repository from here. Now, let’s discuss docker-compose and SQL dump files briefly."
},
{
"code": null,
"e": 1519,
"s": 1257,
"text": "Docker Compose: It’s a YAML file, and we can define containers and their properties inside. These containers are called services. For example, if your application has multiple stacks, such as a web server and a database server, we can use a docker-compose file."
},
{
"code": null,
"e": 1668,
"s": 1519,
"text": "SQL-dump: A sql-dump contains SQL queries in plain text. PostgreSQL provides the command-line utility program pg_dump to create and read dump files."
},
{
"code": null,
"e": 1744,
"s": 1668,
"text": "Let’s break down the individual ingredients of the docker-compose.yml file."
},
{
"code": null,
"e": 2093,
"s": 1744,
"text": "version: '3.8'services:db: container_name: pg_container image: postgres restart: always environment: POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_DB: test_db ports: - \"5432:5432\" volumes: - $HOME/Desktop/PostgreSql-Snippets/infile:/infile - pg_data:/var/lib/postgresql/data/volumes: pg_data:"
},
{
"code": null,
"e": 2293,
"s": 2093,
"text": "The first line defines the version of the Compose file, which is 3.8. There are other file formats — 1, 2, 2.x, and 3.x. Get more information on Compose file formats from Docker’s documentation here."
},
{
"code": null,
"e": 2438,
"s": 2293,
"text": "After that, we have the services hash, and it contains the services for an application. For our application, we only have one service called db."
},
{
"code": null,
"e": 2709,
"s": 2438,
"text": "Inside the db service, the first tag container_name is used to change the default container name to pg_container for our convenience. The second tag image is used to define the Docker image for the db service, and we are using the pre-built official image of PostgreSQL."
},
{
"code": null,
"e": 3054,
"s": 2709,
"text": "For the third tag restart, we have set the value always. What it does is it always automatically restarts the container by saving time. It restarts the container when either the Docker daemon restarts or the container itself is manually restarted. For example, every time you reboot your machine, you don’t have to manually start the container."
},
{
"code": null,
"e": 3476,
"s": 3054,
"text": "The fourth tag environment defines a set of environment variables. Later we will use these for database authentication purposes. Here we have POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB. Among these three variables, the only required one is the POSTGRES_PASSWORD. The default value of POSTGRES_USER is postgres, and for POSTGRES_DB it’s the value of POSTGRES_USER. You can read more about these variables from here."
},
{
"code": null,
"e": 3621,
"s": 3476,
"text": "The fifth tag is the ports tag and is used to define both host and container ports. It maps port 5432 on the host to port 5432 on the container."
},
{
"code": null,
"e": 4300,
"s": 3621,
"text": "Finally, the volumes tag is used to mount a folder from the host machine to the container. It comprises two fields separated by a colon, the first part is the path in the host machine and the second part is the path in the container. Remove this portion if you don’t want to mount the sql-dump into the container. The second line of volumes tag is used to store the database data, the first part is the name of the volume, and the second part is the path in the container where the database data is stored. But how do we know what’s that path exactly? We can determine the path by running the following command using the psql. We will discuss how to use psql later in this post."
},
{
"code": null,
"e": 4321,
"s": 4300,
"text": "show data_directory;"
},
{
"code": null,
"e": 4487,
"s": 4321,
"text": "Remove the second line if you don’t want to back up your container’s database data. If you choose to remove both lines under the volumes tag, remove the volumes tag."
},
{
"code": null,
"e": 4694,
"s": 4487,
"text": "At the end of the docker-compose file, you can see that we have defined the volume pg_data under the volumes tag. It allows us to reuse the volume across multiple services. Read more about volumes tag here."
},
{
"code": null,
"e": 4868,
"s": 4694,
"text": "The moment of truth. Let’s run the following command from the same directory where the docker-compose.yml file is located. We can see that it starts and runs our entire app."
},
{
"code": null,
"e": 4886,
"s": 4868,
"text": "docker compose up"
},
{
"code": null,
"e": 5047,
"s": 4886,
"text": "We can check if the container is running or not using the docker ps command on the host machine. As we can see, we have a running container called pg_container."
},
{
"code": null,
"e": 5116,
"s": 5047,
"text": "Moreover, we can see the image by running the docker images command."
},
{
"code": null,
"e": 5208,
"s": 5116,
"text": "Finally, we can see that a volume has been created by running the docker volume ls command."
},
{
"code": null,
"e": 5375,
"s": 5208,
"text": "What is psql? It’s a terminal-based interface to PostgreSQL, which allows us to run SQL queries interactively. First, let’s access our running container pg_container."
},
{
"code": null,
"e": 5409,
"s": 5375,
"text": "docker exec -it pg_container bash"
},
{
"code": null,
"e": 5488,
"s": 5409,
"text": "I talked about how the above line works in the following article. Have a look."
},
{
"code": null,
"e": 5511,
"s": 5488,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5604,
"s": 5511,
"text": "Now we can connect to psql server using the hostname, database name, username, and password."
},
{
"code": null,
"e": 5662,
"s": 5604,
"text": "psql --host=pg_container --dbname=test_db --username=root"
},
{
"code": null,
"e": 5780,
"s": 5662,
"text": "If you want to type less, use the following command. Find more options for PostgreSQL interactive terminal from here."
},
{
"code": null,
"e": 5820,
"s": 5780,
"text": "psql -h pg_container -d test_db -U root"
},
{
"code": null,
"e": 5923,
"s": 5820,
"text": "Here, the password’s value is the root, which has been defined inside the docker-compose file earlier."
},
{
"code": null,
"e": 6090,
"s": 5923,
"text": "Now we can load the dump file into our test_db database. In this case, infile. It is accessible inside the container because we have mounted it from the host machine."
},
{
"code": null,
"e": 6140,
"s": 6090,
"text": "psql -h pg_container -d test_db -U root -f infile"
},
{
"code": null,
"e": 6255,
"s": 6140,
"text": "If we run the PostgreSQL command \\dt, we can see two tables called marks and students inside our database test_db."
},
{
"code": null,
"e": 6513,
"s": 6255,
"text": "Did we miss something? Not really, but yes! Since our data is backed up in the volume called postgresql-snippets_pg_data, we can remove the container without losing the database data. Let’s try that now. First, delete the container and then create it again."
},
{
"code": null,
"e": 6553,
"s": 6513,
"text": "docker rm pg_containerdocker compose up"
},
{
"code": null,
"e": 6623,
"s": 6553,
"text": "Now after accessing the container and psql we can still see our data!"
},
{
"code": null,
"e": 6699,
"s": 6623,
"text": "docker exec -it pg_container bashpsql -h pg_container -d test_db -U root\\dt"
},
{
"code": null,
"e": 6808,
"s": 6699,
"text": "In case you want to delete the backup volume, use the docker volume rm command. Read the documentation here."
},
{
"code": null,
"e": 6853,
"s": 6808,
"text": "docker volume rm postgresql-snippets_pg_data"
},
{
"code": null,
"e": 6925,
"s": 6853,
"text": "Or you can use the docker-compose command. Read the documentation here."
},
{
"code": null,
"e": 6955,
"s": 6925,
"text": "docker-compose down --volumes"
}
] |
Sunburst Plot using Plotly in Python - GeeksforGeeks | 28 Jul, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
Sunburst plot visualizes stratified data gradually from roots to leaves. The root starts from the center and squirt are added to the outer rings. Each level of the hierarchy is represented by one ring or circle with the innermost circle, further rings are divided into slices that represent data points and the size of the slice represents data values.
Syntax: plotly.express.sunburst(data_frame=None, names=None, values=None, parents=None, path=None, ids=None, color=None, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, branchvalues=None, maxdepth=None)
Parameters:
data_frame: This argument needs to be passed for column names (and not keyword names) to be used.
names: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used as labels for sectors.
values: Either a name of a column in data_frame or a pandas Series or array_like object. Values from this column or array_like are used to set values associated to sectors.
parents: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used as parents in sunburst and treemap charts.
path: Either names of columns in data_frame, or pandas Series, or array_like objects List of columns names or columns of a rectangular dataframe defining the hierarchy of sectors, from root to leaves.
ids: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to set ids of sectors
Example:
Python3
import plotly.express as px df = px.data.iris() fig = px.sunburst(df, path=['sepal_length', 'sepal_width', 'petal_length'], values='petal_width')fig.show()
Output:
The rectangular dataframe represents the hierarchical data where different columns correspond to different levels of hierarchy. To plot such columns path parameter is used. Path parameter takes either name of columns in data_frame, or pandas Series, or array_like objects, list of columns names or columns of a rectangular dataframe defining the hierarchy of sectors, from root to leaves.
Note: When ids or parents are passed along with path an error is raised.
Example:
Python3
import plotly.express as px df = px.data.tips() fig = px.sunburst(df, path=['day', 'sex'], values='total_bill')fig.show()
Output:
If the color argument is passed, the color of the node is calculated as the average color values of its children by their values.
Example:
Python3
import plotly.express as px df = px.data.tips() fig = px.sunburst(df, path=['day', 'sex'], values='total_bill', color='total_bill')fig.show()
Output:
When non-numerical data is passed to the color argument, then discrete data is used. If a color column of a sector has the same value for all of its children, then the corresponding color is used otherwise the same first color of discrete color will be used.
Example:
Python3
import plotly.express as px df = px.data.tips() fig = px.sunburst(df, path=['day', 'sex'], values='total_bill', color='time')fig.show()
Output:
If the data-set is not fully rectangular in shape, then missing values should be mentioned as none. None entries of the parents must be a leaf, otherwise, valueError will be raised.
Example:
Python3
import plotly.express as pximport pandas as pd A = ["A", "B", "C", "D", None, "E", "F", "G", "H", None] B = ["A1", "A1", "B1", "B1", "N", "A1", "A1", "B1", "B1", "N"]C = ["N", "N", "N", "N", "N", "S", "S", "S", "S", "S"]D = [1, 13, 21, 14, 1, 12, 25, 1, 14, 1] df = pd.DataFrame( dict(A=A, B=B, C=C, D=D)) fig = px.sunburst(df, path=['C', 'B', 'A'], values='D')fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 23677,
"s": 23649,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 23979,
"s": 23677,
"text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 24332,
"s": 23979,
"text": "Sunburst plot visualizes stratified data gradually from roots to leaves. The root starts from the center and squirt are added to the outer rings. Each level of the hierarchy is represented by one ring or circle with the innermost circle, further rings are divided into slices that represent data points and the size of the slice represents data values."
},
{
"code": null,
"e": 24734,
"s": 24332,
"text": "Syntax: plotly.express.sunburst(data_frame=None, names=None, values=None, parents=None, path=None, ids=None, color=None, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, branchvalues=None, maxdepth=None)"
},
{
"code": null,
"e": 24746,
"s": 24734,
"text": "Parameters:"
},
{
"code": null,
"e": 24845,
"s": 24746,
"text": "data_frame: This argument needs to be passed for column names (and not keyword names) to be used. "
},
{
"code": null,
"e": 25004,
"s": 24845,
"text": "names: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used as labels for sectors."
},
{
"code": null,
"e": 25178,
"s": 25004,
"text": "values: Either a name of a column in data_frame or a pandas Series or array_like object. Values from this column or array_like are used to set values associated to sectors."
},
{
"code": null,
"e": 25359,
"s": 25178,
"text": "parents: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used as parents in sunburst and treemap charts."
},
{
"code": null,
"e": 25561,
"s": 25359,
"text": "path: Either names of columns in data_frame, or pandas Series, or array_like objects List of columns names or columns of a rectangular dataframe defining the hierarchy of sectors, from root to leaves. "
},
{
"code": null,
"e": 25717,
"s": 25561,
"text": "ids: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to set ids of sectors"
},
{
"code": null,
"e": 25726,
"s": 25717,
"text": "Example:"
},
{
"code": null,
"e": 25734,
"s": 25726,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.sunburst(df, path=['sepal_length', 'sepal_width', 'petal_length'], values='petal_width')fig.show()",
"e": 25965,
"s": 25734,
"text": null
},
{
"code": null,
"e": 25973,
"s": 25965,
"text": "Output:"
},
{
"code": null,
"e": 26362,
"s": 25973,
"text": "The rectangular dataframe represents the hierarchical data where different columns correspond to different levels of hierarchy. To plot such columns path parameter is used. Path parameter takes either name of columns in data_frame, or pandas Series, or array_like objects, list of columns names or columns of a rectangular dataframe defining the hierarchy of sectors, from root to leaves."
},
{
"code": null,
"e": 26435,
"s": 26362,
"text": "Note: When ids or parents are passed along with path an error is raised."
},
{
"code": null,
"e": 26444,
"s": 26435,
"text": "Example:"
},
{
"code": null,
"e": 26452,
"s": 26444,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.sunburst(df, path=['day', 'sex'], values='total_bill')fig.show()",
"e": 26594,
"s": 26452,
"text": null
},
{
"code": null,
"e": 26602,
"s": 26594,
"text": "Output:"
},
{
"code": null,
"e": 26732,
"s": 26602,
"text": "If the color argument is passed, the color of the node is calculated as the average color values of its children by their values."
},
{
"code": null,
"e": 26741,
"s": 26732,
"text": "Example:"
},
{
"code": null,
"e": 26749,
"s": 26741,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.sunburst(df, path=['day', 'sex'], values='total_bill', color='total_bill')fig.show()",
"e": 26911,
"s": 26749,
"text": null
},
{
"code": null,
"e": 26919,
"s": 26911,
"text": "Output:"
},
{
"code": null,
"e": 27178,
"s": 26919,
"text": "When non-numerical data is passed to the color argument, then discrete data is used. If a color column of a sector has the same value for all of its children, then the corresponding color is used otherwise the same first color of discrete color will be used."
},
{
"code": null,
"e": 27187,
"s": 27178,
"text": "Example:"
},
{
"code": null,
"e": 27195,
"s": 27187,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.sunburst(df, path=['day', 'sex'], values='total_bill', color='time')fig.show()",
"e": 27351,
"s": 27195,
"text": null
},
{
"code": null,
"e": 27359,
"s": 27351,
"text": "Output:"
},
{
"code": null,
"e": 27542,
"s": 27359,
"text": "If the data-set is not fully rectangular in shape, then missing values should be mentioned as none. None entries of the parents must be a leaf, otherwise, valueError will be raised. "
},
{
"code": null,
"e": 27551,
"s": 27542,
"text": "Example:"
},
{
"code": null,
"e": 27559,
"s": 27551,
"text": "Python3"
},
{
"code": "import plotly.express as pximport pandas as pd A = [\"A\", \"B\", \"C\", \"D\", None, \"E\", \"F\", \"G\", \"H\", None] B = [\"A1\", \"A1\", \"B1\", \"B1\", \"N\", \"A1\", \"A1\", \"B1\", \"B1\", \"N\"]C = [\"N\", \"N\", \"N\", \"N\", \"N\", \"S\", \"S\", \"S\", \"S\", \"S\"]D = [1, 13, 21, 14, 1, 12, 25, 1, 14, 1] df = pd.DataFrame( dict(A=A, B=B, C=C, D=D)) fig = px.sunburst(df, path=['C', 'B', 'A'], values='D')fig.show()",
"e": 27970,
"s": 27559,
"text": null
},
{
"code": null,
"e": 27978,
"s": 27970,
"text": "Output:"
},
{
"code": null,
"e": 27992,
"s": 27978,
"text": "Python-Plotly"
},
{
"code": null,
"e": 27999,
"s": 27992,
"text": "Python"
},
{
"code": null,
"e": 28097,
"s": 27999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28106,
"s": 28097,
"text": "Comments"
},
{
"code": null,
"e": 28119,
"s": 28106,
"text": "Old Comments"
},
{
"code": null,
"e": 28147,
"s": 28119,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28197,
"s": 28147,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28219,
"s": 28197,
"text": "Python map() function"
},
{
"code": null,
"e": 28263,
"s": 28219,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 28281,
"s": 28263,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28304,
"s": 28281,
"text": "Taking input in Python"
},
{
"code": null,
"e": 28339,
"s": 28304,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28361,
"s": 28339,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28393,
"s": 28361,
"text": "How to Install PIP on Windows ?"
}
] |
How to do a Custom Sort on Pandas DataFrame | by B. Chen | Towards Data Science | Pandas DataFrame has a built-in method sort_values() to sort values by the given variable(s). The method itself is fairly straightforward to use, however it doesn’t work for custom sorting, for example,
the t-shirt size: XS, S, M, L, and XL
the month: Jan, Feb, Mar, Apr , ....etc
the day of the week: Mon, Tue, Wed, Thu, Fri, Sat, and Sun.
In this article, we are going to take a look at how to do a custom sort on Pandas DataFrame.
Please check out my Github repo for the source code
Suppose we have a dataset about a clothing store:
df = pd.DataFrame({ 'cloth_id': [1001, 1002, 1003, 1004, 1005, 1006], 'size': ['S', 'XL', 'M', 'XS', 'L', 'S'],})
We can see that each cloth has a size value and the data should be sorted by the following order:
XS for extra small
S for small
M for medium
L for large
XL for extra large
However, you will get the following output when calling sort_values('size') .
The output is not we want, but it is technically correct. Under the hood, sort_values() is sorting values by numerical order for number data or character alphabetically for object data.
Here are two common solutions:
Create a new column for custom sortingCast data to category type with orderedness using CategoricalDtype
Create a new column for custom sorting
Cast data to category type with orderedness using CategoricalDtype
In this solution, a mapping DataFrame is needed to represent a custom sort, then a new column will be created according to the mapping, and finally we can sort the data by the new column. Let’s see how this works with the help of an example.
Firstly, let’s create a mapping DataFrame to represent a custom sort.
df_mapping = pd.DataFrame({ 'size': ['XS', 'S', 'M', 'L', 'XL'],})sort_mapping = df_mapping.reset_index().set_index('size')
After that, create a new column size_num with mapped value from sort_mapping.
df['size_num'] = df['size'].map(sort_mapping['index'])
Finally, sort values by the new column size_num.
df.sort_values('size_num')
This certainly does our work. But it has created a spare column and can be less efficient when dealing with a large dataset.
We can solve this more efficiently using CategoricalDtype.
CategoricalDtype is a type for categorical data with the categories and orderedness [1]. It is very useful for creating a custom sort [2]. Let’s see how this works with the help of an example.
Firstly, let’s import CategoricalDtype.
from pandas.api.types import CategoricalDtype
Then, create a custom category type cat_size_order with
the 1st argument set to ['XS', 'S', 'M', 'L', 'XL'] for the unique value of cloth size.
and the 2nd argument ordered=True for this variable to be treated as a ordered categorical.
cat_size_order = CategoricalDtype( ['XS', 'S', 'M', 'L', 'XL'], ordered=True)
After that, call astype(cat_size_order) to cast the size data to the custom category type. By running df['size'], we can see that the size column has been casted to a category type with the order [XS < S < M < L < XL].
>>> df['size'] = df['size'].astype(cat_size_order)>>> df['size']0 S1 XL2 M3 XS4 L5 SName: size, dtype: categoryCategories (5, object): [XS < S < M < L < XL]
And finally, we can call the same method to sort values.
df.sort_values('size')
This works much better. Let’s go ahead and see what is actually happening under the hood.
Now the size column has been casted to a category type, and we could use Series.cat accessor to view categorical properties. Under the hood, it is using the category codes to represent the position in an ordered categorical.
Let’s create a new column codes, so we could compare size and codes values side by side.
df['codes'] = df['size'].cat.codesdf
We can see that XS, S, M, L, and XL has got a code 0, 1, 2, 3, 4, and 5 respectively. Codes are the positions of the actual values in the category type. By running df.info() , we can see that codes are int8.
>>> df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 6 entries, 0 to 5Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 cloth_id 6 non-null int64 1 size 6 non-null category 2 codes 6 non-null int8 dtypes: category(1), int64(1), int8(1)memory usage: 388.0 bytes
Next, let’s make things a little more complicated. Here, we’re going to sort our DataFrame by multiple variables.
df = pd.DataFrame({ 'order_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007], 'customer_id': [10, 12, 12, 12, 10, 10, 10], 'month': ['Feb', 'Jan', 'Jan', 'Feb', 'Feb', 'Jan', 'Feb'], 'day_of_week': ['Mon', 'Wed', 'Sun', 'Tue', 'Sat', 'Mon', 'Thu'],})
Similarly, let’s create 2 custom category types cat_day_of_week and cat_month, and pass them to astype().
cat_day_of_week = CategoricalDtype( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], ordered=True)cat_month = CategoricalDtype( ['Jan', 'Feb', 'Mar', 'Apr'], ordered=True,)df['day_of_week'] = df['day_of_week'].astype(cat_day_of_week)df['month'] = df['month'].astype(cat_month)
To sort by multiple variables, we just need to pass a list to sort_values() in stead. For example, sort by month and day_of_week.
df.sort_values(['month', 'day_of_week'])
And sort by customer_id, month and day_of_week.
df.sort_values(['customer_id', 'month', 'day_of_week'])
Thanks for reading.
Please checkout the notebook on my Github for the source code.
Stay tuned if you are interested in the practical aspect of machine learning.
Creating conditional columns on Pandas with Numpy select() and where() methods
When to use Pandas transform() function
Difference between apply() and transform() in Pandas
Using Pandas method chaining to improve code readability
Working with datetime in Pandas DataFrame
Pandas read_csv() tricks you should know
4 tricks you should know to parse date columns with Pandas read_csv()
More can be found from my Github
[1] Pandas.CategoricalDtype API
[2] Pandas Categorical CategoricalDtype tutorial | [
{
"code": null,
"e": 375,
"s": 172,
"text": "Pandas DataFrame has a built-in method sort_values() to sort values by the given variable(s). The method itself is fairly straightforward to use, however it doesn’t work for custom sorting, for example,"
},
{
"code": null,
"e": 413,
"s": 375,
"text": "the t-shirt size: XS, S, M, L, and XL"
},
{
"code": null,
"e": 453,
"s": 413,
"text": "the month: Jan, Feb, Mar, Apr , ....etc"
},
{
"code": null,
"e": 513,
"s": 453,
"text": "the day of the week: Mon, Tue, Wed, Thu, Fri, Sat, and Sun."
},
{
"code": null,
"e": 606,
"s": 513,
"text": "In this article, we are going to take a look at how to do a custom sort on Pandas DataFrame."
},
{
"code": null,
"e": 658,
"s": 606,
"text": "Please check out my Github repo for the source code"
},
{
"code": null,
"e": 708,
"s": 658,
"text": "Suppose we have a dataset about a clothing store:"
},
{
"code": null,
"e": 828,
"s": 708,
"text": "df = pd.DataFrame({ 'cloth_id': [1001, 1002, 1003, 1004, 1005, 1006], 'size': ['S', 'XL', 'M', 'XS', 'L', 'S'],})"
},
{
"code": null,
"e": 926,
"s": 828,
"text": "We can see that each cloth has a size value and the data should be sorted by the following order:"
},
{
"code": null,
"e": 945,
"s": 926,
"text": "XS for extra small"
},
{
"code": null,
"e": 957,
"s": 945,
"text": "S for small"
},
{
"code": null,
"e": 970,
"s": 957,
"text": "M for medium"
},
{
"code": null,
"e": 982,
"s": 970,
"text": "L for large"
},
{
"code": null,
"e": 1001,
"s": 982,
"text": "XL for extra large"
},
{
"code": null,
"e": 1079,
"s": 1001,
"text": "However, you will get the following output when calling sort_values('size') ."
},
{
"code": null,
"e": 1265,
"s": 1079,
"text": "The output is not we want, but it is technically correct. Under the hood, sort_values() is sorting values by numerical order for number data or character alphabetically for object data."
},
{
"code": null,
"e": 1296,
"s": 1265,
"text": "Here are two common solutions:"
},
{
"code": null,
"e": 1401,
"s": 1296,
"text": "Create a new column for custom sortingCast data to category type with orderedness using CategoricalDtype"
},
{
"code": null,
"e": 1440,
"s": 1401,
"text": "Create a new column for custom sorting"
},
{
"code": null,
"e": 1507,
"s": 1440,
"text": "Cast data to category type with orderedness using CategoricalDtype"
},
{
"code": null,
"e": 1749,
"s": 1507,
"text": "In this solution, a mapping DataFrame is needed to represent a custom sort, then a new column will be created according to the mapping, and finally we can sort the data by the new column. Let’s see how this works with the help of an example."
},
{
"code": null,
"e": 1819,
"s": 1749,
"text": "Firstly, let’s create a mapping DataFrame to represent a custom sort."
},
{
"code": null,
"e": 1946,
"s": 1819,
"text": "df_mapping = pd.DataFrame({ 'size': ['XS', 'S', 'M', 'L', 'XL'],})sort_mapping = df_mapping.reset_index().set_index('size')"
},
{
"code": null,
"e": 2024,
"s": 1946,
"text": "After that, create a new column size_num with mapped value from sort_mapping."
},
{
"code": null,
"e": 2079,
"s": 2024,
"text": "df['size_num'] = df['size'].map(sort_mapping['index'])"
},
{
"code": null,
"e": 2128,
"s": 2079,
"text": "Finally, sort values by the new column size_num."
},
{
"code": null,
"e": 2155,
"s": 2128,
"text": "df.sort_values('size_num')"
},
{
"code": null,
"e": 2280,
"s": 2155,
"text": "This certainly does our work. But it has created a spare column and can be less efficient when dealing with a large dataset."
},
{
"code": null,
"e": 2339,
"s": 2280,
"text": "We can solve this more efficiently using CategoricalDtype."
},
{
"code": null,
"e": 2532,
"s": 2339,
"text": "CategoricalDtype is a type for categorical data with the categories and orderedness [1]. It is very useful for creating a custom sort [2]. Let’s see how this works with the help of an example."
},
{
"code": null,
"e": 2572,
"s": 2532,
"text": "Firstly, let’s import CategoricalDtype."
},
{
"code": null,
"e": 2618,
"s": 2572,
"text": "from pandas.api.types import CategoricalDtype"
},
{
"code": null,
"e": 2674,
"s": 2618,
"text": "Then, create a custom category type cat_size_order with"
},
{
"code": null,
"e": 2762,
"s": 2674,
"text": "the 1st argument set to ['XS', 'S', 'M', 'L', 'XL'] for the unique value of cloth size."
},
{
"code": null,
"e": 2854,
"s": 2762,
"text": "and the 2nd argument ordered=True for this variable to be treated as a ordered categorical."
},
{
"code": null,
"e": 2939,
"s": 2854,
"text": "cat_size_order = CategoricalDtype( ['XS', 'S', 'M', 'L', 'XL'], ordered=True)"
},
{
"code": null,
"e": 3158,
"s": 2939,
"text": "After that, call astype(cat_size_order) to cast the size data to the custom category type. By running df['size'], we can see that the size column has been casted to a category type with the order [XS < S < M < L < XL]."
},
{
"code": null,
"e": 3337,
"s": 3158,
"text": ">>> df['size'] = df['size'].astype(cat_size_order)>>> df['size']0 S1 XL2 M3 XS4 L5 SName: size, dtype: categoryCategories (5, object): [XS < S < M < L < XL]"
},
{
"code": null,
"e": 3394,
"s": 3337,
"text": "And finally, we can call the same method to sort values."
},
{
"code": null,
"e": 3417,
"s": 3394,
"text": "df.sort_values('size')"
},
{
"code": null,
"e": 3507,
"s": 3417,
"text": "This works much better. Let’s go ahead and see what is actually happening under the hood."
},
{
"code": null,
"e": 3732,
"s": 3507,
"text": "Now the size column has been casted to a category type, and we could use Series.cat accessor to view categorical properties. Under the hood, it is using the category codes to represent the position in an ordered categorical."
},
{
"code": null,
"e": 3821,
"s": 3732,
"text": "Let’s create a new column codes, so we could compare size and codes values side by side."
},
{
"code": null,
"e": 3858,
"s": 3821,
"text": "df['codes'] = df['size'].cat.codesdf"
},
{
"code": null,
"e": 4066,
"s": 3858,
"text": "We can see that XS, S, M, L, and XL has got a code 0, 1, 2, 3, 4, and 5 respectively. Codes are the positions of the actual values in the category type. By running df.info() , we can see that codes are int8."
},
{
"code": null,
"e": 4435,
"s": 4066,
"text": ">>> df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 6 entries, 0 to 5Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 cloth_id 6 non-null int64 1 size 6 non-null category 2 codes 6 non-null int8 dtypes: category(1), int64(1), int8(1)memory usage: 388.0 bytes"
},
{
"code": null,
"e": 4549,
"s": 4435,
"text": "Next, let’s make things a little more complicated. Here, we’re going to sort our DataFrame by multiple variables."
},
{
"code": null,
"e": 4810,
"s": 4549,
"text": "df = pd.DataFrame({ 'order_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007], 'customer_id': [10, 12, 12, 12, 10, 10, 10], 'month': ['Feb', 'Jan', 'Jan', 'Feb', 'Feb', 'Jan', 'Feb'], 'day_of_week': ['Mon', 'Wed', 'Sun', 'Tue', 'Sat', 'Mon', 'Thu'],})"
},
{
"code": null,
"e": 4916,
"s": 4810,
"text": "Similarly, let’s create 2 custom category types cat_day_of_week and cat_month, and pass them to astype()."
},
{
"code": null,
"e": 5209,
"s": 4916,
"text": "cat_day_of_week = CategoricalDtype( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], ordered=True)cat_month = CategoricalDtype( ['Jan', 'Feb', 'Mar', 'Apr'], ordered=True,)df['day_of_week'] = df['day_of_week'].astype(cat_day_of_week)df['month'] = df['month'].astype(cat_month)"
},
{
"code": null,
"e": 5339,
"s": 5209,
"text": "To sort by multiple variables, we just need to pass a list to sort_values() in stead. For example, sort by month and day_of_week."
},
{
"code": null,
"e": 5380,
"s": 5339,
"text": "df.sort_values(['month', 'day_of_week'])"
},
{
"code": null,
"e": 5428,
"s": 5380,
"text": "And sort by customer_id, month and day_of_week."
},
{
"code": null,
"e": 5484,
"s": 5428,
"text": "df.sort_values(['customer_id', 'month', 'day_of_week'])"
},
{
"code": null,
"e": 5504,
"s": 5484,
"text": "Thanks for reading."
},
{
"code": null,
"e": 5567,
"s": 5504,
"text": "Please checkout the notebook on my Github for the source code."
},
{
"code": null,
"e": 5645,
"s": 5567,
"text": "Stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 5724,
"s": 5645,
"text": "Creating conditional columns on Pandas with Numpy select() and where() methods"
},
{
"code": null,
"e": 5764,
"s": 5724,
"text": "When to use Pandas transform() function"
},
{
"code": null,
"e": 5817,
"s": 5764,
"text": "Difference between apply() and transform() in Pandas"
},
{
"code": null,
"e": 5874,
"s": 5817,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 5916,
"s": 5874,
"text": "Working with datetime in Pandas DataFrame"
},
{
"code": null,
"e": 5957,
"s": 5916,
"text": "Pandas read_csv() tricks you should know"
},
{
"code": null,
"e": 6027,
"s": 5957,
"text": "4 tricks you should know to parse date columns with Pandas read_csv()"
},
{
"code": null,
"e": 6060,
"s": 6027,
"text": "More can be found from my Github"
},
{
"code": null,
"e": 6092,
"s": 6060,
"text": "[1] Pandas.CategoricalDtype API"
}
] |
Responsive analog clock using HTML, CSS and Vanilla JavaScript - GeeksforGeeks | 04 Mar, 2021
In this article, we are going to create an Analog Clock. This is mainly based on HTML, CSS & Vanilla JavaScript.
Approach:
Create an HTML file in which we are going to add the main div, further on we are adding 4 div tags for an hour, minute, second hands & for the pin.Create a CSS file for styling our web-page and for assigning different lengths to the different hands.Create a JavaScript file for creating a brief logic for rotation of different clock-hands.
Create an HTML file in which we are going to add the main div, further on we are adding 4 div tags for an hour, minute, second hands & for the pin.
Create a CSS file for styling our web-page and for assigning different lengths to the different hands.
Create a JavaScript file for creating a brief logic for rotation of different clock-hands.
Logic for rotation of clock hands:
1. Hour Hand
For Achieving 12hrs,
hour hand moves 360deg.
i.e. 12hrs ⇢ 360degs
so, 1hr ⇢ 30degs
and, 60mins ⇢ 30degs
so, 1min ⇢ 0.5degs
Total Rotation of hour hand:
(30deg * hrs) + (0.5deg * mins)
2. Minute Hand
For Achieving 60mins,
hour hand moves 360deg.
i.e. 60mins ⇢ 360degs
so, 1min ⇢ 6degs
Total Rotation of minute hand:
6deg * mins
3. Second Hand
For Achieving 60secs,
hour hand moves 360deg.
i.e. 60secs ⇢ 360degs
so, 1sec ⇢ 6degs
Total Rotation of minute hand:
6deg * secs
HTML Code:
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Analog Clock</title> <link rel="stylesheet" href="style.css"></head> <body> <div class="clock"> <div class="hr"></div> <div class="min"></div> <div class="sec"></div> <div class="pin"></div> </div> <script src="index.js"></script></body> </html>
Code Explanation:
First, create an HTML file (index.html).
Now after the creation of our HTML file, we are going to give a title to our webpage using <title> tag. It should be placed inside the <head> section.
Then we link the CSS file that provides all the styles to our HTML. This is also placed in between the <head> tag.
Coming to the body section of our HTML code.Firstly, create a main div as a clock.In that div add 4divs for an hour, minute, second hands & for the pin.At the end of our body add <script> tag which links the JS file with our HTML file.
Firstly, create a main div as a clock.
In that div add 4divs for an hour, minute, second hands & for the pin.
At the end of our body add <script> tag which links the JS file with our HTML file.
CSS Code:
/* Restoring browser effects */* { margin: 0; padding: 0; box-sizing: border-box; ;} /* All of the same styling to the body */body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #000; background-image: linear-gradient( 70deg, black, white);} /* Sizing, positioning of main dial of the clock */.clock { width: 40vw; height: 40vw; background-image: linear-gradient( 70deg, black, white); background-size: cover; box-shadow: 0 3em 5.8em; border-radius: 50%; position: relative;} .hr,.min,.sec { width: 1%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -100%); transform-origin: bottom; z-index: 2; border-radius: 2em;} .pin { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 1em; height: 1em; background: rgb(38, 0, 255); border: 2px solid #ffffff; border-radius: 10em; margin: auto; z-index: 10;} /* Different length of different hands of clock */.hr { height: 25%; background-color: #ff0000;} .min { height: 30%; background-color: #ff9900;} .sec { height: 40%; background-color: #99ff00; transform-origin: 50% 85%;}
Code Explanation: CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. In CSS, we have to include the following points:
Restore all the browser effects.Use classes and id’s to give effects to HTML elements.
Restore all the browser effects.
Use classes and id’s to give effects to HTML elements.
JS Code:
Javascript
// Selecting all of the css classes on which// we want to apply functionalitiesconst hr = document.querySelector('.hr')const min = document.querySelector('.min')const sec = document.querySelector('.sec') // Setting up the period of workingsetInterval(() => { // Extracting the current time // from DATE() function let day = new Date() let hour = day.getHours() let minutes = day.getMinutes() let seconds = day.getSeconds() // Formula that is explained above for // the rotation of different hands let hrrotation = (30 * hour) + (0.5 * minutes); let minrotation = 6 * minutes; let secrotation = 6 * seconds; hr.style.transform = `translate(-50%,-100%) rotate(${hrrotation}deg)` min.style.transform = `translate(-50%,-100%) rotate(${minrotation}deg)` sec.style.transform = `translate(-50%,-85%) rotate(${secrotation}deg)`});
Code Explanation:
The setInterval() function is used for the execution of function for a specific period of time. For more details click here.
The Date() function is used for returning today date, current time(hours, minutes, seconds).
Complete Code:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> /* Restoring browser effects */ * { margin: 0; padding: 0; box-sizing: border-box; } /* All of the same styling to the body */ body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #000; background-image: linear-gradient( 70deg, black, white); } /* Sizing, positioning of main dial of the clock */ .clock { width: 40vw; height: 40vw; background-image: linear-gradient( 70deg, black, white); background-size: cover; box-shadow: 0 3em 5.8em; border-radius: 50%; position: relative; } .hr, .min, .sec { width: 1%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -100%); transform-origin: bottom; z-index: 2; border-radius: 2em; } .pin { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 1em; height: 1em; background: rgb(38, 0, 255); border: 2px solid #ffffff; border-radius: 10em; margin: auto; z-index: 10; } /* Different length of different hands of clock */ .hr { height: 25%; background-color: #ff0000; } .min { height: 30%; background-color: #ff9900; } .sec { height: 40%; background-color: #99ff00; transform-origin: 50% 85%; } </style></head> <body> <div class="clock"> <div class="hr"></div> <div class="min"></div> <div class="sec"></div> <div class="pin"></div> </div> <script> // Selecting all of the css classes // on which we want to apply functionalities const hr = document.querySelector('.hr') const min = document.querySelector('.min') const sec = document.querySelector('.sec') // Setting up the period of working setInterval(() => { // Extracting the current time // from DATE() function let day = new Date() let hour = day.getHours() let minutes = day.getMinutes() let seconds = day.getSeconds() // Formula that is explained above for // the rotation of different hands let hrrotation = (30 * hour) + (0.5 * minutes); let minrotation = 6 * minutes; let secrotation = 6 * seconds; hr.style.transform = `translate(-50%,-100%) rotate(${hrrotation}deg)` min.style.transform = `translate(-50%,-100%) rotate(${minrotation}deg)` sec.style.transform = `translate(-50%,-85%) rotate(${secrotation}deg)` }); </script></body> </html>
Output:
CSS-Properties
CSS-Selectors
javascript-math
JavaScript-Questions
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n04 Mar, 2021"
},
{
"code": null,
"e": 25098,
"s": 24985,
"text": "In this article, we are going to create an Analog Clock. This is mainly based on HTML, CSS & Vanilla JavaScript."
},
{
"code": null,
"e": 25108,
"s": 25098,
"text": "Approach:"
},
{
"code": null,
"e": 25448,
"s": 25108,
"text": "Create an HTML file in which we are going to add the main div, further on we are adding 4 div tags for an hour, minute, second hands & for the pin.Create a CSS file for styling our web-page and for assigning different lengths to the different hands.Create a JavaScript file for creating a brief logic for rotation of different clock-hands."
},
{
"code": null,
"e": 25596,
"s": 25448,
"text": "Create an HTML file in which we are going to add the main div, further on we are adding 4 div tags for an hour, minute, second hands & for the pin."
},
{
"code": null,
"e": 25699,
"s": 25596,
"text": "Create a CSS file for styling our web-page and for assigning different lengths to the different hands."
},
{
"code": null,
"e": 25790,
"s": 25699,
"text": "Create a JavaScript file for creating a brief logic for rotation of different clock-hands."
},
{
"code": null,
"e": 25825,
"s": 25790,
"text": "Logic for rotation of clock hands:"
},
{
"code": null,
"e": 25838,
"s": 25825,
"text": "1. Hour Hand"
},
{
"code": null,
"e": 26063,
"s": 25838,
"text": "For Achieving 12hrs,\nhour hand moves 360deg.\n\ni.e. 12hrs ⇢ 360degs\n\nso, 1hr ⇢ 30degs\n\nand, 60mins ⇢ 30degs\n \nso, 1min ⇢ 0.5degs\n \nTotal Rotation of hour hand:\n (30deg * hrs) + (0.5deg * mins)"
},
{
"code": null,
"e": 26078,
"s": 26063,
"text": "2. Minute Hand"
},
{
"code": null,
"e": 26234,
"s": 26078,
"text": "For Achieving 60mins,\nhour hand moves 360deg.\n\ni.e. 60mins ⇢ 360degs\n\nso, 1min ⇢ 6degs\n \nTotal Rotation of minute hand:\n 6deg * mins"
},
{
"code": null,
"e": 26249,
"s": 26234,
"text": "3. Second Hand"
},
{
"code": null,
"e": 26405,
"s": 26249,
"text": "For Achieving 60secs,\nhour hand moves 360deg.\n\ni.e. 60secs ⇢ 360degs\n\nso, 1sec ⇢ 6degs\n \nTotal Rotation of minute hand:\n 6deg * secs"
},
{
"code": null,
"e": 26416,
"s": 26405,
"text": "HTML Code:"
},
{
"code": null,
"e": 26421,
"s": 26416,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Analog Clock</title> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div class=\"clock\"> <div class=\"hr\"></div> <div class=\"min\"></div> <div class=\"sec\"></div> <div class=\"pin\"></div> </div> <script src=\"index.js\"></script></body> </html>",
"e": 26767,
"s": 26421,
"text": null
},
{
"code": null,
"e": 26785,
"s": 26767,
"text": "Code Explanation:"
},
{
"code": null,
"e": 26826,
"s": 26785,
"text": "First, create an HTML file (index.html)."
},
{
"code": null,
"e": 26977,
"s": 26826,
"text": "Now after the creation of our HTML file, we are going to give a title to our webpage using <title> tag. It should be placed inside the <head> section."
},
{
"code": null,
"e": 27092,
"s": 26977,
"text": "Then we link the CSS file that provides all the styles to our HTML. This is also placed in between the <head> tag."
},
{
"code": null,
"e": 27328,
"s": 27092,
"text": "Coming to the body section of our HTML code.Firstly, create a main div as a clock.In that div add 4divs for an hour, minute, second hands & for the pin.At the end of our body add <script> tag which links the JS file with our HTML file."
},
{
"code": null,
"e": 27367,
"s": 27328,
"text": "Firstly, create a main div as a clock."
},
{
"code": null,
"e": 27438,
"s": 27367,
"text": "In that div add 4divs for an hour, minute, second hands & for the pin."
},
{
"code": null,
"e": 27522,
"s": 27438,
"text": "At the end of our body add <script> tag which links the JS file with our HTML file."
},
{
"code": null,
"e": 27532,
"s": 27522,
"text": "CSS Code:"
},
{
"code": "/* Restoring browser effects */* { margin: 0; padding: 0; box-sizing: border-box; ;} /* All of the same styling to the body */body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #000; background-image: linear-gradient( 70deg, black, white);} /* Sizing, positioning of main dial of the clock */.clock { width: 40vw; height: 40vw; background-image: linear-gradient( 70deg, black, white); background-size: cover; box-shadow: 0 3em 5.8em; border-radius: 50%; position: relative;} .hr,.min,.sec { width: 1%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -100%); transform-origin: bottom; z-index: 2; border-radius: 2em;} .pin { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 1em; height: 1em; background: rgb(38, 0, 255); border: 2px solid #ffffff; border-radius: 10em; margin: auto; z-index: 10;} /* Different length of different hands of clock */.hr { height: 25%; background-color: #ff0000;} .min { height: 30%; background-color: #ff9900;} .sec { height: 40%; background-color: #99ff00; transform-origin: 50% 85%;}",
"e": 28803,
"s": 27532,
"text": null
},
{
"code": null,
"e": 28992,
"s": 28803,
"text": "Code Explanation: CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. In CSS, we have to include the following points:"
},
{
"code": null,
"e": 29079,
"s": 28992,
"text": "Restore all the browser effects.Use classes and id’s to give effects to HTML elements."
},
{
"code": null,
"e": 29112,
"s": 29079,
"text": "Restore all the browser effects."
},
{
"code": null,
"e": 29167,
"s": 29112,
"text": "Use classes and id’s to give effects to HTML elements."
},
{
"code": null,
"e": 29176,
"s": 29167,
"text": "JS Code:"
},
{
"code": null,
"e": 29187,
"s": 29176,
"text": "Javascript"
},
{
"code": "// Selecting all of the css classes on which// we want to apply functionalitiesconst hr = document.querySelector('.hr')const min = document.querySelector('.min')const sec = document.querySelector('.sec') // Setting up the period of workingsetInterval(() => { // Extracting the current time // from DATE() function let day = new Date() let hour = day.getHours() let minutes = day.getMinutes() let seconds = day.getSeconds() // Formula that is explained above for // the rotation of different hands let hrrotation = (30 * hour) + (0.5 * minutes); let minrotation = 6 * minutes; let secrotation = 6 * seconds; hr.style.transform = `translate(-50%,-100%) rotate(${hrrotation}deg)` min.style.transform = `translate(-50%,-100%) rotate(${minrotation}deg)` sec.style.transform = `translate(-50%,-85%) rotate(${secrotation}deg)`});",
"e": 30082,
"s": 29187,
"text": null
},
{
"code": null,
"e": 30100,
"s": 30082,
"text": "Code Explanation:"
},
{
"code": null,
"e": 30225,
"s": 30100,
"text": "The setInterval() function is used for the execution of function for a specific period of time. For more details click here."
},
{
"code": null,
"e": 30318,
"s": 30225,
"text": "The Date() function is used for returning today date, current time(hours, minutes, seconds)."
},
{
"code": null,
"e": 30333,
"s": 30318,
"text": "Complete Code:"
},
{
"code": null,
"e": 30338,
"s": 30333,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Restoring browser effects */ * { margin: 0; padding: 0; box-sizing: border-box; } /* All of the same styling to the body */ body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #000; background-image: linear-gradient( 70deg, black, white); } /* Sizing, positioning of main dial of the clock */ .clock { width: 40vw; height: 40vw; background-image: linear-gradient( 70deg, black, white); background-size: cover; box-shadow: 0 3em 5.8em; border-radius: 50%; position: relative; } .hr, .min, .sec { width: 1%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -100%); transform-origin: bottom; z-index: 2; border-radius: 2em; } .pin { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 1em; height: 1em; background: rgb(38, 0, 255); border: 2px solid #ffffff; border-radius: 10em; margin: auto; z-index: 10; } /* Different length of different hands of clock */ .hr { height: 25%; background-color: #ff0000; } .min { height: 30%; background-color: #ff9900; } .sec { height: 40%; background-color: #99ff00; transform-origin: 50% 85%; } </style></head> <body> <div class=\"clock\"> <div class=\"hr\"></div> <div class=\"min\"></div> <div class=\"sec\"></div> <div class=\"pin\"></div> </div> <script> // Selecting all of the css classes // on which we want to apply functionalities const hr = document.querySelector('.hr') const min = document.querySelector('.min') const sec = document.querySelector('.sec') // Setting up the period of working setInterval(() => { // Extracting the current time // from DATE() function let day = new Date() let hour = day.getHours() let minutes = day.getMinutes() let seconds = day.getSeconds() // Formula that is explained above for // the rotation of different hands let hrrotation = (30 * hour) + (0.5 * minutes); let minrotation = 6 * minutes; let secrotation = 6 * seconds; hr.style.transform = `translate(-50%,-100%) rotate(${hrrotation}deg)` min.style.transform = `translate(-50%,-100%) rotate(${minrotation}deg)` sec.style.transform = `translate(-50%,-85%) rotate(${secrotation}deg)` }); </script></body> </html>",
"e": 33563,
"s": 30338,
"text": null
},
{
"code": null,
"e": 33571,
"s": 33563,
"text": "Output:"
},
{
"code": null,
"e": 33586,
"s": 33571,
"text": "CSS-Properties"
},
{
"code": null,
"e": 33600,
"s": 33586,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 33616,
"s": 33600,
"text": "javascript-math"
},
{
"code": null,
"e": 33637,
"s": 33616,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 33661,
"s": 33637,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33665,
"s": 33661,
"text": "CSS"
},
{
"code": null,
"e": 33670,
"s": 33665,
"text": "HTML"
},
{
"code": null,
"e": 33681,
"s": 33670,
"text": "JavaScript"
},
{
"code": null,
"e": 33700,
"s": 33681,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33705,
"s": 33700,
"text": "HTML"
},
{
"code": null,
"e": 33803,
"s": 33705,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33812,
"s": 33803,
"text": "Comments"
},
{
"code": null,
"e": 33825,
"s": 33812,
"text": "Old Comments"
},
{
"code": null,
"e": 33862,
"s": 33825,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33891,
"s": 33862,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 33930,
"s": 33891,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 33972,
"s": 33930,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 34007,
"s": 33972,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 34067,
"s": 34007,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 34128,
"s": 34067,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 34181,
"s": 34128,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 34231,
"s": 34181,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
How to rotate an image in imageview by an angle on Android using Kotlin? | This example demonstrates how to rotate an image in imageview by an angle on Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="600dp"
android:src="@drawable/image" />
<Button
android:layout_above="@+id/imageView"
android:id="@+id/btnRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:text="Rotate View"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
lateinit var btnRotate: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
btnRotate = findViewById(R.id.btnRotate)
btnRotate.setOnClickListener { imageView.rotation = 90f }
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "This example demonstrates how to rotate an image in imageview by an angle on Android using Kotlin."
},
{
"code": null,
"e": 1290,
"s": 1161,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1355,
"s": 1290,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2170,
"s": 1355,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"2dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"600dp\"\n android:src=\"@drawable/image\" />\n <Button\n android:layout_above=\"@+id/imageView\"\n android:id=\"@+id/btnRotate\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerInParent=\"true\"\n android:text=\"Rotate View\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2225,
"s": 2170,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2806,
"s": 2225,
"text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var imageView: ImageView\n lateinit var btnRotate: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n imageView = findViewById(R.id.imageView)\n btnRotate = findViewById(R.id.btnRotate)\n btnRotate.setOnClickListener { imageView.rotation = 90f }\n }\n}"
},
{
"code": null,
"e": 2861,
"s": 2806,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3532,
"s": 2861,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3880,
"s": 3532,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Tryit Editor v3.7 | CSS Rounded Corners
Tryit: Creating rounded corners | [
{
"code": null,
"e": 29,
"s": 9,
"text": "CSS Rounded Corners"
}
] |
Best data type for storing currency values in a MySQL database? | For representation of money, we need to use Decimal (TotalDigitsinteger, DigitsAfterDecimalinteger) method.
Let’s say, we need to display the value 345.66. For that, count how many digits are available. In value 345.66, there are 5 digits in total and 2 digits after decimal point, which is 66.
We can represent the same with the help of Decimal() method from MySQL. Here is the exact representation.
DECIMAL(5,2)
Let us first create a table and consider the same above representation for our example −
mysql> create table MoneyRepresentation
-> (
-> Money Decimal(5,2)
-> );
Query OK, 0 rows affected (0.65 sec)
Let us insert the same value i.e. 345.66
mysql> insert into MoneyRepresentation values(345.66);
Query OK, 1 row affected (0.13 sec)
Display all records with the help of SELECT statement. The query is as follows −
mysql> select *from MoneyRepresentation;
The following is the output.
+--------+
| Money |
+--------+
| 345.66 |
+--------+
1 row in set (0.00 sec)
Look at the above output, we got 5 digits total and added 2 digits after decimal point because we have set the function as
Decimal(5,2) | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "For representation of money, we need to use Decimal (TotalDigitsinteger, DigitsAfterDecimalinteger) method."
},
{
"code": null,
"e": 1357,
"s": 1170,
"text": "Let’s say, we need to display the value 345.66. For that, count how many digits are available. In value 345.66, there are 5 digits in total and 2 digits after decimal point, which is 66."
},
{
"code": null,
"e": 1463,
"s": 1357,
"text": "We can represent the same with the help of Decimal() method from MySQL. Here is the exact representation."
},
{
"code": null,
"e": 1476,
"s": 1463,
"text": "DECIMAL(5,2)"
},
{
"code": null,
"e": 1565,
"s": 1476,
"text": "Let us first create a table and consider the same above representation for our example −"
},
{
"code": null,
"e": 1684,
"s": 1565,
"text": "mysql> create table MoneyRepresentation\n -> (\n -> Money Decimal(5,2)\n -> );\nQuery OK, 0 rows affected (0.65 sec)"
},
{
"code": null,
"e": 1725,
"s": 1684,
"text": "Let us insert the same value i.e. 345.66"
},
{
"code": null,
"e": 1816,
"s": 1725,
"text": "mysql> insert into MoneyRepresentation values(345.66);\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1897,
"s": 1816,
"text": "Display all records with the help of SELECT statement. The query is as follows −"
},
{
"code": null,
"e": 1938,
"s": 1897,
"text": "mysql> select *from MoneyRepresentation;"
},
{
"code": null,
"e": 1967,
"s": 1938,
"text": "The following is the output."
},
{
"code": null,
"e": 2047,
"s": 1967,
"text": "+--------+\n| Money |\n+--------+\n| 345.66 |\n+--------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 2170,
"s": 2047,
"text": "Look at the above output, we got 5 digits total and added 2 digits after decimal point because we have set the function as"
},
{
"code": null,
"e": 2183,
"s": 2170,
"text": "Decimal(5,2)"
}
] |
Top K Frequent Elements in Array - | | Practice | GeeksforGeeks | Given a non-empty array of integers, find the top k elements which have the highest frequency in the array. If two numbers have the same frequency then the larger number should be given preference.
Note: Print the elements according to the frequency count (from highest to lowest) and if the frequency is equal then larger number will be given preference.
Example 1:
Input:
N = 6
nums = {1,1,1,2,2,3}
k = 2
Output: {1, 2}
Example 2:
Input:
N = 8
nums = {1,1,2,2,3,3,3,4}
k = 2
Output: {3, 2}
Explanation: Elements 1 and 2 have the
same frequency ie. 2. Therefore, in this
case, the answer includes the element 2
as 2 > 1.
User Task:
The task is to complete the function topK() that takes the array and integer k as input and returns a list of top k frequent elements.
Expected Time Complexity : O(NlogN)
Expected Auxilliary Space : O(N)
Constraints:
1 <= N <= 105
1<=A[i]<=105
0
hrithikraina20011 week ago
priority_queue<pair<int,int> >pq;
map<int,int>mp;
vector<int>ans;
for(int i=0;i<nums.size();i++)
{
mp[nums[i]]++;
}
for(auto it:mp)
{
pq.push({it.second,it.first});
}
for(int i=0;i<k;i++)
{
ans.push_back(pq.top().second);
pq.pop();
}
return ans;
0
akhilyadav00882 weeks ago
c++ solution with best time complexity
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> minh; unordered_map<int,int> mp; int n= nums.size(); for(int i=0;i<n;i++) mp[nums[i]]++; for(auto i=mp.begin();i!=mp.end();i++) { minh.push({i->second , i->first}); if(minh.size()>k) minh.pop(); } vector<int> res; while(minh.size()>0) { res.push_back((minh.top()).second); minh.pop(); } reverse(res.begin(), res.end()); return res;
+1
geeky20092 weeks ago
vector<int> topK(vector<int>& nums, int k) { // Code here map<int,int>m; vector<int>v; for(int i=0;i<nums.size();i++){ m[nums[i]]++; } vector<pair<int,int>>v2; for(auto x:m){ v2.push_back({x.second,x.first}); } sort(v2.begin(),v2.end(),greater<pair<int,int>>()); for(int i=0;i<k;i++){ v.push_back(v2[i].second); } return v; }
0
mitradiptamoy2 weeks ago
//C++ using unordered_map
vector<int> topK(vector<int>& nums, int k) { // Code here unordered_map<int,int>mp; vector<int>ans; vector<pair<int,int>>vec; for(int i=0;i<nums.size();i++) { mp[nums[i]]=mp[nums[i]]+1; } for(auto it:mp) { vec.push_back({it.second,it.first}); } sort(vec.begin(),vec.end(),greater<pair<int,int>>()); for(int i=0;i<k;i++) { ans.push_back(vec[i].second); } return ans; }
+1
sagrikasoni2 weeks ago
class Solution {
public int[] topK(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int val: nums)
map.put(val, map.getOrDefault(val, 0)+1);
PriorityQueue<Integer> pQueue= new PriorityQueue<>((a,b)->{
if(map.get(a)==map.get(b))
return a-b;
return map.get(a) - map.get(b);
});
for(int n: map.keySet())
{
pQueue.add(n);
if(pQueue.size()>k)
pQueue.poll();
}
int [] ans = new int[k];
for(int i = k - 1; i >= 0;i--) {
ans[i] = pQueue.poll();
}
return ans;
}
}
+1
siddharth1923co10682 weeks ago
tym 0.42 Brute force approach
/*firstly creating a hash map for storing freaquency of each element.
then placing this element along with frequecny in vector pair
applying sorting to the given array then in final step returning the first k most frequent element in the array.*/
vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int>map; vector<pair<int,int>>high; vector<int>ans; for(int i=0;i<nums.size();i++){ map[nums[i]]++; } for(auto it:map){ auto a=make_pair(it.second,it.first); high.push_back(a); } //for (auto it=map.begin(); it!=map.end(); ++it) sort(high.begin(),high.end(),greater<pair<int,int>>()); for(int i=0;i<k;i++){ ans.push_back(high[i].second); } return ans; }
+2
aryany8712 weeks ago
//Time Complexity-O(nlogk) , Auxiliary Space-O(n)
vector<int> topK(vector<int>& a, int k) { unordered_map<int,int> m; for(auto it : a){//-O(n) m[it]++; } //min heap priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq; for(auto it : m){//-O(nlogk) pq.push({it.second,it.first}); //inserting freq first as it's sorted using first element by default if(pq.size()>k){ pq.pop(); } } vector<int> v(k); for(int i=k-1;i>=0;i--){//O(klogk) auto it =pq.top(); v[i]=it.second; pq.pop(); } return v; }
0
aryany871
This comment was deleted.
0
princechaudhary0073 weeks ago
timeComplexity=(NlogN)
//
static bool comp(pair<int,int>a,pair<int,int>b){ if(a.second==b.second) return a.first>b.first; return a.second>b.second; } vector<int> topK(vector<int>& arr, int k) { // Code here unordered_map<int,int>mp; int n=arr.size(); for(int i=0;i<n;i++){ mp[arr[i]]++; } vector<pair<int,int>>v; for(auto x:mp){ v.push_back(x); } sort(v.begin(),v.end(),comp); vector<int>ans; for(int i=0;i<k;i++){ ans.push_back(v[i].first); } return ans; }};
0
itachinamikaze2211 month ago
JAVA
class Solution { public int[] topK(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for(int val: nums) map.put(val, map.getOrDefault(val, 0)+1); PriorityQueue<Integer> pQueue= new PriorityQueue<>((a,b)->{ int aValue=map.get(a); int bValue=map.get(b); if(aValue==bValue) return a-b; return aValue - bValue; }); for(int n: map.keySet()) { pQueue.add(n); if(pQueue.size()>k) pQueue.poll(); } int []a = new int[k]; int i=k-1; while(pQueue.isEmpty()==false) { int n=pQueue.poll(); a[i]=n; i--; } return a; }}
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": 437,
"s": 238,
"text": "Given a non-empty array of integers, find the top k elements which have the highest frequency in the array. If two numbers have the same frequency then the larger number should be given preference. "
},
{
"code": null,
"e": 595,
"s": 437,
"text": "Note: Print the elements according to the frequency count (from highest to lowest) and if the frequency is equal then larger number will be given preference."
},
{
"code": null,
"e": 606,
"s": 595,
"text": "Example 1:"
},
{
"code": null,
"e": 662,
"s": 606,
"text": "Input:\nN = 6\nnums = {1,1,1,2,2,3}\nk = 2\nOutput: {1, 2}\n"
},
{
"code": null,
"e": 673,
"s": 662,
"text": "Example 2:"
},
{
"code": null,
"e": 862,
"s": 673,
"text": "Input:\nN = 8\nnums = {1,1,2,2,3,3,3,4}\nk = 2\nOutput: {3, 2}\nExplanation: Elements 1 and 2 have the\nsame frequency ie. 2. Therefore, in this\ncase, the answer includes the element 2\nas 2 > 1."
},
{
"code": null,
"e": 1008,
"s": 862,
"text": "User Task:\nThe task is to complete the function topK() that takes the array and integer k as input and returns a list of top k frequent elements."
},
{
"code": null,
"e": 1077,
"s": 1008,
"text": "Expected Time Complexity : O(NlogN)\nExpected Auxilliary Space : O(N)"
},
{
"code": null,
"e": 1118,
"s": 1077,
"text": "Constraints: \n1 <= N <= 105\n1<=A[i]<=105"
},
{
"code": null,
"e": 1120,
"s": 1118,
"text": "0"
},
{
"code": null,
"e": 1147,
"s": 1120,
"text": "hrithikraina20011 week ago"
},
{
"code": null,
"e": 1534,
"s": 1147,
"text": " priority_queue<pair<int,int> >pq;\n map<int,int>mp;\n \n vector<int>ans;\n \n \n for(int i=0;i<nums.size();i++)\n {\n mp[nums[i]]++;\n \n }\n for(auto it:mp)\n {\n pq.push({it.second,it.first});\n \n }\n \n for(int i=0;i<k;i++)\n {\n ans.push_back(pq.top().second);\n pq.pop();\n }\n return ans;"
},
{
"code": null,
"e": 1536,
"s": 1534,
"text": "0"
},
{
"code": null,
"e": 1562,
"s": 1536,
"text": "akhilyadav00882 weeks ago"
},
{
"code": null,
"e": 1601,
"s": 1562,
"text": "c++ solution with best time complexity"
},
{
"code": null,
"e": 2140,
"s": 1601,
"text": " priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> minh; unordered_map<int,int> mp; int n= nums.size(); for(int i=0;i<n;i++) mp[nums[i]]++; for(auto i=mp.begin();i!=mp.end();i++) { minh.push({i->second , i->first}); if(minh.size()>k) minh.pop(); } vector<int> res; while(minh.size()>0) { res.push_back((minh.top()).second); minh.pop(); } reverse(res.begin(), res.end()); return res;"
},
{
"code": null,
"e": 2143,
"s": 2140,
"text": "+1"
},
{
"code": null,
"e": 2164,
"s": 2143,
"text": "geeky20092 weeks ago"
},
{
"code": null,
"e": 2591,
"s": 2164,
"text": "vector<int> topK(vector<int>& nums, int k) { // Code here map<int,int>m; vector<int>v; for(int i=0;i<nums.size();i++){ m[nums[i]]++; } vector<pair<int,int>>v2; for(auto x:m){ v2.push_back({x.second,x.first}); } sort(v2.begin(),v2.end(),greater<pair<int,int>>()); for(int i=0;i<k;i++){ v.push_back(v2[i].second); } return v; }"
},
{
"code": null,
"e": 2593,
"s": 2591,
"text": "0"
},
{
"code": null,
"e": 2618,
"s": 2593,
"text": "mitradiptamoy2 weeks ago"
},
{
"code": null,
"e": 2644,
"s": 2618,
"text": "//C++ using unordered_map"
},
{
"code": null,
"e": 3134,
"s": 2644,
"text": "vector<int> topK(vector<int>& nums, int k) { // Code here unordered_map<int,int>mp; vector<int>ans; vector<pair<int,int>>vec; for(int i=0;i<nums.size();i++) { mp[nums[i]]=mp[nums[i]]+1; } for(auto it:mp) { vec.push_back({it.second,it.first}); } sort(vec.begin(),vec.end(),greater<pair<int,int>>()); for(int i=0;i<k;i++) { ans.push_back(vec[i].second); } return ans; }"
},
{
"code": null,
"e": 3137,
"s": 3134,
"text": "+1"
},
{
"code": null,
"e": 3160,
"s": 3137,
"text": "sagrikasoni2 weeks ago"
},
{
"code": null,
"e": 3837,
"s": 3160,
"text": "class Solution {\n public int[] topK(int[] nums, int k) {\n HashMap<Integer, Integer> map = new HashMap<>();\n for(int val: nums)\n map.put(val, map.getOrDefault(val, 0)+1);\n \n PriorityQueue<Integer> pQueue= new PriorityQueue<>((a,b)->{\n \n if(map.get(a)==map.get(b))\n return a-b;\n return map.get(a) - map.get(b);\n });\n for(int n: map.keySet())\n {\n pQueue.add(n);\n if(pQueue.size()>k)\n pQueue.poll();\n }\n int [] ans = new int[k];\n \n for(int i = k - 1; i >= 0;i--) {\n ans[i] = pQueue.poll();\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 3840,
"s": 3837,
"text": "+1"
},
{
"code": null,
"e": 3871,
"s": 3840,
"text": "siddharth1923co10682 weeks ago"
},
{
"code": null,
"e": 3901,
"s": 3871,
"text": "tym 0.42 Brute force approach"
},
{
"code": null,
"e": 3971,
"s": 3901,
"text": "/*firstly creating a hash map for storing freaquency of each element."
},
{
"code": null,
"e": 4033,
"s": 3971,
"text": "then placing this element along with frequecny in vector pair"
},
{
"code": null,
"e": 4148,
"s": 4033,
"text": "applying sorting to the given array then in final step returning the first k most frequent element in the array.*/"
},
{
"code": null,
"e": 4701,
"s": 4152,
"text": " vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int>map; vector<pair<int,int>>high; vector<int>ans; for(int i=0;i<nums.size();i++){ map[nums[i]]++; } for(auto it:map){ auto a=make_pair(it.second,it.first); high.push_back(a); } //for (auto it=map.begin(); it!=map.end(); ++it) sort(high.begin(),high.end(),greater<pair<int,int>>()); for(int i=0;i<k;i++){ ans.push_back(high[i].second); } return ans; }"
},
{
"code": null,
"e": 4704,
"s": 4701,
"text": "+2"
},
{
"code": null,
"e": 4725,
"s": 4704,
"text": "aryany8712 weeks ago"
},
{
"code": null,
"e": 4776,
"s": 4725,
"text": "//Time Complexity-O(nlogk) , Auxiliary Space-O(n) "
},
{
"code": null,
"e": 5457,
"s": 4778,
"text": "vector<int> topK(vector<int>& a, int k) { unordered_map<int,int> m; for(auto it : a){//-O(n) m[it]++; } //min heap priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq; for(auto it : m){//-O(nlogk) pq.push({it.second,it.first}); //inserting freq first as it's sorted using first element by default if(pq.size()>k){ pq.pop(); } } vector<int> v(k); for(int i=k-1;i>=0;i--){//O(klogk) auto it =pq.top(); v[i]=it.second; pq.pop(); } return v; }"
},
{
"code": null,
"e": 5459,
"s": 5457,
"text": "0"
},
{
"code": null,
"e": 5469,
"s": 5459,
"text": "aryany871"
},
{
"code": null,
"e": 5495,
"s": 5469,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5497,
"s": 5495,
"text": "0"
},
{
"code": null,
"e": 5527,
"s": 5497,
"text": "princechaudhary0073 weeks ago"
},
{
"code": null,
"e": 5550,
"s": 5527,
"text": "timeComplexity=(NlogN)"
},
{
"code": null,
"e": 5553,
"s": 5550,
"text": "//"
},
{
"code": null,
"e": 6117,
"s": 5553,
"text": "static bool comp(pair<int,int>a,pair<int,int>b){ if(a.second==b.second) return a.first>b.first; return a.second>b.second; } vector<int> topK(vector<int>& arr, int k) { // Code here unordered_map<int,int>mp; int n=arr.size(); for(int i=0;i<n;i++){ mp[arr[i]]++; } vector<pair<int,int>>v; for(auto x:mp){ v.push_back(x); } sort(v.begin(),v.end(),comp); vector<int>ans; for(int i=0;i<k;i++){ ans.push_back(v[i].first); } return ans; }};"
},
{
"code": null,
"e": 6119,
"s": 6117,
"text": "0"
},
{
"code": null,
"e": 6148,
"s": 6119,
"text": "itachinamikaze2211 month ago"
},
{
"code": null,
"e": 6153,
"s": 6148,
"text": "JAVA"
},
{
"code": null,
"e": 6891,
"s": 6153,
"text": "class Solution { public int[] topK(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for(int val: nums) map.put(val, map.getOrDefault(val, 0)+1); PriorityQueue<Integer> pQueue= new PriorityQueue<>((a,b)->{ int aValue=map.get(a); int bValue=map.get(b); if(aValue==bValue) return a-b; return aValue - bValue; }); for(int n: map.keySet()) { pQueue.add(n); if(pQueue.size()>k) pQueue.poll(); } int []a = new int[k]; int i=k-1; while(pQueue.isEmpty()==false) { int n=pQueue.poll(); a[i]=n; i--; } return a; }}"
},
{
"code": null,
"e": 7037,
"s": 6891,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7073,
"s": 7037,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7083,
"s": 7073,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7093,
"s": 7083,
"text": "\nContest\n"
},
{
"code": null,
"e": 7156,
"s": 7093,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7304,
"s": 7156,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7512,
"s": 7304,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7618,
"s": 7512,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to add a new column to a data frame using mutate in R? | The mutate function of dplyr package in R can help us to add a new column to a data frame and the benefit of using mutate is that we can decide the position of the new column during the addition. For example, if we have a data frame called df that contains three columns say x, y, a then we can add a new column say z after y using mutate function. To understand how it can be done, check out the below examples.
Consider the below data frame −
Live Demo
> x1<-rpois(20,2)
> x3<-rpois(20,5)
> df1<-data.frame(x1,x3)
> df1
x1 x3
1 2 3
2 1 7
3 1 6
4 5 6
5 2 7
6 5 2
7 1 7
8 2 5
9 1 4
10 2 7
11 2 3
12 1 6
13 3 5
14 3 4
15 2 7
16 3 7
17 6 7
18 2 9
19 1 5
20 1 5
Loading dplyr package and adding a new column x2 after x1 in df1 −
> library(dplyr)
> df1%>%mutate(x2=rpois(20,1),.after=x1)
x1 x2 x3
1 2 0 3
2 1 0 7
3 1 1 6
4 5 0 6
5 2 1 7
6 5 0 2
7 1 1 7
8 2 1 5
9 1 0 4
10 2 1 7
11 2 0 3
12 1 1 6
13 3 1 5
14 3 1 4
15 2 1 7
16 3 4 7
17 6 1 7
18 2 2 9
19 1 1 5
20 1 4 5
Live Demo
> y1<-rnorm(20)
> y2<-rnorm(20)
> y4<-rnorm(20)
> df2<-data.frame(y1,y2,y4)
> df2
y1 y2 y4
1 1.21750225 -1.33082010 0.7365231
2 0.24052365 -1.19657893 -0.7325931
3 0.82363925 -0.03890292 -0.3103461
4 -0.28315390 -0.20730053 -1.0066420
5 -0.56196875 -0.41592524 0.4996899
6 0.90983596 0.66105140 -0.9552844
7 1.14413650 1.20610045 0.9542341
8 0.03566065 1.31518070 0.2722798
9 1.72309925 0.55267260 0.3036829
10 1.27783338 -0.61818175 -0.2573076
11 0.22074289 1.23057901 0.5180043
12 1.60663571 -1.00737269 1.1614623
13 -0.75813279 -0.36594209 0.3923075
14 -0.31492265 1.30409915 -0.2759040
15 -1.03101619 0.15687986 0.8609099
16 -0.37968676 -0.04247421 -0.7490176
17 -1.90078740 -0.61468534 1.0015994
18 -0.76753148 0.21451207 -0.1875631
19 -0.36281597 -0.94474847 -1.1014309
20 -1.90049600 -0.20750306 2.1602226
adding a new column y3 after y2 in df2 −
> df2%>%mutate(y3=rnorm(20,10,0.5),.after=y2)
y1 y2 y3 y4
1 1.21750225 -1.33082010 8.801898 0.7365231
2 0.24052365 -1.19657893 9.592606 -0.7325931
3 0.82363925 -0.03890292 10.088155 -0.3103461
4 -0.28315390 -0.20730053 9.297835 -1.0066420
5 -0.56196875 -0.41592524 9.463427 0.4996899
6 0.90983596 0.66105140 9.494079 -0.9552844
7 1.14413650 1.20610045 9.689292 0.9542341
8 0.03566065 1.31518070 10.664904 0.2722798
9 1.72309925 0.55267260 10.778179 0.3036829
10 1.27783338 -0.61818175 9.872532 -0.2573076
11 0.22074289 1.23057901 9.301869 0.5180043
12 1.60663571 -1.00737269 10.176794 1.1614623
13 -0.75813279 -0.36594209 9.367227 0.3923075
14 -0.31492265 1.30409915 11.086966 -0.2759040
15 -1.03101619 0.15687986 9.082294 0.8609099
16 -0.37968676 -0.04247421 9.547622 -0.7490176
17 -1.90078740 -0.61468534 9.694575 1.0015994
18 -0.76753148 0.21451207 10.583576 -0.1875631
19 -0.36281597 -0.94474847 10.075352 -1.1014309
20 -1.90049600 -0.20750306 10.106721 2.1602226 | [
{
"code": null,
"e": 1475,
"s": 1062,
"text": "The mutate function of dplyr package in R can help us to add a new column to a data frame and the benefit of using mutate is that we can decide the position of the new column during the addition. For example, if we have a data frame called df that contains three columns say x, y, a then we can add a new column say z after y using mutate function. To understand how it can be done, check out the below examples."
},
{
"code": null,
"e": 1507,
"s": 1475,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1517,
"s": 1507,
"text": "Live Demo"
},
{
"code": null,
"e": 1584,
"s": 1517,
"text": "> x1<-rpois(20,2)\n> x3<-rpois(20,5)\n> df1<-data.frame(x1,x3)\n> df1"
},
{
"code": null,
"e": 1753,
"s": 1584,
"text": " x1 x3\n1 2 3\n2 1 7\n3 1 6\n4 5 6\n5 2 7\n6 5 2\n7 1 7\n8 2 5\n9 1 4\n10 2 7\n11 2 3\n12 1 6\n13 3 5\n14 3 4\n15 2 7\n16 3 7\n17 6 7\n18 2 9\n19 1 5\n20 1 5"
},
{
"code": null,
"e": 1820,
"s": 1753,
"text": "Loading dplyr package and adding a new column x2 after x1 in df1 −"
},
{
"code": null,
"e": 1878,
"s": 1820,
"text": "> library(dplyr)\n> df1%>%mutate(x2=rpois(20,1),.after=x1)"
},
{
"code": null,
"e": 2110,
"s": 1878,
"text": " x1 x2 x3\n1 2 0 3\n2 1 0 7\n3 1 1 6\n4 5 0 6\n5 2 1 7\n6 5 0 2\n7 1 1 7\n8 2 1 5\n9 1 0 4\n10 2 1 7\n11 2 0 3\n12 1 1 6\n13 3 1 5\n14 3 1 4\n15 2 1 7\n16 3 4 7\n17 6 1 7\n18 2 2 9\n19 1 1 5\n20 1 4 5"
},
{
"code": null,
"e": 2120,
"s": 2110,
"text": "Live Demo"
},
{
"code": null,
"e": 2202,
"s": 2120,
"text": "> y1<-rnorm(20)\n> y2<-rnorm(20)\n> y4<-rnorm(20)\n> df2<-data.frame(y1,y2,y4)\n> df2"
},
{
"code": null,
"e": 3016,
"s": 2202,
"text": " y1 y2 y4\n1 1.21750225 -1.33082010 0.7365231\n2 0.24052365 -1.19657893 -0.7325931\n3 0.82363925 -0.03890292 -0.3103461\n4 -0.28315390 -0.20730053 -1.0066420\n5 -0.56196875 -0.41592524 0.4996899\n6 0.90983596 0.66105140 -0.9552844\n7 1.14413650 1.20610045 0.9542341\n8 0.03566065 1.31518070 0.2722798\n9 1.72309925 0.55267260 0.3036829\n10 1.27783338 -0.61818175 -0.2573076\n11 0.22074289 1.23057901 0.5180043\n12 1.60663571 -1.00737269 1.1614623\n13 -0.75813279 -0.36594209 0.3923075\n14 -0.31492265 1.30409915 -0.2759040\n15 -1.03101619 0.15687986 0.8609099\n16 -0.37968676 -0.04247421 -0.7490176\n17 -1.90078740 -0.61468534 1.0015994\n18 -0.76753148 0.21451207 -0.1875631\n19 -0.36281597 -0.94474847 -1.1014309\n20 -1.90049600 -0.20750306 2.1602226"
},
{
"code": null,
"e": 3057,
"s": 3016,
"text": "adding a new column y3 after y2 in df2 −"
},
{
"code": null,
"e": 3103,
"s": 3057,
"text": "> df2%>%mutate(y3=rnorm(20,10,0.5),.after=y2)"
},
{
"code": null,
"e": 4147,
"s": 3103,
"text": " y1 y2 y3 y4\n1 1.21750225 -1.33082010 8.801898 0.7365231\n2 0.24052365 -1.19657893 9.592606 -0.7325931\n3 0.82363925 -0.03890292 10.088155 -0.3103461\n4 -0.28315390 -0.20730053 9.297835 -1.0066420\n5 -0.56196875 -0.41592524 9.463427 0.4996899\n6 0.90983596 0.66105140 9.494079 -0.9552844\n7 1.14413650 1.20610045 9.689292 0.9542341\n8 0.03566065 1.31518070 10.664904 0.2722798\n9 1.72309925 0.55267260 10.778179 0.3036829\n10 1.27783338 -0.61818175 9.872532 -0.2573076\n11 0.22074289 1.23057901 9.301869 0.5180043\n12 1.60663571 -1.00737269 10.176794 1.1614623\n13 -0.75813279 -0.36594209 9.367227 0.3923075\n14 -0.31492265 1.30409915 11.086966 -0.2759040\n15 -1.03101619 0.15687986 9.082294 0.8609099\n16 -0.37968676 -0.04247421 9.547622 -0.7490176\n17 -1.90078740 -0.61468534 9.694575 1.0015994\n18 -0.76753148 0.21451207 10.583576 -0.1875631\n19 -0.36281597 -0.94474847 10.075352 -1.1014309\n20 -1.90049600 -0.20750306 10.106721 2.1602226"
}
] |
Number of trailing zeroes in base B representation of N! - GeeksforGeeks | 13 Jul, 2021
Given two positive integers B and N. The task is to find the number of trailing zeroes in b-ary (base B) representation of N! (factorial of N)Examples:
Input: N = 5, B = 2
Output: 3
5! = 120 which is represented as 1111000 in base 2.
Input: N = 6, B = 9
Output: 1
A naive solution is to find the factorial of the given number and convert it into given base B. Then, count the number of trailing zeroes but that would be a costly operation. Also, it will not be easy to find the factorial of large numbers and store it in integer.Efficient Approach: Suppose, the base is 10 i.e., decimal then we’ll have to calculate the highest power of 10 that divides N! using Legendre’s formula. Thus, number B is represented as 10 when converted into base B. Let’s say base B = 13, then 13 in base 13 will be represented as 10, i.e., 1310 = 1013. Hence, problem reduces to finding the highest power of B in N!. (Largest power of k in n!)Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// CPP program to find the number of trailing// zeroes in base B representation of N!#include <bits/stdc++.h>using namespace std; // To find the power of a prime p in// factorial Nint findPowerOfP(int N, int p){ int count = 0; int r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kvector<pair<int, int> > primeFactorsofB(int B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B vector<pair<int, int> > ans; for (int i = 2; B != 1; i++) { if (B % i == 0) { int count = 0; while (B % i == 0) { B = B / i; count++; } ans.push_back(make_pair(i, count)); } } return ans;} // Returns largest power of B that// divides N!int largestPowerOfB(int N, int B){ vector<pair<int, int> > vec; vec = primeFactorsofB(B); int ans = INT_MAX; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of B ans = min(ans, findPowerOfP(N, vec[i].first) / vec[i].second); return ans;} // Driver codeint main(){ cout << largestPowerOfB(5, 2) << endl; cout << largestPowerOfB(6, 9) << endl; return 0;}
// Java program to find the number of trailing// zeroes in base B representation of N!import java.util.*;class GFG{static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nstatic int findPowerOfP(int N, int p){ int count = 0; int r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic Vector<pair> primeFactorsofB(int B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B Vector<pair> ans = new Vector<pair>(); for (int i = 2; B != 1; i++) { if (B % i == 0) { int count = 0; while (B % i == 0) { B = B / i; count++; } ans.add(new pair(i, count)); } } return ans;} // Returns largest power of B that// divides N!static int largestPowerOfB(int N, int B){ Vector<pair> vec = new Vector<pair>(); vec = primeFactorsofB(B); int ans = Integer.MAX_VALUE; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of B ans = Math.min(ans, findPowerOfP( N, vec.get(i).first) / vec.get(i).second); return ans;} // Driver codepublic static void main(String[] args){ System.out.println(largestPowerOfB(5, 2)); System.out.println(largestPowerOfB(6, 9));}} // This code is contributed by Princi Singh
# Python 3 program to find the number of# trailing zeroes in base B representation of N!import sys # To find the power of a prime# p in factorial Ndef findPowerOfP(N, p): count = 0 r = p while (r <= N): # calculating floor(n/r) # and adding to the count count += int(N / r) # increasing the power of p # from 1 to 2 to 3 and so on r = r * p return count # returns all the prime factors of kdef primeFactorsofB(B): # vector to store all the prime factors # along with their number of occurrence # in factorization of B' ans = [] i = 2 while(B!= 1): if (B % i == 0): count = 0 while (B % i == 0): B = int(B / i) count += 1 ans.append((i, count)) i += 1 return ans # Returns largest power of B that# divides N!def largestPowerOfB(N, B): vec = [] vec = primeFactorsofB(B) ans = sys.maxsize # calculating minimum power of all # the prime factors of B ans = min(ans, int(findPowerOfP(N, vec[0][0]) / vec[0][1])) return ans # Driver codeif __name__ == '__main__': print(largestPowerOfB(5, 2)) print(largestPowerOfB(6, 9)) # This code is contributed by# Surendra_Gangwar
// C# program to find the number of trailing// zeroes in base B representation of N!using System;using System.Collections.Generic; class GFG{public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nstatic int findPowerOfP(int N, int p){ int count = 0; int r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic List<pair> primeFactorsofB(int B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B List<pair> ans = new List<pair>(); for (int i = 2; B != 1; i++) { if (B % i == 0) { int count = 0; while (B % i == 0) { B = B / i; count++; } ans.Add(new pair(i, count)); } } return ans;} // Returns largest power of B that// divides N!static int largestPowerOfB(int N, int B){ List<pair> vec = new List<pair>(); vec = primeFactorsofB(B); int ans = int.MaxValue; for (int i = 0; i < vec.Count; i++) // calculating minimum power of all // the prime factors of B ans = Math.Min(ans, findPowerOfP( N, vec[i].first) / vec[i].second); return ans;} // Driver codepublic static void Main(String[] args){ Console.WriteLine(largestPowerOfB(5, 2)); Console.WriteLine(largestPowerOfB(6, 9));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the number of trailing// zeroes in base B representation of N! // To find the power of a prime p in// factorial Nfunction findPowerOfP(N, p){ var count = 0; var r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kfunction primeFactorsofB(B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B var ans = []; for (var i = 2; B != 1; i++) { if (B % i == 0) { var count = 0; while (B % i == 0) { B = B / i; count++; } ans.push([i, count]); } } return ans;} // Returns largest power of B that// divides N!function largestPowerOfB(N, B){ var vec =[]; vec = primeFactorsofB(B); var ans = Number.MAX_VALUE; for (var i = 0; i < vec.length; i++) // calculating minimum power of all // the prime factors of B ans = Math.min(ans, Math.floor(findPowerOfP(N, vec[i][0]) / vec[i][1])); return ans;} // Driver codedocument.write(largestPowerOfB(5, 2) + "<br>");document.write(largestPowerOfB(6, 9) + "<br>"); // This code is contributed by ShubhamSingh10 </script>
3
1
SURENDRA_GANGWAR
princi singh
29AjayKumar
SHUBHAMSINGH10
factorial
number-theory
Competitive Programming
Mathematical
number-theory
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Breadth First Traversal ( BFS ) on a 2D array
Runtime Errors
Most important type of Algorithms
Multistage Graph (Shortest Path)
Shortest path in a directed graph by Dijkstra’s algorithm
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24737,
"s": 24709,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 24891,
"s": 24737,
"text": "Given two positive integers B and N. The task is to find the number of trailing zeroes in b-ary (base B) representation of N! (factorial of N)Examples: "
},
{
"code": null,
"e": 25005,
"s": 24891,
"text": "Input: N = 5, B = 2\nOutput: 3\n5! = 120 which is represented as 1111000 in base 2. \n\nInput: N = 6, B = 9\nOutput: 1"
},
{
"code": null,
"e": 25720,
"s": 25007,
"text": "A naive solution is to find the factorial of the given number and convert it into given base B. Then, count the number of trailing zeroes but that would be a costly operation. Also, it will not be easy to find the factorial of large numbers and store it in integer.Efficient Approach: Suppose, the base is 10 i.e., decimal then we’ll have to calculate the highest power of 10 that divides N! using Legendre’s formula. Thus, number B is represented as 10 when converted into base B. Let’s say base B = 13, then 13 in base 13 will be represented as 10, i.e., 1310 = 1013. Hence, problem reduces to finding the highest power of B in N!. (Largest power of k in n!)Below is the implementation of the above approach. "
},
{
"code": null,
"e": 25724,
"s": 25720,
"text": "C++"
},
{
"code": null,
"e": 25729,
"s": 25724,
"text": "Java"
},
{
"code": null,
"e": 25737,
"s": 25729,
"text": "Python3"
},
{
"code": null,
"e": 25740,
"s": 25737,
"text": "C#"
},
{
"code": null,
"e": 25751,
"s": 25740,
"text": "Javascript"
},
{
"code": "// CPP program to find the number of trailing// zeroes in base B representation of N!#include <bits/stdc++.h>using namespace std; // To find the power of a prime p in// factorial Nint findPowerOfP(int N, int p){ int count = 0; int r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kvector<pair<int, int> > primeFactorsofB(int B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B vector<pair<int, int> > ans; for (int i = 2; B != 1; i++) { if (B % i == 0) { int count = 0; while (B % i == 0) { B = B / i; count++; } ans.push_back(make_pair(i, count)); } } return ans;} // Returns largest power of B that// divides N!int largestPowerOfB(int N, int B){ vector<pair<int, int> > vec; vec = primeFactorsofB(B); int ans = INT_MAX; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of B ans = min(ans, findPowerOfP(N, vec[i].first) / vec[i].second); return ans;} // Driver codeint main(){ cout << largestPowerOfB(5, 2) << endl; cout << largestPowerOfB(6, 9) << endl; return 0;}",
"e": 27269,
"s": 25751,
"text": null
},
{
"code": "// Java program to find the number of trailing// zeroes in base B representation of N!import java.util.*;class GFG{static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nstatic int findPowerOfP(int N, int p){ int count = 0; int r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic Vector<pair> primeFactorsofB(int B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B Vector<pair> ans = new Vector<pair>(); for (int i = 2; B != 1; i++) { if (B % i == 0) { int count = 0; while (B % i == 0) { B = B / i; count++; } ans.add(new pair(i, count)); } } return ans;} // Returns largest power of B that// divides N!static int largestPowerOfB(int N, int B){ Vector<pair> vec = new Vector<pair>(); vec = primeFactorsofB(B); int ans = Integer.MAX_VALUE; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of B ans = Math.min(ans, findPowerOfP( N, vec.get(i).first) / vec.get(i).second); return ans;} // Driver codepublic static void main(String[] args){ System.out.println(largestPowerOfB(5, 2)); System.out.println(largestPowerOfB(6, 9));}} // This code is contributed by Princi Singh",
"e": 29043,
"s": 27269,
"text": null
},
{
"code": "# Python 3 program to find the number of# trailing zeroes in base B representation of N!import sys # To find the power of a prime# p in factorial Ndef findPowerOfP(N, p): count = 0 r = p while (r <= N): # calculating floor(n/r) # and adding to the count count += int(N / r) # increasing the power of p # from 1 to 2 to 3 and so on r = r * p return count # returns all the prime factors of kdef primeFactorsofB(B): # vector to store all the prime factors # along with their number of occurrence # in factorization of B' ans = [] i = 2 while(B!= 1): if (B % i == 0): count = 0 while (B % i == 0): B = int(B / i) count += 1 ans.append((i, count)) i += 1 return ans # Returns largest power of B that# divides N!def largestPowerOfB(N, B): vec = [] vec = primeFactorsofB(B) ans = sys.maxsize # calculating minimum power of all # the prime factors of B ans = min(ans, int(findPowerOfP(N, vec[0][0]) / vec[0][1])) return ans # Driver codeif __name__ == '__main__': print(largestPowerOfB(5, 2)) print(largestPowerOfB(6, 9)) # This code is contributed by# Surendra_Gangwar",
"e": 30378,
"s": 29043,
"text": null
},
{
"code": "// C# program to find the number of trailing// zeroes in base B representation of N!using System;using System.Collections.Generic; class GFG{public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nstatic int findPowerOfP(int N, int p){ int count = 0; int r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic List<pair> primeFactorsofB(int B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B List<pair> ans = new List<pair>(); for (int i = 2; B != 1; i++) { if (B % i == 0) { int count = 0; while (B % i == 0) { B = B / i; count++; } ans.Add(new pair(i, count)); } } return ans;} // Returns largest power of B that// divides N!static int largestPowerOfB(int N, int B){ List<pair> vec = new List<pair>(); vec = primeFactorsofB(B); int ans = int.MaxValue; for (int i = 0; i < vec.Count; i++) // calculating minimum power of all // the prime factors of B ans = Math.Min(ans, findPowerOfP( N, vec[i].first) / vec[i].second); return ans;} // Driver codepublic static void Main(String[] args){ Console.WriteLine(largestPowerOfB(5, 2)); Console.WriteLine(largestPowerOfB(6, 9));}} // This code is contributed by 29AjayKumar",
"e": 32158,
"s": 30378,
"text": null
},
{
"code": "<script> // JavaScript program to find the number of trailing// zeroes in base B representation of N! // To find the power of a prime p in// factorial Nfunction findPowerOfP(N, p){ var count = 0; var r = p; while (r <= N) { // calculating floor(n/r) // and adding to the count count += (N / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kfunction primeFactorsofB(B){ // vector to store all the prime factors // along with their number of occurrence // in factorization of B var ans = []; for (var i = 2; B != 1; i++) { if (B % i == 0) { var count = 0; while (B % i == 0) { B = B / i; count++; } ans.push([i, count]); } } return ans;} // Returns largest power of B that// divides N!function largestPowerOfB(N, B){ var vec =[]; vec = primeFactorsofB(B); var ans = Number.MAX_VALUE; for (var i = 0; i < vec.length; i++) // calculating minimum power of all // the prime factors of B ans = Math.min(ans, Math.floor(findPowerOfP(N, vec[i][0]) / vec[i][1])); return ans;} // Driver codedocument.write(largestPowerOfB(5, 2) + \"<br>\");document.write(largestPowerOfB(6, 9) + \"<br>\"); // This code is contributed by ShubhamSingh10 </script>",
"e": 33584,
"s": 32158,
"text": null
},
{
"code": null,
"e": 33588,
"s": 33584,
"text": "3\n1"
},
{
"code": null,
"e": 33607,
"s": 33590,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33620,
"s": 33607,
"text": "princi singh"
},
{
"code": null,
"e": 33632,
"s": 33620,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33647,
"s": 33632,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33657,
"s": 33647,
"text": "factorial"
},
{
"code": null,
"e": 33671,
"s": 33657,
"text": "number-theory"
},
{
"code": null,
"e": 33695,
"s": 33671,
"text": "Competitive Programming"
},
{
"code": null,
"e": 33708,
"s": 33695,
"text": "Mathematical"
},
{
"code": null,
"e": 33722,
"s": 33708,
"text": "number-theory"
},
{
"code": null,
"e": 33735,
"s": 33722,
"text": "Mathematical"
},
{
"code": null,
"e": 33745,
"s": 33735,
"text": "factorial"
},
{
"code": null,
"e": 33843,
"s": 33745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33852,
"s": 33843,
"text": "Comments"
},
{
"code": null,
"e": 33865,
"s": 33852,
"text": "Old Comments"
},
{
"code": null,
"e": 33911,
"s": 33865,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 33926,
"s": 33911,
"text": "Runtime Errors"
},
{
"code": null,
"e": 33960,
"s": 33926,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 33993,
"s": 33960,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 34051,
"s": 33993,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 34081,
"s": 34051,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34141,
"s": 34081,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34156,
"s": 34141,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34199,
"s": 34156,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Professional 3-way Venn diagrams | Tailor labels and legend | Towards Data Science | As an avid python enthusiast, I recently came across the task of generating a 3-way Venn diagram. The quantity of time I spent on this seemingly simple task illuminated areas of sparsity in my working knowledge of matplotlib. May this tutorial aid others in efficiently customizing matplotlib embedded text to generate graphics ready for publication, dashboards, or reports. The full Jupyter Notebook is hosted on GitHub.
Let’s begin with data stored in pandas DataFrames. As a standard data structure, we wish to quickly visualize categorical data from three DataFrames or Series. For the purpose of this example, we will consider ten total people distributed across three groups: A, B, and C. The goal is to visualize these groupings using Venn diagrams.
import pandas as pdgroupA =['person1','person2','person3','person4','person5', 'person6','person7']groupB = ['person1','person2','person3', 'person8','person9']groupC = ['person1','person2', 'person4', 'person9','person10']dfA = pd.DataFrame(groupA,columns=[‘A’])dfB = pd.DataFrame(groupB,columns=[‘B’])dfC = pd.DataFrame(groupC,columns=[‘C’])
The ideal python data structure for analyzing groupings is the “set.” A set is an unordered grouping of unique items. In the first line, we call the column A of pandas DataFrame dfA as a series. Then, we convert the series to a set.
If your data column has duplicated items, you will need to drop them or transform their names prior to using this method. If you are unsure, call with sum(dfA.A.duplicated()). If this number is greater than zero, address duplicates prior to proceeding.
A = set(dfA.A)B = set(dfB.B)C = set(dfC.C)
Subsets of A, B, and C can be found using the set operators & and - to compute intersections (shared components) and differences. A_rest contains the individuals only found in A. AB_only contains the individuals in both A and B not found in C. ABC_overlap contains individuals who have membership in all three groups.
AB_overlap = A & B #compute intersection of set A & set BAC_overlap = A & CBC_overlap = B & CABC_overlap = A & B & CA_rest = A - AB_overlap - AC_overlap #see left graphicB_rest = B - AB_overlap - BC_overlapC_rest = C - AC_overlap - BC_overlapAB_only = AB_overlap - ABC_overlap #see right graphicAC_only = AC_overlap - ABC_overlapBC_only = BC_overlap - ABC_overlap
These variables can now be used to generate the Venn using the matplotlib_venn package. When customizing to your data, keep track of the group order!
from collections import Counterfrom matplotlib_venn import venn2, venn3import matplotlib.pyplot as pltsets = Counter() #set order A, B, C sets['100'] = len(A_rest) #100 denotes A on, B off, C off sets['010'] = len(B_rest) #010 denotes A off, B on, C offsets['001'] = len(C_rest) #001 denotes A off, B off, C on sets['110'] = len(AB_only) #110 denotes A on, B on, C offsets['101'] = len(AC_only) #101 denotes A on, B off, C on sets['011'] = len(BC_only) #011 denotes A off, B on, C on sets['111'] = len(ABC_overlap) #011 denotes A on, B on, C onlabels = ('Group A', 'Group B', 'Group C') plt.figure(figsize=(7,7)) ax = plt.gca() venn3(subsets=sets, set_labels=labels, ax=ax,set_colors= ('darkviolet','deepskyblue','blue'),alpha=0.7) plt.show()
This diagram is nice, but it looks more amateur than professional. To jazz it up, we can customize just a several aspects of the visual. First, we can modify the set label colors. See the bolded section of added code.
plt.figure(figsize=(7,7))ax = plt.gca()colors = ['darkviolet','deepskyblue','blue']v = venn3(subsets=sets, set_labels=labels, ax=ax,set_colors= colors,alpha=0.7) i = 0for text in v.set_labels: text.set_color(colors[i]) i+=1plt.show()
Now that the set label colors correspond with the circle sections, we can also modify the number font. For additional clarity, we can change the color, fontsize, and fontweight of the subset label on the Venn diagram.
plt.figure(figsize=(7,7))ax = plt.gca()colors = ['darkviolet','deepskyblue','blue']v = venn3(subsets=sets, set_labels=labels, ax=ax,set_colors= colors,alpha=0.7) i = 0for text in v.set_labels: text.set_color(colors[i]) i+=1for text in v.subset_labels: text.set_color('white') text.set_fontsize(16) text.set_fontweight('bold')plt.show()
Once satisfied with these fonts, we might wish to eliminate the colored labels altogether for a more formal effect. Create the legend by generating two lists, handles and labels.
Handles is generated by iterating through the patches of the Venn using the get_patch_id()method in the Venn3 class and adding the components to an empty list. In my experience, it is best to print the handles list on the graphic, and manually write the label list to match.
plt.figure(figsize=(7,7))ax = plt.gca()v = venn3(subsets=sets, set_labels=('','',''), ax=ax,set_colors= colors,alpha=0.7) for text in v.subset_labels: text.set_color('white') text.set_fontsize(16) text.set_fontweight('bold')h = [] for i in sets: h.append(v.get_patch_by_id(i)) l = ['A only','C only','B only','A & C shared','A & B shared', 'B & C shared','A & B & C shared']ax.legend(handles=h, labels=l, title="Legend",loc='lower left') plt.title('Membership across Three Groups')plt.show()
Remove elements of the legend that are self-explanatory, redundant, or unimportant. This will guide your audience to the remaining elements you wish to emphasize. To do this, we manually modify the handles and labels lists generated above.
Please note the handles list hhas a way of shifting around when counts change. Conveniently, I could call slices of hand l using h[0:3] and l[0:3] for this example. However, if you need to eliminate color patches from the centers of these two lists, you can apply the del h[2]operator to remove elements at specific indexes from handles and labels prior to calling them as arguments in ax.lengend(). For instance, that would remove the element at index 2 from list h. Just remember to keep the lengths of these lists equal.
plt.figure(figsize=(7,7)) ax = plt.gca() v = venn3(subsets=sets, set_labels=('','',''), ax=ax, set_colors=colors, alpha=0.7) for text in v.subset_labels: text.set_color('white') text.set_fontsize(16) text.set_fontweight('bold') ax.legend(handles=h[0:3], labels=l[0:3], title="Legend", loc='lower left') plt.title('Membership across Three Groups') plt.show()
These methods can also be applied to 2-way diagrams, which are substantially simpler. The notation of the venn2 class follows that of venn3. All of the above methods can be applied to this base class using the same format.
sets = Counter() #set order A, B sets['10'] = len(A-AB_overlap) #10 denotes A on, B off sets['01'] = len(B-AB_overlap) #01 denotes A off, B on sets['11'] = len(AB_overlap) #11 denotes A on, B on labels = ('Group A', 'Group B') plt.figure(figsize=(7,7)) ax = plt.gca() venn2(subsets=sets, set_labels=labels, ax=ax,set_colors= ('darkviolet','deepskyblue'),alpha=0.7) plt.title('Membership across Two Groups') plt.show()
That concludes this tutorial.
To some, customizing text content, placement, color, size, or weight in graphics may seem unnecessary. For practical use, it is. However, in formal presentation settings, a clean, clear graphic is crucial. If a picture speaks 1,000 words, use these techniques to make them count.
For more, check out the full notebook on GitHub. Interested in related articles? Read more from the author. | [
{
"code": null,
"e": 594,
"s": 172,
"text": "As an avid python enthusiast, I recently came across the task of generating a 3-way Venn diagram. The quantity of time I spent on this seemingly simple task illuminated areas of sparsity in my working knowledge of matplotlib. May this tutorial aid others in efficiently customizing matplotlib embedded text to generate graphics ready for publication, dashboards, or reports. The full Jupyter Notebook is hosted on GitHub."
},
{
"code": null,
"e": 929,
"s": 594,
"text": "Let’s begin with data stored in pandas DataFrames. As a standard data structure, we wish to quickly visualize categorical data from three DataFrames or Series. For the purpose of this example, we will consider ten total people distributed across three groups: A, B, and C. The goal is to visualize these groupings using Venn diagrams."
},
{
"code": null,
"e": 1281,
"s": 929,
"text": "import pandas as pdgroupA =['person1','person2','person3','person4','person5', 'person6','person7']groupB = ['person1','person2','person3', 'person8','person9']groupC = ['person1','person2', 'person4', 'person9','person10']dfA = pd.DataFrame(groupA,columns=[‘A’])dfB = pd.DataFrame(groupB,columns=[‘B’])dfC = pd.DataFrame(groupC,columns=[‘C’])"
},
{
"code": null,
"e": 1514,
"s": 1281,
"text": "The ideal python data structure for analyzing groupings is the “set.” A set is an unordered grouping of unique items. In the first line, we call the column A of pandas DataFrame dfA as a series. Then, we convert the series to a set."
},
{
"code": null,
"e": 1767,
"s": 1514,
"text": "If your data column has duplicated items, you will need to drop them or transform their names prior to using this method. If you are unsure, call with sum(dfA.A.duplicated()). If this number is greater than zero, address duplicates prior to proceeding."
},
{
"code": null,
"e": 1810,
"s": 1767,
"text": "A = set(dfA.A)B = set(dfB.B)C = set(dfC.C)"
},
{
"code": null,
"e": 2128,
"s": 1810,
"text": "Subsets of A, B, and C can be found using the set operators & and - to compute intersections (shared components) and differences. A_rest contains the individuals only found in A. AB_only contains the individuals in both A and B not found in C. ABC_overlap contains individuals who have membership in all three groups."
},
{
"code": null,
"e": 2495,
"s": 2128,
"text": "AB_overlap = A & B #compute intersection of set A & set BAC_overlap = A & CBC_overlap = B & CABC_overlap = A & B & CA_rest = A - AB_overlap - AC_overlap #see left graphicB_rest = B - AB_overlap - BC_overlapC_rest = C - AC_overlap - BC_overlapAB_only = AB_overlap - ABC_overlap #see right graphicAC_only = AC_overlap - ABC_overlapBC_only = BC_overlap - ABC_overlap"
},
{
"code": null,
"e": 2645,
"s": 2495,
"text": "These variables can now be used to generate the Venn using the matplotlib_venn package. When customizing to your data, keep track of the group order!"
},
{
"code": null,
"e": 3444,
"s": 2645,
"text": "from collections import Counterfrom matplotlib_venn import venn2, venn3import matplotlib.pyplot as pltsets = Counter() #set order A, B, C sets['100'] = len(A_rest) #100 denotes A on, B off, C off sets['010'] = len(B_rest) #010 denotes A off, B on, C offsets['001'] = len(C_rest) #001 denotes A off, B off, C on sets['110'] = len(AB_only) #110 denotes A on, B on, C offsets['101'] = len(AC_only) #101 denotes A on, B off, C on sets['011'] = len(BC_only) #011 denotes A off, B on, C on sets['111'] = len(ABC_overlap) #011 denotes A on, B on, C onlabels = ('Group A', 'Group B', 'Group C') plt.figure(figsize=(7,7)) ax = plt.gca() venn3(subsets=sets, set_labels=labels, ax=ax,set_colors= ('darkviolet','deepskyblue','blue'),alpha=0.7) plt.show()"
},
{
"code": null,
"e": 3662,
"s": 3444,
"text": "This diagram is nice, but it looks more amateur than professional. To jazz it up, we can customize just a several aspects of the visual. First, we can modify the set label colors. See the bolded section of added code."
},
{
"code": null,
"e": 3909,
"s": 3662,
"text": "plt.figure(figsize=(7,7))ax = plt.gca()colors = ['darkviolet','deepskyblue','blue']v = venn3(subsets=sets, set_labels=labels, ax=ax,set_colors= colors,alpha=0.7) i = 0for text in v.set_labels: text.set_color(colors[i]) i+=1plt.show()"
},
{
"code": null,
"e": 4127,
"s": 3909,
"text": "Now that the set label colors correspond with the circle sections, we can also modify the number font. For additional clarity, we can change the color, fontsize, and fontweight of the subset label on the Venn diagram."
},
{
"code": null,
"e": 4479,
"s": 4127,
"text": "plt.figure(figsize=(7,7))ax = plt.gca()colors = ['darkviolet','deepskyblue','blue']v = venn3(subsets=sets, set_labels=labels, ax=ax,set_colors= colors,alpha=0.7) i = 0for text in v.set_labels: text.set_color(colors[i]) i+=1for text in v.subset_labels: text.set_color('white') text.set_fontsize(16) text.set_fontweight('bold')plt.show()"
},
{
"code": null,
"e": 4658,
"s": 4479,
"text": "Once satisfied with these fonts, we might wish to eliminate the colored labels altogether for a more formal effect. Create the legend by generating two lists, handles and labels."
},
{
"code": null,
"e": 4933,
"s": 4658,
"text": "Handles is generated by iterating through the patches of the Venn using the get_patch_id()method in the Venn3 class and adding the components to an empty list. In my experience, it is best to print the handles list on the graphic, and manually write the label list to match."
},
{
"code": null,
"e": 5446,
"s": 4933,
"text": "plt.figure(figsize=(7,7))ax = plt.gca()v = venn3(subsets=sets, set_labels=('','',''), ax=ax,set_colors= colors,alpha=0.7) for text in v.subset_labels: text.set_color('white') text.set_fontsize(16) text.set_fontweight('bold')h = [] for i in sets: h.append(v.get_patch_by_id(i)) l = ['A only','C only','B only','A & C shared','A & B shared', 'B & C shared','A & B & C shared']ax.legend(handles=h, labels=l, title=\"Legend\",loc='lower left') plt.title('Membership across Three Groups')plt.show()"
},
{
"code": null,
"e": 5686,
"s": 5446,
"text": "Remove elements of the legend that are self-explanatory, redundant, or unimportant. This will guide your audience to the remaining elements you wish to emphasize. To do this, we manually modify the handles and labels lists generated above."
},
{
"code": null,
"e": 6210,
"s": 5686,
"text": "Please note the handles list hhas a way of shifting around when counts change. Conveniently, I could call slices of hand l using h[0:3] and l[0:3] for this example. However, if you need to eliminate color patches from the centers of these two lists, you can apply the del h[2]operator to remove elements at specific indexes from handles and labels prior to calling them as arguments in ax.lengend(). For instance, that would remove the element at index 2 from list h. Just remember to keep the lengths of these lists equal."
},
{
"code": null,
"e": 6609,
"s": 6210,
"text": "plt.figure(figsize=(7,7)) ax = plt.gca() v = venn3(subsets=sets, set_labels=('','',''), ax=ax, set_colors=colors, alpha=0.7) for text in v.subset_labels: text.set_color('white') text.set_fontsize(16) text.set_fontweight('bold') ax.legend(handles=h[0:3], labels=l[0:3], title=\"Legend\", loc='lower left') plt.title('Membership across Three Groups') plt.show()"
},
{
"code": null,
"e": 6832,
"s": 6609,
"text": "These methods can also be applied to 2-way diagrams, which are substantially simpler. The notation of the venn2 class follows that of venn3. All of the above methods can be applied to this base class using the same format."
},
{
"code": null,
"e": 7278,
"s": 6832,
"text": "sets = Counter() #set order A, B sets['10'] = len(A-AB_overlap) #10 denotes A on, B off sets['01'] = len(B-AB_overlap) #01 denotes A off, B on sets['11'] = len(AB_overlap) #11 denotes A on, B on labels = ('Group A', 'Group B') plt.figure(figsize=(7,7)) ax = plt.gca() venn2(subsets=sets, set_labels=labels, ax=ax,set_colors= ('darkviolet','deepskyblue'),alpha=0.7) plt.title('Membership across Two Groups') plt.show()"
},
{
"code": null,
"e": 7308,
"s": 7278,
"text": "That concludes this tutorial."
},
{
"code": null,
"e": 7588,
"s": 7308,
"text": "To some, customizing text content, placement, color, size, or weight in graphics may seem unnecessary. For practical use, it is. However, in formal presentation settings, a clean, clear graphic is crucial. If a picture speaks 1,000 words, use these techniques to make them count."
}
] |
How to echo XML file in PHP | HTTP URLs can be used to behave like local files, with the help of PHP wrappers. The contents from a URL can be fetched through the file_get_contents() and it can be echoed. or read using the readfile function.
Below is a sample code to do the same −
$file = file_get_contents('http://example.com/');
echo $file;
An alternative is demonstrated below −
readfile('http://example.com/');
header('Content-type: text/xml'); //The correct MIME type has to be set before displaying the output.
The asXML method also can be used. Below is a sample code −
echo $xml->asXML();
or
$xml->asXML('filename.xml'); //providing a name for the xml file. | [
{
"code": null,
"e": 1273,
"s": 1062,
"text": "HTTP URLs can be used to behave like local files, with the help of PHP wrappers. The contents from a URL can be fetched through the file_get_contents() and it can be echoed. or read using the readfile function."
},
{
"code": null,
"e": 1313,
"s": 1273,
"text": "Below is a sample code to do the same −"
},
{
"code": null,
"e": 1375,
"s": 1313,
"text": "$file = file_get_contents('http://example.com/');\necho $file;"
},
{
"code": null,
"e": 1414,
"s": 1375,
"text": "An alternative is demonstrated below −"
},
{
"code": null,
"e": 1549,
"s": 1414,
"text": "readfile('http://example.com/');\nheader('Content-type: text/xml'); //The correct MIME type has to be set before displaying the output."
},
{
"code": null,
"e": 1609,
"s": 1549,
"text": "The asXML method also can be used. Below is a sample code −"
},
{
"code": null,
"e": 1698,
"s": 1609,
"text": "echo $xml->asXML();\nor\n$xml->asXML('filename.xml'); //providing a name for the xml file."
}
] |
Where are static variables stored in C/C++? | Static variables are variables that remain in memory while the program is running i.e. their lifetime is the entire program run. This is different than automatic variables as they remain in memory only when their function is running and are destroyed when the function is over.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program.
All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment). Compared to this, the static variables that are initialized are stored in the initialized data segment.
An example of this is given as follows −
static int x = 5;
static int y;
The static variable x is stored in the initialized data segment and the static variable y is stored in the BSS segment.
A program that demonstrates static variables in C is given as follows −
Live Demo
#include<stdio.h>
int func(){
static int i = 4 ;
i++;
return i;
}
int main(){
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
return 0;
}
The output of the above program is as follows −
5
6
7
8
9
10
Now let us understand the above program.
In the function func(), i is a static variable that is initialized to 4. So it is stored in the initialized data segment. Then i is incremented and its value is returned. The code snippet that shows this is as follows −
int func(){
static int i = 4 ;
i++;
return i;
}
In the function main(), the function func() is called 6 times and it returns the value of i which is printed. Since i is a static variable, it remains in the memory while the program is running and it provides consistent values. The code snippet that shows this is as follows −
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func()); | [
{
"code": null,
"e": 1340,
"s": 1062,
"text": "Static variables are variables that remain in memory while the program is running i.e. their lifetime is the entire program run. This is different than automatic variables as they remain in memory only when their function is running and are destroyed when the function is over."
},
{
"code": null,
"e": 1477,
"s": 1340,
"text": "The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program."
},
{
"code": null,
"e": 1755,
"s": 1477,
"text": "All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment). Compared to this, the static variables that are initialized are stored in the initialized data segment."
},
{
"code": null,
"e": 1796,
"s": 1755,
"text": "An example of this is given as follows −"
},
{
"code": null,
"e": 1949,
"s": 1796,
"text": "static int x = 5;\nstatic int y;\n\nThe static variable x is stored in the initialized data segment and the static variable y is stored in the BSS segment."
},
{
"code": null,
"e": 2021,
"s": 1949,
"text": "A program that demonstrates static variables in C is given as follows −"
},
{
"code": null,
"e": 2032,
"s": 2021,
"text": " Live Demo"
},
{
"code": null,
"e": 2298,
"s": 2032,
"text": "#include<stdio.h>\nint func(){\n static int i = 4 ;\n i++;\n return i;\n}\n\nint main(){\n printf(\"%d\\n\", func());\n printf(\"%d\\n\", func());\n printf(\"%d\\n\", func());\n printf(\"%d\\n\", func());\n printf(\"%d\\n\", func());\n printf(\"%d\\n\", func());\n\n return 0;\n}"
},
{
"code": null,
"e": 2346,
"s": 2298,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 2359,
"s": 2346,
"text": "5\n6\n7\n8\n9\n10"
},
{
"code": null,
"e": 2400,
"s": 2359,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2620,
"s": 2400,
"text": "In the function func(), i is a static variable that is initialized to 4. So it is stored in the initialized data segment. Then i is incremented and its value is returned. The code snippet that shows this is as follows −"
},
{
"code": null,
"e": 2677,
"s": 2620,
"text": "int func(){\n static int i = 4 ;\n i++;\n return i;\n}"
},
{
"code": null,
"e": 2955,
"s": 2677,
"text": "In the function main(), the function func() is called 6 times and it returns the value of i which is printed. Since i is a static variable, it remains in the memory while the program is running and it provides consistent values. The code snippet that shows this is as follows −"
},
{
"code": null,
"e": 3099,
"s": 2955,
"text": "printf(\"%d\\n\", func());\nprintf(\"%d\\n\", func());\nprintf(\"%d\\n\", func());\nprintf(\"%d\\n\", func());\nprintf(\"%d\\n\", func());\nprintf(\"%d\\n\", func());"
}
] |
MySQL | CONNECTION_ID( ) Function - GeeksforGeeks | 25 Nov, 2019
The MySQL CONNECTION_ID() function is used for return the connection ID for a current connection in MySQL. The connection ID used to establish a connection to a database is unique for every connection among the connected clients. The CONNECTION_ID() function does not require any parameters or arguments.
The value returned by the CONNECTION_ID() function is the same type of value as displayed in the ID column of the INFORMATION_SCHEMA.PROCESSLIST table.
Syntax:
CONNECTION_ID()
Parameters Used:The CONNECTION_ID() function does not require any parameters or arguments.
Return Value:The MySQL CONNECTION_ID() function returns an integer value which represents the unique current connection ID.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example: Implementing CONNECTION_ID() function.
SELECT CONNECTION_ID();
Output:
1196078
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 24573,
"s": 24268,
"text": "The MySQL CONNECTION_ID() function is used for return the connection ID for a current connection in MySQL. The connection ID used to establish a connection to a database is unique for every connection among the connected clients. The CONNECTION_ID() function does not require any parameters or arguments."
},
{
"code": null,
"e": 24725,
"s": 24573,
"text": "The value returned by the CONNECTION_ID() function is the same type of value as displayed in the ID column of the INFORMATION_SCHEMA.PROCESSLIST table."
},
{
"code": null,
"e": 24733,
"s": 24725,
"text": "Syntax:"
},
{
"code": null,
"e": 24749,
"s": 24733,
"text": "CONNECTION_ID()"
},
{
"code": null,
"e": 24840,
"s": 24749,
"text": "Parameters Used:The CONNECTION_ID() function does not require any parameters or arguments."
},
{
"code": null,
"e": 24964,
"s": 24840,
"text": "Return Value:The MySQL CONNECTION_ID() function returns an integer value which represents the unique current connection ID."
},
{
"code": null,
"e": 24993,
"s": 24964,
"text": "Supported Versions of MySQL:"
},
{
"code": null,
"e": 25003,
"s": 24993,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 25013,
"s": 25003,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 25023,
"s": 25013,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 25033,
"s": 25023,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 25043,
"s": 25033,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 25053,
"s": 25043,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 25063,
"s": 25053,
"text": "MySQL 4.0"
},
{
"code": null,
"e": 25074,
"s": 25063,
"text": "MySQL 3.23"
},
{
"code": null,
"e": 25122,
"s": 25074,
"text": "Example: Implementing CONNECTION_ID() function."
},
{
"code": null,
"e": 25147,
"s": 25122,
"text": "SELECT CONNECTION_ID(); "
},
{
"code": null,
"e": 25155,
"s": 25147,
"text": "Output:"
},
{
"code": null,
"e": 25164,
"s": 25155,
"text": "1196078 "
},
{
"code": null,
"e": 25170,
"s": 25164,
"text": "mysql"
},
{
"code": null,
"e": 25179,
"s": 25170,
"text": "SQLmysql"
},
{
"code": null,
"e": 25183,
"s": 25179,
"text": "SQL"
},
{
"code": null,
"e": 25187,
"s": 25183,
"text": "SQL"
},
{
"code": null,
"e": 25285,
"s": 25187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25294,
"s": 25285,
"text": "Comments"
},
{
"code": null,
"e": 25307,
"s": 25294,
"text": "Old Comments"
},
{
"code": null,
"e": 25373,
"s": 25307,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25426,
"s": 25373,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 25458,
"s": 25426,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25536,
"s": 25458,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25553,
"s": 25536,
"text": "SQL using Python"
},
{
"code": null,
"e": 25568,
"s": 25553,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 25604,
"s": 25568,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 25625,
"s": 25604,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 25678,
"s": 25625,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
What is the difference between Math.ceil() and Math.round() methods in JavaScript? | Math.ceil() and Math.round() methods differ in a way that the former round off a number to its nearest integer in upward direction of rounding(towards the greater value) whereas the latter round off a number to its nearest integer in downward direction of rounding(towards lower value). Let's examine the two methods individually.
Math.ceil() method round off number passed as parameter to its nearest integer so as to get greater value.
In the below example when a number 5.34 passed as a parameter, Math.ceil() round off it in to 6, which is a greater value than actual number.
Live Demo
<html>
<body>
<script>
document.write(Math.ceil(5.34));
</script>
</body>
</html>
6
Math.round() method round off number passed as parameter to its nearest integer so as to get lower value.
In the below example when a number 5.34 passed as a parameter, Math.round() round off it in to 5, which is a lower value than actual number.
Live Demo
<html>
<body>
<script>
document.write(Math.round(5.34));
</script>
</body>
</html>
5 | [
{
"code": null,
"e": 1393,
"s": 1062,
"text": "Math.ceil() and Math.round() methods differ in a way that the former round off a number to its nearest integer in upward direction of rounding(towards the greater value) whereas the latter round off a number to its nearest integer in downward direction of rounding(towards lower value). Let's examine the two methods individually."
},
{
"code": null,
"e": 1500,
"s": 1393,
"text": "Math.ceil() method round off number passed as parameter to its nearest integer so as to get greater value."
},
{
"code": null,
"e": 1642,
"s": 1500,
"text": "In the below example when a number 5.34 passed as a parameter, Math.ceil() round off it in to 6, which is a greater value than actual number."
},
{
"code": null,
"e": 1652,
"s": 1642,
"text": "Live Demo"
},
{
"code": null,
"e": 1737,
"s": 1652,
"text": "<html>\n<body>\n<script>\n document.write(Math.ceil(5.34));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1739,
"s": 1737,
"text": "6"
},
{
"code": null,
"e": 1845,
"s": 1739,
"text": "Math.round() method round off number passed as parameter to its nearest integer so as to get lower value."
},
{
"code": null,
"e": 1986,
"s": 1845,
"text": "In the below example when a number 5.34 passed as a parameter, Math.round() round off it in to 5, which is a lower value than actual number."
},
{
"code": null,
"e": 1996,
"s": 1986,
"text": "Live Demo"
},
{
"code": null,
"e": 2082,
"s": 1996,
"text": "<html>\n<body>\n<script>\n document.write(Math.round(5.34));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2084,
"s": 2082,
"text": "5"
}
] |
How to turn an Image into a Link in HTML ? - GeeksforGeeks | 16 Dec, 2021
In this article, we will see how to turn an HTML image into a webpage link in HTML. The HTML <a> type attribute is used to create a hyperlink to web pages, files, locations on the same page. We can make elements like images into links by nesting them within an <a> element. It defines a hyperlink that is used to link from one page to another. If the <a> tag has no href attribute, then it will be only a placeholder for a hyperlink.
Syntax:
<a href=""></a>
Note: The href attribute is used to specify the destination address of the link.
Example: This example describes adding the link to the image to redirect to a specific page.
HTML
<!DOCTYPE html><html> <body style="text-align: center;"> <h3> Click on GeeksforGeeks logo to Redirect into geeksforgeeks.org </h3> <a href="https://geeksforgeeks.org"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png" alt="Click to visit geeksforgeeks.org"> </a></body> </html>
Output:
Making the image as a link in HTML
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubhamyadav4
bhaskargeeksforgeeks
CSS-Misc
HTML-Misc
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25400,
"s": 25372,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 25834,
"s": 25400,
"text": "In this article, we will see how to turn an HTML image into a webpage link in HTML. The HTML <a> type attribute is used to create a hyperlink to web pages, files, locations on the same page. We can make elements like images into links by nesting them within an <a> element. It defines a hyperlink that is used to link from one page to another. If the <a> tag has no href attribute, then it will be only a placeholder for a hyperlink."
},
{
"code": null,
"e": 25842,
"s": 25834,
"text": "Syntax:"
},
{
"code": null,
"e": 25858,
"s": 25842,
"text": "<a href=\"\"></a>"
},
{
"code": null,
"e": 25939,
"s": 25858,
"text": "Note: The href attribute is used to specify the destination address of the link."
},
{
"code": null,
"e": 26032,
"s": 25939,
"text": "Example: This example describes adding the link to the image to redirect to a specific page."
},
{
"code": null,
"e": 26037,
"s": 26032,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h3> Click on GeeksforGeeks logo to Redirect into geeksforgeeks.org </h3> <a href=\"https://geeksforgeeks.org\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png\" alt=\"Click to visit geeksforgeeks.org\"> </a></body> </html>",
"e": 26393,
"s": 26037,
"text": null
},
{
"code": null,
"e": 26401,
"s": 26393,
"text": "Output:"
},
{
"code": null,
"e": 26436,
"s": 26401,
"text": "Making the image as a link in HTML"
},
{
"code": null,
"e": 26573,
"s": 26436,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26587,
"s": 26573,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 26608,
"s": 26587,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 26617,
"s": 26608,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26627,
"s": 26617,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26631,
"s": 26627,
"text": "CSS"
},
{
"code": null,
"e": 26636,
"s": 26631,
"text": "HTML"
},
{
"code": null,
"e": 26655,
"s": 26636,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26672,
"s": 26655,
"text": "Web Technologies"
},
{
"code": null,
"e": 26677,
"s": 26672,
"text": "HTML"
},
{
"code": null,
"e": 26775,
"s": 26677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26812,
"s": 26775,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26841,
"s": 26812,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26880,
"s": 26841,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 26922,
"s": 26880,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 26969,
"s": 26922,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 27029,
"s": 26969,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27090,
"s": 27029,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27143,
"s": 27090,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 27193,
"s": 27143,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Check if it is possible to create a polygon with a given angle - GeeksforGeeks | 03 May, 2021
Given an angle where, . The task is to check whether it is possible to make a regular polygon with all of its interior angle equal to . If possible then print “YES”, otherwise print “NO” (without quotes). Examples:
Input: angle = 90
Output: YES
Polygons with sides 4 is
possible with angle 90 degrees.
Input: angle = 30
Output: NO
Approach: The Interior angle is defined as the angle between any two adjacent sides of a regular polygon.It is given by where, n is the number of sides in the polygon.This can be written as .On rearranging terms we get, .Thus, if n is an Integer the answer is “YES” otherwise, answer is “NO”.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check whether it is possible// to make a regular polygon with a given angle.void makePolygon(float a){ // N denotes the number of sides // of polygons possible float n = 360 / (180 - a); if (n == (int)n) cout << "YES"; else cout << "NO";} // Driver codeint main(){ float a = 90; // function to print the required answer makePolygon(a); return 0;}
class GFG{// Function to check whether// it is possible to make a// regular polygon with a given angle.static void makePolygon(double a){ // N denotes the number of // sides of polygons possible double n = 360 / (180 - a); if (n == (int)n) System.out.println("YES"); else System.out.println("NO");} // Driver codepublic static void main (String[] args){ double a = 90; // function to print // the required answer makePolygon(a);}} // This code is contributed by Bilal
# Python 3 implementation# of above approach # Function to check whether# it is possible to make a# regular polygon with a# given angle.def makePolygon(a) : # N denotes the number of sides # of polygons possible n = 360 / (180 - a) if n == int(n) : print("YES") else : print("NO") # Driver Codeif __name__ == "__main__" : a = 90 # function calling makePolygon(a) # This code is contributed# by ANKITRAI1
// C# implementation of// above approachusing System; class GFG{// Function to check whether// it is possible to make a// regular polygon with a// given angle.static void makePolygon(double a){ // N denotes the number of // sides of polygons possible double n = 360 / (180 - a); if (n == (int)n) Console.WriteLine("YES"); else Console.WriteLine("NO");} // Driver codestatic void Main(){ double a = 90; // function to print // the required answer makePolygon(a);}} // This code is contributed by mits
<?php// PHP implementation of above approach // Function to check whether it// is possible to make a regular// polygon with a given angle.function makePolygon($a){ // N denotes the number of // sides of polygons possible $n = 360 / (180 - $a); if ($n == (int)$n) echo "YES"; else echo "NO";} // Driver code$a = 90; // function to print the// required answermakePolygon($a); // This code is contributed// by ChitraNayal?>
<script> // JavaScript implementation of above approach // Function to check whether it is possible // to make a regular polygon with a given angle. function makePolygon(a) { // N denotes the number of sides // of polygons possible var n = parseFloat(360 / (180 - a)); if (n === parseInt(n)) document.write("YES"); else document.write("NO"); } // Driver code var a = 90; // function to print the required answer makePolygon(a); </script>
YES
bilal-hungund
Mithun Kumar
ankthon
ukasp
rdtank
math
Geometric
Mathematical
School Programming
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Closest Pair of Points | O(nlogn) Implementation
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25498,
"s": 25470,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 25715,
"s": 25498,
"text": "Given an angle where, . The task is to check whether it is possible to make a regular polygon with all of its interior angle equal to . If possible then print “YES”, otherwise print “NO” (without quotes). Examples: "
},
{
"code": null,
"e": 25832,
"s": 25715,
"text": "Input: angle = 90\nOutput: YES\nPolygons with sides 4 is\npossible with angle 90 degrees.\n\nInput: angle = 30\nOutput: NO"
},
{
"code": null,
"e": 26187,
"s": 25834,
"text": "Approach: The Interior angle is defined as the angle between any two adjacent sides of a regular polygon.It is given by where, n is the number of sides in the polygon.This can be written as .On rearranging terms we get, .Thus, if n is an Integer the answer is “YES” otherwise, answer is “NO”.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26191,
"s": 26187,
"text": "C++"
},
{
"code": null,
"e": 26196,
"s": 26191,
"text": "Java"
},
{
"code": null,
"e": 26204,
"s": 26196,
"text": "Python3"
},
{
"code": null,
"e": 26207,
"s": 26204,
"text": "C#"
},
{
"code": null,
"e": 26211,
"s": 26207,
"text": "PHP"
},
{
"code": null,
"e": 26222,
"s": 26211,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check whether it is possible// to make a regular polygon with a given angle.void makePolygon(float a){ // N denotes the number of sides // of polygons possible float n = 360 / (180 - a); if (n == (int)n) cout << \"YES\"; else cout << \"NO\";} // Driver codeint main(){ float a = 90; // function to print the required answer makePolygon(a); return 0;}",
"e": 26711,
"s": 26222,
"text": null
},
{
"code": "class GFG{// Function to check whether// it is possible to make a// regular polygon with a given angle.static void makePolygon(double a){ // N denotes the number of // sides of polygons possible double n = 360 / (180 - a); if (n == (int)n) System.out.println(\"YES\"); else System.out.println(\"NO\");} // Driver codepublic static void main (String[] args){ double a = 90; // function to print // the required answer makePolygon(a);}} // This code is contributed by Bilal",
"e": 27221,
"s": 26711,
"text": null
},
{
"code": "# Python 3 implementation# of above approach # Function to check whether# it is possible to make a# regular polygon with a# given angle.def makePolygon(a) : # N denotes the number of sides # of polygons possible n = 360 / (180 - a) if n == int(n) : print(\"YES\") else : print(\"NO\") # Driver Codeif __name__ == \"__main__\" : a = 90 # function calling makePolygon(a) # This code is contributed# by ANKITRAI1",
"e": 27671,
"s": 27221,
"text": null
},
{
"code": "// C# implementation of// above approachusing System; class GFG{// Function to check whether// it is possible to make a// regular polygon with a// given angle.static void makePolygon(double a){ // N denotes the number of // sides of polygons possible double n = 360 / (180 - a); if (n == (int)n) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");} // Driver codestatic void Main(){ double a = 90; // function to print // the required answer makePolygon(a);}} // This code is contributed by mits",
"e": 28213,
"s": 27671,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // Function to check whether it// is possible to make a regular// polygon with a given angle.function makePolygon($a){ // N denotes the number of // sides of polygons possible $n = 360 / (180 - $a); if ($n == (int)$n) echo \"YES\"; else echo \"NO\";} // Driver code$a = 90; // function to print the// required answermakePolygon($a); // This code is contributed// by ChitraNayal?>",
"e": 28663,
"s": 28213,
"text": null
},
{
"code": "<script> // JavaScript implementation of above approach // Function to check whether it is possible // to make a regular polygon with a given angle. function makePolygon(a) { // N denotes the number of sides // of polygons possible var n = parseFloat(360 / (180 - a)); if (n === parseInt(n)) document.write(\"YES\"); else document.write(\"NO\"); } // Driver code var a = 90; // function to print the required answer makePolygon(a); </script>",
"e": 29222,
"s": 28663,
"text": null
},
{
"code": null,
"e": 29226,
"s": 29222,
"text": "YES"
},
{
"code": null,
"e": 29242,
"s": 29228,
"text": "bilal-hungund"
},
{
"code": null,
"e": 29255,
"s": 29242,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29263,
"s": 29255,
"text": "ankthon"
},
{
"code": null,
"e": 29269,
"s": 29263,
"text": "ukasp"
},
{
"code": null,
"e": 29276,
"s": 29269,
"text": "rdtank"
},
{
"code": null,
"e": 29281,
"s": 29276,
"text": "math"
},
{
"code": null,
"e": 29291,
"s": 29281,
"text": "Geometric"
},
{
"code": null,
"e": 29304,
"s": 29291,
"text": "Mathematical"
},
{
"code": null,
"e": 29323,
"s": 29304,
"text": "School Programming"
},
{
"code": null,
"e": 29336,
"s": 29323,
"text": "Mathematical"
},
{
"code": null,
"e": 29346,
"s": 29336,
"text": "Geometric"
},
{
"code": null,
"e": 29444,
"s": 29346,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29493,
"s": 29444,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 29546,
"s": 29493,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 29580,
"s": 29546,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 29638,
"s": 29580,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 29687,
"s": 29638,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 29717,
"s": 29687,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29777,
"s": 29717,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29792,
"s": 29777,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29835,
"s": 29792,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Find an array element such that all elements are divisible by it using c++ | Consider we have an array A with few elements. We have to find an element from A, such that all elements can be divided by it. Suppose the A is like [15, 21, 69, 33, 3, 72, 81], then the element will be 3, as all numbers can be divisible by 3.
To solve this problem, we will take the smallest number in A, then check whether all numbers can be divided by the smallest number or not, if yes, then return the number, otherwise, return false.
Live Demo
#include<iostream>
#include<algorithm>
using namespace std;
int getNumber(int a[], int n) {
int minNumber = *min_element(a, a+n);
for (int i = 1; i < n; i++)
if (a[i] % minNumber)
return -1;
return minNumber;
}
int main() {
int a[] = { 15, 21, 69, 33, 3, 72, 81 };
int n = sizeof(a) / sizeof(int);
cout << "The number is: "<< getNumber(a, n);
}
The number is: 3 | [
{
"code": null,
"e": 1306,
"s": 1062,
"text": "Consider we have an array A with few elements. We have to find an element from A, such that all elements can be divided by it. Suppose the A is like [15, 21, 69, 33, 3, 72, 81], then the element will be 3, as all numbers can be divisible by 3."
},
{
"code": null,
"e": 1502,
"s": 1306,
"text": "To solve this problem, we will take the smallest number in A, then check whether all numbers can be divided by the smallest number or not, if yes, then return the number, otherwise, return false."
},
{
"code": null,
"e": 1513,
"s": 1502,
"text": " Live Demo"
},
{
"code": null,
"e": 1888,
"s": 1513,
"text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nint getNumber(int a[], int n) {\n int minNumber = *min_element(a, a+n);\n for (int i = 1; i < n; i++)\n if (a[i] % minNumber)\n return -1;\n return minNumber;\n}\nint main() {\n int a[] = { 15, 21, 69, 33, 3, 72, 81 };\n int n = sizeof(a) / sizeof(int);\n cout << \"The number is: \"<< getNumber(a, n);\n}"
},
{
"code": null,
"e": 1905,
"s": 1888,
"text": "The number is: 3"
}
] |
Java Program to set title position in Java | To set title position, use the setTitlePosition() method in Java. Let’s say we have to position the title above the border's top line. For that, use the constant ABOVE_TOP for the border −
setTitlePosition(TitledBorder.ABOVE_TOP);
The following is an example to set title position −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LineBorder lineBorder = new LineBorder(Color.orange);
TitledBorder titledBorder = BorderFactory.createTitledBorder(lineBorder, "Demo Title");
titledBorder.setTitlePosition(TitledBorder.ABOVE_TOP);
JLabel label = new JLabel();
label.setBorder(titledBorder);
Container contentPane = frame.getContentPane();
contentPane.add(label, BorderLayout.CENTER);
frame.setSize(550, 300);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "To set title position, use the setTitlePosition() method in Java. Let’s say we have to position the title above the border's top line. For that, use the constant ABOVE_TOP for the border −"
},
{
"code": null,
"e": 1293,
"s": 1251,
"text": "setTitlePosition(TitledBorder.ABOVE_TOP);"
},
{
"code": null,
"e": 1345,
"s": 1293,
"text": "The following is an example to set title position −"
},
{
"code": null,
"e": 2233,
"s": 1345,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Container;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.border.LineBorder;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n LineBorder lineBorder = new LineBorder(Color.orange);\n TitledBorder titledBorder = BorderFactory.createTitledBorder(lineBorder, \"Demo Title\");\n titledBorder.setTitlePosition(TitledBorder.ABOVE_TOP);\n JLabel label = new JLabel();\n label.setBorder(titledBorder);\n Container contentPane = frame.getContentPane();\n contentPane.add(label, BorderLayout.CENTER);\n frame.setSize(550, 300);\n frame.setVisible(true);\n }\n}"
}
] |
Get your computer ready for machine learning: How, what and why you should use Anaconda, Miniconda and Conda | by Daniel Bourke | Towards Data Science | This article will go through what Anaconda is, what Minconda is and what Conda is, why you should know about them if you’re a data scientist or machine learning engineer and how you can use them.
Your computer is capable of running many different programs and applications. However, when you want to create or write your own, such as, building a machine learning project, it’s important to set your computer up in the right way.
Let’s say you wanted to work with a dataset of patient records to try and predict who had heart disease or not. You’ll need a few tools to do this.
One for exploring the data, another for making a predictive model, one for making graphs to present your findings to others and one more to run experiments and put all the others together.
If you’re thinking, I don’t even know where to start, don’t worry, you’re not alone. Many people have this problem. Luckily, this is where Anaconda, Miniconda and Conda come in.
Anaconda, Miniconda and Conda are tools which help you manage your other tools. We’ll get into the specifics of each shortly. Let’s start with why they’re important.
A lot of machine learning and data science is experimental. You try something and it doesn’t work, then you keep trying other things until something works or nothing works at all.
If you were doing these experiments on your own and you eventually find something which works, you’ll probably want to be able to do it again.
The same goes for if you wanted to share your work. Whether it be with a colleague, team or the world through an application powered by your machine learning system.
Anaconda, Miniconda and Conda provide the ability for you to share the foundation on which your experiment is built on.
Anaconda, Miniconda and Conda ensure that if someone else wanted to reproduce your work, they’d have the same tools as you.
So whether you’re working solo, hacking away at a machine learning problem, or working in a team of data scientists finding insights on an internet-scale dataset, Anaconda, Miniconda and Conda provide the infrastructure for a consistent experience throughout.
Anaconda and Miniconda are software distributions. Anaconda comes with over 150 data science packages, everything you could imagine, whereas, Miniconda comes with a handful of what’s needed.
A package is a piece of code someone else has written which can be run and often serves a specific purpose. You can consider a package as a tool you can use for your own projects.
Packages are helpful because without them, you would have to write far more code to get what you need done. Since many people have similar problems, you’ll often find a group of people have written code to help solve their problem and released it as a package.
Conda is a package manager. It helps you take care of your different packages by handling installing, updating and removing them.
These aren’t the only ones. There’s Pip, Pipenv and others too. But we’ll focus on Anaconda, Miniconda and Conda. They’ll be more than enough to get you started.
Anaconda can be thought of the data scientists hardware store. It’s got everything you need. From tools for exploring datasets, to tools for modelling them, to tools for visualising what you’ve found. Everyone can access the hardware store and all the tools inside.
Miniconda is the workbench of a data scientist. Every workbench starts clean with only the bare necessities. But as a project grows, so do the number of tools on the workbench. They get used, they get changed, they get swapped. Each workbench can be customised however a data scientist wants. One data scientists workbench may be completely different to another, even if they’re on the same team.
Conda helps to organise all of these tools. Although Anaconda comes with many of them ready to go, sometimes they’ll need changing. Conda is like the assistant who takes stock of all the tools. The same goes for Miniconda.
Another term for a collection of tools or packages is environment. The hardware store is an environment and each individual workbench is an environment.
For example, if you’re working on a machine learning problem and find some insights using the tools in your environment (workbench), a teammate may ask you to share your environment with them so they can reproduce your results and contribute to the project.
Use Anaconda:
If you’re after a one size fits all approach which works out of the box for most projects, have 3 GB of space on your computer.
Use Miniconda:
If you don’t have 3 GB of space on your computer and prefer a setup has only what you need.
Your main consideration when starting out with Anaconda or Miniconda is space on your computer.
If you’ve chosen Anaconda, follow the Anaconda steps. If you’ve chosen Miniconda, follow the Miniconda steps.
Note: Both Anaconda and Miniconda come with Conda. And because Conda is a package manager, what you can accomplish with Anaconda, you can do with Miniconda. In other words, the steps in the Miniconda section (creating a custom environment with Conda) will work after you’ve gone through the Anaconda section.
You can think of Anaconda as the hardware store of data science tools.
Download it to your computer and it will bring with it the tools (packages) you need to do much of your data science or machine learning work. If it doesn’t have the package you need, just like a hardware store, you can order it in (download it).
The good thing is, following these steps and installing Anaconda will install Conda too.
Note: These steps are for macOS (since that's my computer). If you're not using macOS, the concepts will be relevant but the code an images a little different.If you're on Windows, check out this guide by Anaconda.
1. Go to the Anaconda distribution page.
2. Download the appropriate Anaconda distribution for your computer (will take a while depending on your internet speed). Unless you have a specific reason, it’s a good idea to download the latest version of each (highest number).
In my case, I downloaded the macOS Python 3.7 64-bit Graphical Installer. The difference between the command line and graphical installer is one uses an application you can see, the other requires you to write lines of code. To keep it simple, we’re using the Graphical Installer.
3. Once the download has completed, double click on the download file to go through the setup steps, leaving everything as default. This will install Anaconda on your computer. It may take a couple of minutes and you’ll need up to 3 GB of space available.
4. To check the installation, if you’re on a Mac, open Terminal, if you’re on another computer, open a command line.
If it was successful, you’ll see (base) appear next to your name. This means we're in the base environment, think of this as being on the floor of the hardware store.
To see all the tools (packages) you just installed, type the code conda list and press enter. Don't worry, you won't break anything.
What you should see is four columns. Name, version, build and channel.
Name is the package name. Remember, a package is a collection of code someone else has written.
Version is the version number of the package and build is the Python version the package is made for. For now, we won’t worry about either of these but what you should know is some projects require specific version and build numbers.
Channel is the Anaconda channel the package came from, no channel means the default channel.
5. You can also check it by typing python on the command line and hitting enter. This will show you the version of Python you're running as well as whether or not Anaconda is there.
To get out of Python (the >>>), type exit() and hit enter.
6. We just downloaded the entire hardware store of data science tools (packages) to our computer.
Right now, they’re located in the default environment called (base), which was created automatically when we installed Anaconda. An environment is a collection of packages or data science tools. We'll see how to create our own environments later.
You can see all of the environments on your machine by typing conda env list (env is short for environment).
Okay, now we know we have Anaconda installed, let’s say your goal is to get set up for our project to predict heart disease with machine learning.
After doing some research, you find the tools (packages) you’ll need are:
Jupyter Notebooks — for writing Python code, running experiments and communicating your work to others.
pandas — for exploring and manipulating data.
NumPy — for performing numerical operations on data.
Matplotlib — for creating visualizations of your findings.
scikit-learn — also called sklearn, for building and analysing machine learning models.
If you’ve never used these before, don’t worry. What’s important to know if you’ve followed the steps above and installed Anaconda, these packages have been installed too.
Anaconda comes with many of the most popular and useful data science tools right out of the box. And the ones above are no exception.
7. To really test things, we’ll start a Jupyter Notebook and see if the packages above are available. To open a Jupyter Notebook, type jupyter notebook on your command line and press enter.
8. You should see the Jupyter Interface come up. It will contain all of the files you have in your current directory. Click on new in the top right corner and select Python 3, this will create a new Jupyter Notebook.
9. Now we’ll try for the other tools we need.
You can see if pandas is installed via typing the command import pandas as pd and hitting shift+enter (this is how code in a Jupyter cell is run).
If there are no errors, thanks to Anaconda, we can now use pandas for data manipulation.
10. Do the same for NumPy, Matplotlib and scikit-learn packages using the following:
NumPy — import numpy as np
Matplotlib — import matplotlib.pyplot as plt
scikit-learn — import sklearn
This may seem like a lot of steps to get started but they will form the foundation of what you will need going forward as a data scientist or machine learning engineer.
Why — We use Anaconda to access all of the code other people have written before us so we don’t have to rewrite it ourselves.
What — Anaconda provides a hardware store worth of data science tools such as, Jupyter Notebooks, pandas, NumPy and more.
How — We downloaded Anaconda from the internet onto our computer and went through an example showing how to get started with the fundamental tools.
The steps we took:
Downloaded Anaconda from the internet.Installed Anaconda to our computer.Tested in the install in terminal using conda list which showed us all the packages (data science tools) we installed.Loaded a Jupyter Notebook (one of the tools).Performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook.
Downloaded Anaconda from the internet.
Installed Anaconda to our computer.
Tested in the install in terminal using conda list which showed us all the packages (data science tools) we installed.
Loaded a Jupyter Notebook (one of the tools).
Performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook.
Using Anaconda, the whole hardware store of data science tools is great to get started. But for longer-term projects, you’ll probably want to create your own unique environments (workbenches) which only have the tools you need for the project, rather than everything.
There are several ways you can create a custom environment with Conda. For this example, we’ll download Miniconda which only contains the bare minimum of data science tools to begin with. Then we’ll go through creating a custom environment within a project folder (folders are also called directories).
It’s a good idea at the start of every project to create a new project directory. Then within this directory, keep all of the relevant files for that project there, such as the data, the code and the tools you use.
In the next steps, we’ll set up a new project folder called project_1. And within this directory, we'll create another directory called env (short for environment) which contains all the tools we need.
Then, within the env directory, we'll set up an environment to work on the same project as above, predicting heart disease. So we'll need Jupyter Notebooks, pandas, NumPy, Matplotlib and scikit-learn.
Doing it like this allows for an easy way to share your projects with others in the future.
Note: If you already have Anaconda, you don’t need Miniconda so you can skip step 1 and go straight to step 2. Since Anaconda and Miniconda both come with Conda, all of the steps from step 2 onwards in this section are compatible with the previous section.
To start, we download Miniconda from the Conda documentation website. Choose the relevant one for you. Since I’m using a Mac, I’ve chosen the Python 3.7, 64-bit pkg version.
To start, we download Miniconda from the Conda documentation website. Choose the relevant one for you. Since I’m using a Mac, I’ve chosen the Python 3.7, 64-bit pkg version.
Once it’s downloaded, go through the setup steps. Because Miniconda doesn’t come with everything Anaconda does, it takes up about 10x less disk space (2.15 GB versus 200 MB).
When the setup completes, you can check where it’s installed using which conda on the command line.
2. Create a project folder on the desktop called project_1. In practice, we use this project folder for all of our work so it can be easily shared with others.
To create a folder called project_1 on the desktop, we can use the command mkdir desktop/project_1. mkdir stands for make directory and desktop/project_1 means make project_1 on the desktop.
3. We’ll change into the newly created project folder using cd desktop/project_1. cd stands for change directory.
4. Once you’re in the project folder, the next step is to create an environment in it.
The environment contains all of the foundation code we’ll need for our project. So if we wanted to reproduce our work later or share it with someone else, we can be sure our future selves and others have the same foundations to work off as we did.
We’ll create another folder called env, inside this folder will be all of the relevant environment files. To do this we use:
$ conda create --prefix ./env pandas numpy matplotlib scikit-learn
The --prefix tag along with the . before /env means the env folder will be created in the current working directory. Which in our case, is Users/daniel/desktop/project_1/.
After running the line of code above, you’ll be asked whether you want to proceed. Press y.
When the code completes, there will now be a folder called env in the project_1 folder. You can see a list of all the files in a directory using ls which is short for list.
5. Once the environment is setup, the output in the terminal window lets us know how we can activate our new environment.
In my case, it’s conda activate Users/daniel/desktop/project_1. You'll probably want to write this command down somewhere.
This is because I’ve created the env folder on my desktop in the project_1 folder.
Running the line of code above activates our new environment. Activating the new environment changes (base) to (Users/daniel/desktop/project_1) because this is where the new environment lives.
6. Now our environment is activated, we should have access to the packages we installed above. Let’s see if we can start up a Jupyter Notebook like we did in the previous section.
To do so, we run the command jupyter notebook on the command line with our new environment activated.
7. Oops... We forgot to install Jupyter. This is a common mistake when setting up new environments for the first time. But there’s ways around it. Such as setting up environments from templates (or YAML file). We’ll see how to do that in the extension section.
To install the Jupyter package and use Jupyter Notebooks, you can use conda install jupyter.
This is similar to what we ran before to setup the environment, except now we’re focused on one package, jupyter.
It's like saying, 'Hey Conda install the jupyter package to the current environment'.
Running this command will again, ask you if you want to proceed. Press y. Conda will then install the jupyter package to your activated environment. In our case, it's the env folder in project_1.
8. Now we have Jupyter installed, let’s try open a notebook again. We can do so using jupyter notebook.
9. Beautiful, the Jupyter Interface loads up, we can create a new notebook by clicking new and selecting Python 3.
Then to test the installation of our other tools, pandas, NumPy, Matploblib and scikit-learn, we can enter the following lines of code in the first cell and then press shift+enter.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport sklearn
10. To stop your Jupyter Notebook running, press control+c in your terminal window where it’s running. When it asks if you want to proceed, press y.
11. To exit your environment you can use conda deactivate. This will take you back to the (base) environment.
12. To get back into your environment run the conda activate [ENV_NAME] command you wrote down earlier where [ENV_NAME] is your environment.
Then to get access back to Jupyter Notebooks, run the jupyter notebook command. This will load up the Jupyter Interface.
In my case, the code looks like the following:
(base) Daniels-MBP:~ daniel$ conda activate \ /Users/daniel/Desktop/project_1/env(/Users/daniel/Desktop/project_1/env) Daniels-MBP:~ daniel$ jupyter notebook
This seems like a lot of steps and it is. But these skills are important to know.
Ensuring you have a good foundational environment to work on will help save a lot of time in the future.
Imagine working in your toolshed but everything was misplaced. You might know where things are but as soon as someone else comes to help, they spend hours trying to find the right tool. Instead, now they’ve got an environment to work with.
Why — We use Miniconda when we don’t need everything Anaconda offer and to create our own custom environments we can share with others.
What — Minconda is a smaller version of Anaconda and Conda is a fully customisable package manager we can use to create and manage environments.
How — We downloaded Miniconda from the internet onto our computer, which includes Conda. We then used Conda to create our own custom environment for project_1.
The steps we took setting up a custom Conda environment (these steps will also work for Anaconda):
Downloaded Miniconda from the internet.Installed Miniconda to our computer.Create a project folder called project_1 on the desktop using mkdir project_1 then changed into it using cd project_1.Used conda create --prefix ./env pandas numpy matplotlib scikit-learn to create an environment folder called env containing pandas, NumPy, Matplotlib and scikit-learn inside our project_1 folder.Activated our environment using conda activate /Users/daniel/Desktop/project_1/envTried to load a Jupyter Notebook using jupyter notebook but it didn't work because we didn't have the package.Installed Jupyter using conda install jupyter.Started a Jupyter Notebook using jupyter notebook and performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook.
Downloaded Miniconda from the internet.
Installed Miniconda to our computer.
Create a project folder called project_1 on the desktop using mkdir project_1 then changed into it using cd project_1.
Used conda create --prefix ./env pandas numpy matplotlib scikit-learn to create an environment folder called env containing pandas, NumPy, Matplotlib and scikit-learn inside our project_1 folder.
Activated our environment using conda activate /Users/daniel/Desktop/project_1/env
Tried to load a Jupyter Notebook using jupyter notebook but it didn't work because we didn't have the package.
Installed Jupyter using conda install jupyter.
Started a Jupyter Notebook using jupyter notebook and performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook.
It’s important to remember, both Anaconda and Miniconda come with Conda. So not matter which one you download, you can perform the same steps with each.
Where Anaconda is the hardware store of data science tools and Miniconda is the workbench (software distributions), Conda is the assistant (package manager) who helps you get new tools and customise your hardware store or workbench.
The following are some helpful Conda commands you’ll want to remember.
If you’ve done all of the above, the next place you’ll want to go is how to share your environments as a YAML file. A YAML file is a common file type which can be shared easily and used easily.
To export the environment we created earlier at /Users/daniel/Desktop/project_1/env as a YAML file called environment.yaml we can use the command:
$ conda env export --prefix /Users/daniel/Desktop/project_1/env > environment.yaml
After running the export command, we can see our new YAML file stored as environment.yaml.
A sample YAML file might look like the following:
name: my_ml_envdependencies: - numpy - pandas - scikit-learn - jupyter - matplotlib
Your actual YAML file will differ depending on your environment name and what your environment contains.
Once you’ve exported your environment as a YAML file, you may want to share it with a teammate so they can recreate the environment you were working in. They might run the following command to create env2 using the environment.yaml file you sent them.
$ conda env create --file environment.yaml --name env2
Once env2 has been created, your teammate will be able to access the tools within it by activating it using conda activate env2.
There’s much more you can do with Anaconda, Miniconda and Conda and this article only scratches the surface. But what we’ve covered here is more than enough to get started.
If you’re looking for more, I’d suggest checking out the documentation. Reading through it is what helped me write this article.
Don’t worry if you don’t understand something at first, try it out, see if it works, if it doesn’t, try again.
A big shout out to the following for helping me understand Anaconda, Miniconda and Conda.
Save the environment with Conda (and how to let others run your programs) by Sébastien Eustace.
Introduction to Conda for (Data) Scientists
The entire Anaconda team and their amazing documentation | [
{
"code": null,
"e": 367,
"s": 171,
"text": "This article will go through what Anaconda is, what Minconda is and what Conda is, why you should know about them if you’re a data scientist or machine learning engineer and how you can use them."
},
{
"code": null,
"e": 600,
"s": 367,
"text": "Your computer is capable of running many different programs and applications. However, when you want to create or write your own, such as, building a machine learning project, it’s important to set your computer up in the right way."
},
{
"code": null,
"e": 748,
"s": 600,
"text": "Let’s say you wanted to work with a dataset of patient records to try and predict who had heart disease or not. You’ll need a few tools to do this."
},
{
"code": null,
"e": 937,
"s": 748,
"text": "One for exploring the data, another for making a predictive model, one for making graphs to present your findings to others and one more to run experiments and put all the others together."
},
{
"code": null,
"e": 1115,
"s": 937,
"text": "If you’re thinking, I don’t even know where to start, don’t worry, you’re not alone. Many people have this problem. Luckily, this is where Anaconda, Miniconda and Conda come in."
},
{
"code": null,
"e": 1281,
"s": 1115,
"text": "Anaconda, Miniconda and Conda are tools which help you manage your other tools. We’ll get into the specifics of each shortly. Let’s start with why they’re important."
},
{
"code": null,
"e": 1461,
"s": 1281,
"text": "A lot of machine learning and data science is experimental. You try something and it doesn’t work, then you keep trying other things until something works or nothing works at all."
},
{
"code": null,
"e": 1604,
"s": 1461,
"text": "If you were doing these experiments on your own and you eventually find something which works, you’ll probably want to be able to do it again."
},
{
"code": null,
"e": 1770,
"s": 1604,
"text": "The same goes for if you wanted to share your work. Whether it be with a colleague, team or the world through an application powered by your machine learning system."
},
{
"code": null,
"e": 1890,
"s": 1770,
"text": "Anaconda, Miniconda and Conda provide the ability for you to share the foundation on which your experiment is built on."
},
{
"code": null,
"e": 2014,
"s": 1890,
"text": "Anaconda, Miniconda and Conda ensure that if someone else wanted to reproduce your work, they’d have the same tools as you."
},
{
"code": null,
"e": 2274,
"s": 2014,
"text": "So whether you’re working solo, hacking away at a machine learning problem, or working in a team of data scientists finding insights on an internet-scale dataset, Anaconda, Miniconda and Conda provide the infrastructure for a consistent experience throughout."
},
{
"code": null,
"e": 2465,
"s": 2274,
"text": "Anaconda and Miniconda are software distributions. Anaconda comes with over 150 data science packages, everything you could imagine, whereas, Miniconda comes with a handful of what’s needed."
},
{
"code": null,
"e": 2645,
"s": 2465,
"text": "A package is a piece of code someone else has written which can be run and often serves a specific purpose. You can consider a package as a tool you can use for your own projects."
},
{
"code": null,
"e": 2906,
"s": 2645,
"text": "Packages are helpful because without them, you would have to write far more code to get what you need done. Since many people have similar problems, you’ll often find a group of people have written code to help solve their problem and released it as a package."
},
{
"code": null,
"e": 3036,
"s": 2906,
"text": "Conda is a package manager. It helps you take care of your different packages by handling installing, updating and removing them."
},
{
"code": null,
"e": 3198,
"s": 3036,
"text": "These aren’t the only ones. There’s Pip, Pipenv and others too. But we’ll focus on Anaconda, Miniconda and Conda. They’ll be more than enough to get you started."
},
{
"code": null,
"e": 3464,
"s": 3198,
"text": "Anaconda can be thought of the data scientists hardware store. It’s got everything you need. From tools for exploring datasets, to tools for modelling them, to tools for visualising what you’ve found. Everyone can access the hardware store and all the tools inside."
},
{
"code": null,
"e": 3861,
"s": 3464,
"text": "Miniconda is the workbench of a data scientist. Every workbench starts clean with only the bare necessities. But as a project grows, so do the number of tools on the workbench. They get used, they get changed, they get swapped. Each workbench can be customised however a data scientist wants. One data scientists workbench may be completely different to another, even if they’re on the same team."
},
{
"code": null,
"e": 4084,
"s": 3861,
"text": "Conda helps to organise all of these tools. Although Anaconda comes with many of them ready to go, sometimes they’ll need changing. Conda is like the assistant who takes stock of all the tools. The same goes for Miniconda."
},
{
"code": null,
"e": 4237,
"s": 4084,
"text": "Another term for a collection of tools or packages is environment. The hardware store is an environment and each individual workbench is an environment."
},
{
"code": null,
"e": 4495,
"s": 4237,
"text": "For example, if you’re working on a machine learning problem and find some insights using the tools in your environment (workbench), a teammate may ask you to share your environment with them so they can reproduce your results and contribute to the project."
},
{
"code": null,
"e": 4509,
"s": 4495,
"text": "Use Anaconda:"
},
{
"code": null,
"e": 4637,
"s": 4509,
"text": "If you’re after a one size fits all approach which works out of the box for most projects, have 3 GB of space on your computer."
},
{
"code": null,
"e": 4652,
"s": 4637,
"text": "Use Miniconda:"
},
{
"code": null,
"e": 4744,
"s": 4652,
"text": "If you don’t have 3 GB of space on your computer and prefer a setup has only what you need."
},
{
"code": null,
"e": 4840,
"s": 4744,
"text": "Your main consideration when starting out with Anaconda or Miniconda is space on your computer."
},
{
"code": null,
"e": 4950,
"s": 4840,
"text": "If you’ve chosen Anaconda, follow the Anaconda steps. If you’ve chosen Miniconda, follow the Miniconda steps."
},
{
"code": null,
"e": 5259,
"s": 4950,
"text": "Note: Both Anaconda and Miniconda come with Conda. And because Conda is a package manager, what you can accomplish with Anaconda, you can do with Miniconda. In other words, the steps in the Miniconda section (creating a custom environment with Conda) will work after you’ve gone through the Anaconda section."
},
{
"code": null,
"e": 5330,
"s": 5259,
"text": "You can think of Anaconda as the hardware store of data science tools."
},
{
"code": null,
"e": 5577,
"s": 5330,
"text": "Download it to your computer and it will bring with it the tools (packages) you need to do much of your data science or machine learning work. If it doesn’t have the package you need, just like a hardware store, you can order it in (download it)."
},
{
"code": null,
"e": 5666,
"s": 5577,
"text": "The good thing is, following these steps and installing Anaconda will install Conda too."
},
{
"code": null,
"e": 5881,
"s": 5666,
"text": "Note: These steps are for macOS (since that's my computer). If you're not using macOS, the concepts will be relevant but the code an images a little different.If you're on Windows, check out this guide by Anaconda."
},
{
"code": null,
"e": 5922,
"s": 5881,
"text": "1. Go to the Anaconda distribution page."
},
{
"code": null,
"e": 6153,
"s": 5922,
"text": "2. Download the appropriate Anaconda distribution for your computer (will take a while depending on your internet speed). Unless you have a specific reason, it’s a good idea to download the latest version of each (highest number)."
},
{
"code": null,
"e": 6434,
"s": 6153,
"text": "In my case, I downloaded the macOS Python 3.7 64-bit Graphical Installer. The difference between the command line and graphical installer is one uses an application you can see, the other requires you to write lines of code. To keep it simple, we’re using the Graphical Installer."
},
{
"code": null,
"e": 6690,
"s": 6434,
"text": "3. Once the download has completed, double click on the download file to go through the setup steps, leaving everything as default. This will install Anaconda on your computer. It may take a couple of minutes and you’ll need up to 3 GB of space available."
},
{
"code": null,
"e": 6807,
"s": 6690,
"text": "4. To check the installation, if you’re on a Mac, open Terminal, if you’re on another computer, open a command line."
},
{
"code": null,
"e": 6974,
"s": 6807,
"text": "If it was successful, you’ll see (base) appear next to your name. This means we're in the base environment, think of this as being on the floor of the hardware store."
},
{
"code": null,
"e": 7107,
"s": 6974,
"text": "To see all the tools (packages) you just installed, type the code conda list and press enter. Don't worry, you won't break anything."
},
{
"code": null,
"e": 7178,
"s": 7107,
"text": "What you should see is four columns. Name, version, build and channel."
},
{
"code": null,
"e": 7274,
"s": 7178,
"text": "Name is the package name. Remember, a package is a collection of code someone else has written."
},
{
"code": null,
"e": 7508,
"s": 7274,
"text": "Version is the version number of the package and build is the Python version the package is made for. For now, we won’t worry about either of these but what you should know is some projects require specific version and build numbers."
},
{
"code": null,
"e": 7601,
"s": 7508,
"text": "Channel is the Anaconda channel the package came from, no channel means the default channel."
},
{
"code": null,
"e": 7783,
"s": 7601,
"text": "5. You can also check it by typing python on the command line and hitting enter. This will show you the version of Python you're running as well as whether or not Anaconda is there."
},
{
"code": null,
"e": 7842,
"s": 7783,
"text": "To get out of Python (the >>>), type exit() and hit enter."
},
{
"code": null,
"e": 7940,
"s": 7842,
"text": "6. We just downloaded the entire hardware store of data science tools (packages) to our computer."
},
{
"code": null,
"e": 8187,
"s": 7940,
"text": "Right now, they’re located in the default environment called (base), which was created automatically when we installed Anaconda. An environment is a collection of packages or data science tools. We'll see how to create our own environments later."
},
{
"code": null,
"e": 8296,
"s": 8187,
"text": "You can see all of the environments on your machine by typing conda env list (env is short for environment)."
},
{
"code": null,
"e": 8443,
"s": 8296,
"text": "Okay, now we know we have Anaconda installed, let’s say your goal is to get set up for our project to predict heart disease with machine learning."
},
{
"code": null,
"e": 8517,
"s": 8443,
"text": "After doing some research, you find the tools (packages) you’ll need are:"
},
{
"code": null,
"e": 8621,
"s": 8517,
"text": "Jupyter Notebooks — for writing Python code, running experiments and communicating your work to others."
},
{
"code": null,
"e": 8667,
"s": 8621,
"text": "pandas — for exploring and manipulating data."
},
{
"code": null,
"e": 8720,
"s": 8667,
"text": "NumPy — for performing numerical operations on data."
},
{
"code": null,
"e": 8779,
"s": 8720,
"text": "Matplotlib — for creating visualizations of your findings."
},
{
"code": null,
"e": 8867,
"s": 8779,
"text": "scikit-learn — also called sklearn, for building and analysing machine learning models."
},
{
"code": null,
"e": 9039,
"s": 8867,
"text": "If you’ve never used these before, don’t worry. What’s important to know if you’ve followed the steps above and installed Anaconda, these packages have been installed too."
},
{
"code": null,
"e": 9173,
"s": 9039,
"text": "Anaconda comes with many of the most popular and useful data science tools right out of the box. And the ones above are no exception."
},
{
"code": null,
"e": 9363,
"s": 9173,
"text": "7. To really test things, we’ll start a Jupyter Notebook and see if the packages above are available. To open a Jupyter Notebook, type jupyter notebook on your command line and press enter."
},
{
"code": null,
"e": 9580,
"s": 9363,
"text": "8. You should see the Jupyter Interface come up. It will contain all of the files you have in your current directory. Click on new in the top right corner and select Python 3, this will create a new Jupyter Notebook."
},
{
"code": null,
"e": 9626,
"s": 9580,
"text": "9. Now we’ll try for the other tools we need."
},
{
"code": null,
"e": 9773,
"s": 9626,
"text": "You can see if pandas is installed via typing the command import pandas as pd and hitting shift+enter (this is how code in a Jupyter cell is run)."
},
{
"code": null,
"e": 9862,
"s": 9773,
"text": "If there are no errors, thanks to Anaconda, we can now use pandas for data manipulation."
},
{
"code": null,
"e": 9947,
"s": 9862,
"text": "10. Do the same for NumPy, Matplotlib and scikit-learn packages using the following:"
},
{
"code": null,
"e": 9974,
"s": 9947,
"text": "NumPy — import numpy as np"
},
{
"code": null,
"e": 10019,
"s": 9974,
"text": "Matplotlib — import matplotlib.pyplot as plt"
},
{
"code": null,
"e": 10049,
"s": 10019,
"text": "scikit-learn — import sklearn"
},
{
"code": null,
"e": 10218,
"s": 10049,
"text": "This may seem like a lot of steps to get started but they will form the foundation of what you will need going forward as a data scientist or machine learning engineer."
},
{
"code": null,
"e": 10344,
"s": 10218,
"text": "Why — We use Anaconda to access all of the code other people have written before us so we don’t have to rewrite it ourselves."
},
{
"code": null,
"e": 10466,
"s": 10344,
"text": "What — Anaconda provides a hardware store worth of data science tools such as, Jupyter Notebooks, pandas, NumPy and more."
},
{
"code": null,
"e": 10614,
"s": 10466,
"text": "How — We downloaded Anaconda from the internet onto our computer and went through an example showing how to get started with the fundamental tools."
},
{
"code": null,
"e": 10633,
"s": 10614,
"text": "The steps we took:"
},
{
"code": null,
"e": 10969,
"s": 10633,
"text": "Downloaded Anaconda from the internet.Installed Anaconda to our computer.Tested in the install in terminal using conda list which showed us all the packages (data science tools) we installed.Loaded a Jupyter Notebook (one of the tools).Performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook."
},
{
"code": null,
"e": 11008,
"s": 10969,
"text": "Downloaded Anaconda from the internet."
},
{
"code": null,
"e": 11044,
"s": 11008,
"text": "Installed Anaconda to our computer."
},
{
"code": null,
"e": 11163,
"s": 11044,
"text": "Tested in the install in terminal using conda list which showed us all the packages (data science tools) we installed."
},
{
"code": null,
"e": 11209,
"s": 11163,
"text": "Loaded a Jupyter Notebook (one of the tools)."
},
{
"code": null,
"e": 11309,
"s": 11209,
"text": "Performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook."
},
{
"code": null,
"e": 11577,
"s": 11309,
"text": "Using Anaconda, the whole hardware store of data science tools is great to get started. But for longer-term projects, you’ll probably want to create your own unique environments (workbenches) which only have the tools you need for the project, rather than everything."
},
{
"code": null,
"e": 11880,
"s": 11577,
"text": "There are several ways you can create a custom environment with Conda. For this example, we’ll download Miniconda which only contains the bare minimum of data science tools to begin with. Then we’ll go through creating a custom environment within a project folder (folders are also called directories)."
},
{
"code": null,
"e": 12095,
"s": 11880,
"text": "It’s a good idea at the start of every project to create a new project directory. Then within this directory, keep all of the relevant files for that project there, such as the data, the code and the tools you use."
},
{
"code": null,
"e": 12297,
"s": 12095,
"text": "In the next steps, we’ll set up a new project folder called project_1. And within this directory, we'll create another directory called env (short for environment) which contains all the tools we need."
},
{
"code": null,
"e": 12498,
"s": 12297,
"text": "Then, within the env directory, we'll set up an environment to work on the same project as above, predicting heart disease. So we'll need Jupyter Notebooks, pandas, NumPy, Matplotlib and scikit-learn."
},
{
"code": null,
"e": 12590,
"s": 12498,
"text": "Doing it like this allows for an easy way to share your projects with others in the future."
},
{
"code": null,
"e": 12847,
"s": 12590,
"text": "Note: If you already have Anaconda, you don’t need Miniconda so you can skip step 1 and go straight to step 2. Since Anaconda and Miniconda both come with Conda, all of the steps from step 2 onwards in this section are compatible with the previous section."
},
{
"code": null,
"e": 13021,
"s": 12847,
"text": "To start, we download Miniconda from the Conda documentation website. Choose the relevant one for you. Since I’m using a Mac, I’ve chosen the Python 3.7, 64-bit pkg version."
},
{
"code": null,
"e": 13195,
"s": 13021,
"text": "To start, we download Miniconda from the Conda documentation website. Choose the relevant one for you. Since I’m using a Mac, I’ve chosen the Python 3.7, 64-bit pkg version."
},
{
"code": null,
"e": 13370,
"s": 13195,
"text": "Once it’s downloaded, go through the setup steps. Because Miniconda doesn’t come with everything Anaconda does, it takes up about 10x less disk space (2.15 GB versus 200 MB)."
},
{
"code": null,
"e": 13470,
"s": 13370,
"text": "When the setup completes, you can check where it’s installed using which conda on the command line."
},
{
"code": null,
"e": 13630,
"s": 13470,
"text": "2. Create a project folder on the desktop called project_1. In practice, we use this project folder for all of our work so it can be easily shared with others."
},
{
"code": null,
"e": 13821,
"s": 13630,
"text": "To create a folder called project_1 on the desktop, we can use the command mkdir desktop/project_1. mkdir stands for make directory and desktop/project_1 means make project_1 on the desktop."
},
{
"code": null,
"e": 13935,
"s": 13821,
"text": "3. We’ll change into the newly created project folder using cd desktop/project_1. cd stands for change directory."
},
{
"code": null,
"e": 14022,
"s": 13935,
"text": "4. Once you’re in the project folder, the next step is to create an environment in it."
},
{
"code": null,
"e": 14270,
"s": 14022,
"text": "The environment contains all of the foundation code we’ll need for our project. So if we wanted to reproduce our work later or share it with someone else, we can be sure our future selves and others have the same foundations to work off as we did."
},
{
"code": null,
"e": 14395,
"s": 14270,
"text": "We’ll create another folder called env, inside this folder will be all of the relevant environment files. To do this we use:"
},
{
"code": null,
"e": 14462,
"s": 14395,
"text": "$ conda create --prefix ./env pandas numpy matplotlib scikit-learn"
},
{
"code": null,
"e": 14634,
"s": 14462,
"text": "The --prefix tag along with the . before /env means the env folder will be created in the current working directory. Which in our case, is Users/daniel/desktop/project_1/."
},
{
"code": null,
"e": 14726,
"s": 14634,
"text": "After running the line of code above, you’ll be asked whether you want to proceed. Press y."
},
{
"code": null,
"e": 14899,
"s": 14726,
"text": "When the code completes, there will now be a folder called env in the project_1 folder. You can see a list of all the files in a directory using ls which is short for list."
},
{
"code": null,
"e": 15021,
"s": 14899,
"text": "5. Once the environment is setup, the output in the terminal window lets us know how we can activate our new environment."
},
{
"code": null,
"e": 15144,
"s": 15021,
"text": "In my case, it’s conda activate Users/daniel/desktop/project_1. You'll probably want to write this command down somewhere."
},
{
"code": null,
"e": 15227,
"s": 15144,
"text": "This is because I’ve created the env folder on my desktop in the project_1 folder."
},
{
"code": null,
"e": 15420,
"s": 15227,
"text": "Running the line of code above activates our new environment. Activating the new environment changes (base) to (Users/daniel/desktop/project_1) because this is where the new environment lives."
},
{
"code": null,
"e": 15600,
"s": 15420,
"text": "6. Now our environment is activated, we should have access to the packages we installed above. Let’s see if we can start up a Jupyter Notebook like we did in the previous section."
},
{
"code": null,
"e": 15702,
"s": 15600,
"text": "To do so, we run the command jupyter notebook on the command line with our new environment activated."
},
{
"code": null,
"e": 15963,
"s": 15702,
"text": "7. Oops... We forgot to install Jupyter. This is a common mistake when setting up new environments for the first time. But there’s ways around it. Such as setting up environments from templates (or YAML file). We’ll see how to do that in the extension section."
},
{
"code": null,
"e": 16056,
"s": 15963,
"text": "To install the Jupyter package and use Jupyter Notebooks, you can use conda install jupyter."
},
{
"code": null,
"e": 16170,
"s": 16056,
"text": "This is similar to what we ran before to setup the environment, except now we’re focused on one package, jupyter."
},
{
"code": null,
"e": 16256,
"s": 16170,
"text": "It's like saying, 'Hey Conda install the jupyter package to the current environment'."
},
{
"code": null,
"e": 16452,
"s": 16256,
"text": "Running this command will again, ask you if you want to proceed. Press y. Conda will then install the jupyter package to your activated environment. In our case, it's the env folder in project_1."
},
{
"code": null,
"e": 16556,
"s": 16452,
"text": "8. Now we have Jupyter installed, let’s try open a notebook again. We can do so using jupyter notebook."
},
{
"code": null,
"e": 16671,
"s": 16556,
"text": "9. Beautiful, the Jupyter Interface loads up, we can create a new notebook by clicking new and selecting Python 3."
},
{
"code": null,
"e": 16852,
"s": 16671,
"text": "Then to test the installation of our other tools, pandas, NumPy, Matploblib and scikit-learn, we can enter the following lines of code in the first cell and then press shift+enter."
},
{
"code": null,
"e": 16935,
"s": 16852,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport sklearn"
},
{
"code": null,
"e": 17084,
"s": 16935,
"text": "10. To stop your Jupyter Notebook running, press control+c in your terminal window where it’s running. When it asks if you want to proceed, press y."
},
{
"code": null,
"e": 17194,
"s": 17084,
"text": "11. To exit your environment you can use conda deactivate. This will take you back to the (base) environment."
},
{
"code": null,
"e": 17335,
"s": 17194,
"text": "12. To get back into your environment run the conda activate [ENV_NAME] command you wrote down earlier where [ENV_NAME] is your environment."
},
{
"code": null,
"e": 17456,
"s": 17335,
"text": "Then to get access back to Jupyter Notebooks, run the jupyter notebook command. This will load up the Jupyter Interface."
},
{
"code": null,
"e": 17503,
"s": 17456,
"text": "In my case, the code looks like the following:"
},
{
"code": null,
"e": 17661,
"s": 17503,
"text": "(base) Daniels-MBP:~ daniel$ conda activate \\ /Users/daniel/Desktop/project_1/env(/Users/daniel/Desktop/project_1/env) Daniels-MBP:~ daniel$ jupyter notebook"
},
{
"code": null,
"e": 17743,
"s": 17661,
"text": "This seems like a lot of steps and it is. But these skills are important to know."
},
{
"code": null,
"e": 17848,
"s": 17743,
"text": "Ensuring you have a good foundational environment to work on will help save a lot of time in the future."
},
{
"code": null,
"e": 18088,
"s": 17848,
"text": "Imagine working in your toolshed but everything was misplaced. You might know where things are but as soon as someone else comes to help, they spend hours trying to find the right tool. Instead, now they’ve got an environment to work with."
},
{
"code": null,
"e": 18224,
"s": 18088,
"text": "Why — We use Miniconda when we don’t need everything Anaconda offer and to create our own custom environments we can share with others."
},
{
"code": null,
"e": 18369,
"s": 18224,
"text": "What — Minconda is a smaller version of Anaconda and Conda is a fully customisable package manager we can use to create and manage environments."
},
{
"code": null,
"e": 18529,
"s": 18369,
"text": "How — We downloaded Miniconda from the internet onto our computer, which includes Conda. We then used Conda to create our own custom environment for project_1."
},
{
"code": null,
"e": 18628,
"s": 18529,
"text": "The steps we took setting up a custom Conda environment (these steps will also work for Anaconda):"
},
{
"code": null,
"e": 19408,
"s": 18628,
"text": "Downloaded Miniconda from the internet.Installed Miniconda to our computer.Create a project folder called project_1 on the desktop using mkdir project_1 then changed into it using cd project_1.Used conda create --prefix ./env pandas numpy matplotlib scikit-learn to create an environment folder called env containing pandas, NumPy, Matplotlib and scikit-learn inside our project_1 folder.Activated our environment using conda activate /Users/daniel/Desktop/project_1/envTried to load a Jupyter Notebook using jupyter notebook but it didn't work because we didn't have the package.Installed Jupyter using conda install jupyter.Started a Jupyter Notebook using jupyter notebook and performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook."
},
{
"code": null,
"e": 19448,
"s": 19408,
"text": "Downloaded Miniconda from the internet."
},
{
"code": null,
"e": 19485,
"s": 19448,
"text": "Installed Miniconda to our computer."
},
{
"code": null,
"e": 19604,
"s": 19485,
"text": "Create a project folder called project_1 on the desktop using mkdir project_1 then changed into it using cd project_1."
},
{
"code": null,
"e": 19800,
"s": 19604,
"text": "Used conda create --prefix ./env pandas numpy matplotlib scikit-learn to create an environment folder called env containing pandas, NumPy, Matplotlib and scikit-learn inside our project_1 folder."
},
{
"code": null,
"e": 19883,
"s": 19800,
"text": "Activated our environment using conda activate /Users/daniel/Desktop/project_1/env"
},
{
"code": null,
"e": 19994,
"s": 19883,
"text": "Tried to load a Jupyter Notebook using jupyter notebook but it didn't work because we didn't have the package."
},
{
"code": null,
"e": 20041,
"s": 19994,
"text": "Installed Jupyter using conda install jupyter."
},
{
"code": null,
"e": 20195,
"s": 20041,
"text": "Started a Jupyter Notebook using jupyter notebook and performed a final check by importing pandas, NumPy, Matplotlib and sklearn to the Jupyter Notebook."
},
{
"code": null,
"e": 20348,
"s": 20195,
"text": "It’s important to remember, both Anaconda and Miniconda come with Conda. So not matter which one you download, you can perform the same steps with each."
},
{
"code": null,
"e": 20581,
"s": 20348,
"text": "Where Anaconda is the hardware store of data science tools and Miniconda is the workbench (software distributions), Conda is the assistant (package manager) who helps you get new tools and customise your hardware store or workbench."
},
{
"code": null,
"e": 20652,
"s": 20581,
"text": "The following are some helpful Conda commands you’ll want to remember."
},
{
"code": null,
"e": 20846,
"s": 20652,
"text": "If you’ve done all of the above, the next place you’ll want to go is how to share your environments as a YAML file. A YAML file is a common file type which can be shared easily and used easily."
},
{
"code": null,
"e": 20993,
"s": 20846,
"text": "To export the environment we created earlier at /Users/daniel/Desktop/project_1/env as a YAML file called environment.yaml we can use the command:"
},
{
"code": null,
"e": 21076,
"s": 20993,
"text": "$ conda env export --prefix /Users/daniel/Desktop/project_1/env > environment.yaml"
},
{
"code": null,
"e": 21167,
"s": 21076,
"text": "After running the export command, we can see our new YAML file stored as environment.yaml."
},
{
"code": null,
"e": 21217,
"s": 21167,
"text": "A sample YAML file might look like the following:"
},
{
"code": null,
"e": 21306,
"s": 21217,
"text": "name: my_ml_envdependencies: - numpy - pandas - scikit-learn - jupyter - matplotlib"
},
{
"code": null,
"e": 21411,
"s": 21306,
"text": "Your actual YAML file will differ depending on your environment name and what your environment contains."
},
{
"code": null,
"e": 21663,
"s": 21411,
"text": "Once you’ve exported your environment as a YAML file, you may want to share it with a teammate so they can recreate the environment you were working in. They might run the following command to create env2 using the environment.yaml file you sent them."
},
{
"code": null,
"e": 21718,
"s": 21663,
"text": "$ conda env create --file environment.yaml --name env2"
},
{
"code": null,
"e": 21847,
"s": 21718,
"text": "Once env2 has been created, your teammate will be able to access the tools within it by activating it using conda activate env2."
},
{
"code": null,
"e": 22020,
"s": 21847,
"text": "There’s much more you can do with Anaconda, Miniconda and Conda and this article only scratches the surface. But what we’ve covered here is more than enough to get started."
},
{
"code": null,
"e": 22149,
"s": 22020,
"text": "If you’re looking for more, I’d suggest checking out the documentation. Reading through it is what helped me write this article."
},
{
"code": null,
"e": 22260,
"s": 22149,
"text": "Don’t worry if you don’t understand something at first, try it out, see if it works, if it doesn’t, try again."
},
{
"code": null,
"e": 22350,
"s": 22260,
"text": "A big shout out to the following for helping me understand Anaconda, Miniconda and Conda."
},
{
"code": null,
"e": 22447,
"s": 22350,
"text": "Save the environment with Conda (and how to let others run your programs) by Sébastien Eustace."
},
{
"code": null,
"e": 22491,
"s": 22447,
"text": "Introduction to Conda for (Data) Scientists"
}
] |
How to filter rows by excluding a particular value in columns of the R data frame? | To filter rows by excluding a particular value in columns of the data frame, we can use filter_all function of dplyr package along with all_vars argument that will select all the rows except the one that includes the passed value with negation. For example, if we have a data frame called df and we want to filter rows by excluding value 2 then we can use the command
df%>%filter_all(all_vars(.!=2))
Consider the below data frame −
Live Demo
x1<-rpois(20,5)
x2<-rpois(20,5)
df1<-data.frame(x1,x2)
df1
x1 x2
1 6 5
2 3 5
3 1 4
4 8 7
5 4 5
6 2 4
7 5 1
8 2 7
9 3 5
10 5 9
11 4 10
12 6 4
13 9 1
14 3 4
15 5 5
16 6 3
17 4 7
18 4 2
19 3 7
20 8 4
Loading dplyr package and filtering rows of df1 by excluding 4 in all the columns −
library(dplyr)
df1%>%filter_all(all_vars(.!=4))
x1 x2
1 6 5
2 3 5
3 8 7
4 5 1
5 2 7
6 3 5
7 5 9
8 9 1
9 5 5
10 6 3
11 3 7
Live Demo
y1<-rpois(20,2)
y2<-rpois(20,2)
df2<-data.frame(y1,y2)
df2
y1 y2
1 1 2
2 0 2
3 0 3
4 2 3
5 1 1
6 1 3
7 6 2
8 2 3
9 2 2
10 3 2
11 3 0
12 0 5
13 0 0
14 5 5
15 1 1
16 3 3
17 3 1
18 1 1
19 2 2
20 3 0
Filtering rows of df2 by excluding 2 in all the columns −
df2%>%filter_all(all_vars(.!=2))
y1 y2
1 0 3
2 1 1
3 1 3
4 3 0
5 0 5
6 0 0
7 5 5
8 1 1
9 3 3
10 3 1
11 1 1
12 3 0 | [
{
"code": null,
"e": 1430,
"s": 1062,
"text": "To filter rows by excluding a particular value in columns of the data frame, we can use filter_all function of dplyr package along with all_vars argument that will select all the rows except the one that includes the passed value with negation. For example, if we have a data frame called df and we want to filter rows by excluding value 2 then we can use the command"
},
{
"code": null,
"e": 1462,
"s": 1430,
"text": "df%>%filter_all(all_vars(.!=2))"
},
{
"code": null,
"e": 1494,
"s": 1462,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1505,
"s": 1494,
"text": " Live Demo"
},
{
"code": null,
"e": 1564,
"s": 1505,
"text": "x1<-rpois(20,5)\nx2<-rpois(20,5)\ndf1<-data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1733,
"s": 1564,
"text": " x1 x2\n1 6 5\n2 3 5\n3 1 4\n4 8 7\n5 4 5\n6 2 4\n7 5 1\n8 2 7\n9 3 5\n10 5 9\n11 4 10\n12 6 4\n13 9 1\n14 3 4\n15 5 5\n16 6 3\n17 4 7\n18 4 2\n19 3 7\n20 8 4"
},
{
"code": null,
"e": 1817,
"s": 1733,
"text": "Loading dplyr package and filtering rows of df1 by excluding 4 in all the columns −"
},
{
"code": null,
"e": 1865,
"s": 1817,
"text": "library(dplyr)\ndf1%>%filter_all(all_vars(.!=4))"
},
{
"code": null,
"e": 1962,
"s": 1865,
"text": " x1 x2\n1 6 5\n2 3 5\n3 8 7\n4 5 1\n5 2 7\n6 3 5\n7 5 9\n8 9 1\n9 5 5\n10 6 3\n11 3 7"
},
{
"code": null,
"e": 1973,
"s": 1962,
"text": " Live Demo"
},
{
"code": null,
"e": 2032,
"s": 1973,
"text": "y1<-rpois(20,2)\ny2<-rpois(20,2)\ndf2<-data.frame(y1,y2)\ndf2"
},
{
"code": null,
"e": 2222,
"s": 2032,
"text": " y1 y2\n1 1 2\n2 0 2\n3 0 3\n4 2 3\n5 1 1\n6 1 3\n7 6 2\n8 2 3\n9 2 2\n10 3 2\n11 3 0\n12 0 5\n13 0 0\n14 5 5\n15 1 1\n16 3 3\n17 3 1\n18 1 1\n19 2 2\n20 3 0"
},
{
"code": null,
"e": 2280,
"s": 2222,
"text": "Filtering rows of df2 by excluding 2 in all the columns −"
},
{
"code": null,
"e": 2313,
"s": 2280,
"text": "df2%>%filter_all(all_vars(.!=2))"
},
{
"code": null,
"e": 2418,
"s": 2313,
"text": " y1 y2\n1 0 3\n2 1 1\n3 1 3\n4 3 0\n5 0 5\n6 0 0\n7 5 5\n8 1 1\n9 3 3\n10 3 1\n11 1 1\n12 3 0"
}
] |
How to open chrome default profile with selenium? | We can open Chrome default profile with Selenium. To get the Chrome profile path, we need to input chrome://version/ in the Chrome browser and then press enter.
We need to use the ChromeOptions class to open the default Chrome profile. We need to use the add_argument method to specify the path of the Chrome profile.
o = webdriver.ChromeOptions()
o.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}
Code Implementation
from selenium import webdriver
#object of ChromeOptions class
o = webdriver.ChromeOptions()
#adding Chrome Profile Path
o.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe", options=o)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#get browser title
print(driver.title)
#quit browser
driver.quit() | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "We can open Chrome default profile with Selenium. To get the Chrome profile path, we need to input chrome://version/ in the Chrome browser and then press enter."
},
{
"code": null,
"e": 1380,
"s": 1223,
"text": "We need to use the ChromeOptions class to open the default Chrome profile. We need to use the add_argument method to specify the path of the Chrome profile."
},
{
"code": null,
"e": 1481,
"s": 1380,
"text": "o = webdriver.ChromeOptions()\no.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}"
},
{
"code": null,
"e": 1501,
"s": 1481,
"text": "Code Implementation"
},
{
"code": null,
"e": 1973,
"s": 1501,
"text": "from selenium import webdriver\n#object of ChromeOptions class\no = webdriver.ChromeOptions()\n#adding Chrome Profile Path\no.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\", options=o)\n#maximize browser\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#get browser title\nprint(driver.title)\n#quit browser\ndriver.quit()"
}
] |
Stacking Classifiers for Higher Predictive Performance | by Frank Ceballos | Towards Data Science | Purpose: The purpose of this article is to provide the reader with the necessary tools to implement the ensemble learning technique known as stacking.
Materials and methods: Using Scikit-learn, we generate a Madelon-like data set for a classification task. Then a Support Vector classifier (SVC), Nu-Support Vector classifier (NuSVC), a Multi-layer perceptron (MLP), and a Random Forest classifier will be individually trained. The performance of each classifier will be measured using the area under the receiver operating curve (AUC). Finally, we stack the predictions of these classifiers using the StackingCVClassifier object and compare the results.
Hardware: We train and evaluate our models on a workstation equipped with Inter(R)Core(TM) i7–8700 with 12 CPU @ 3.70 Ghz and NVIDIA GeForce RTX 2080.
Note: In the case you’re starting from scratch, I advise you follow this article to install all the necessary libraries. Finally, it will be assumed that the reader is familiar with Python, Pandas, Scikit-learn, and ensemble methods. The whole contents of this article can be found on my GitHub. You’re welcomed to fork it.
Notation: Bold text will represent either a list, dictionary, tuple, a Pandas DataFrame object, or will be referring to a figure or script. This notation will be used to represent parameters in an object or command lines to run in the terminal.
The simplest form of stacking can be described as an ensemble learning technique where the predictions of multiple classifiers (referred as level-one classifiers) are used as new features to train a meta-classifier. The meta-classifier can be any classifier of your choice. Figure 1 shows how three different classifiers get trained. Their predictions get stacked and are used as features to train the meta-classifier which makes the final prediction.
To prevent information from leaking into the training from the target (the thing you’re trying to predict), the following rule should be followed when stacking classifiers:
The level one predictions should come from a subset of the training data that was not used to train the level one classifiers.
The level one predictions should come from a subset of the training data that was not used to train the level one classifiers.
A simple way to achieve this is to split your training set in half. Use the first half of your training data to train the level one classifiers. Then use the trained level one classifiers to make predictions on the second half of the training data. These predictions should then be used to train meta-classifier.
A more robust way to do this, is to use k-fold cross validation to generate the level one predictions. Here, the training data is split into k-folds. Then the first k-1 folds are used to train the level one classifiers. The validation fold is then used to generate a subset of the level one predictions. The process is repeated for each unique group. Figure 2 illustrates this process.
The avid reader might be wondering, why not stack another layer of classifiers? Well you can but this would add more complexity to your stack. For example consider the following architecture:
This is starting to look like a neural network where each neuron is a classifier. The number and type of classifiers used in level two don’t necessary need to be the same than the ones used in level one — see how things are starting to get out of hand real quick. For example, the level one classifiers can be an Extra Trees classifier, a Decision Tree classifier, and a Support Vector Classifier, and the level two classifiers can be an artificial neural network, a Random Forest, and a Support Vector Classifier. In this article, we will implement the Stacking classifier architecture shown in Figure 2.
Before you start stacking classifiers, it’s advisable that you first consider all your other options to boost your predictive performance. As a guide, consider the following questions to determine if you should start stacking:
Is it possible for you to get a hold of more data? In machine learning, data is king (that is the biggest boost in performance can be done by gathering more data); therefore, if it this is a possibility you should focus your efforts in putting together a bigger more diverse data set.
Is it possible to add more features to your data set? For example, you can use the pixel intensity values in an image as features. You could also extract texture features from these images, which considers how pixel intensity values are spatially distributed. Is important that you collect as many features as possible from the problem at hand. This should be done simply because you do not know which of these features are good predictors. Remember, the predictive power of any model should mainly stem from the features used to train it and not from the algorithm itself.
Have you correctly preprocess all of your data? If you push trash into a model, trash should come out. Make sure that you visually explore all of your features to gain a better understanding of them. Take care of missing values, outliers, and ensure that your data set is not grotesquely imbalanced. Scale your features, remove all redundant features, apply feature selection methods if your number of features is large, and consider feature engineering.
Have you explored the predictive performance of a large set of classifiers with your data set? Have you carefully tuned these classifiers?
If your answer to all of this questions was a yes and you’re willing to do anything for a possible boost in performance consider stacking.
The easiest way to implement the stacking architecture shown in Figure 2 is to use the MLXTEND Python library. To install it read their GitHub ReadMe file found here. If you have Anaconda on Windows, launch Anaconda prompt, navigate to the conda environment you want to install this module, and run the following command:
conda install -c conda-forge mlxtend
or you can use pip:
pip install mlxtend
Disclaimer: I’m almost certain this won’t break your Python environment but if it does don’t blame me. Here is a guide in How to Install A Python Based Machine Learning Environment in Windows using Anaconda for the interested reader.
We will generate a Madelon-like synthetic data set using Scikit-learn for a classification task. This is the same data set I used to explore the performance of various models in a previous article I published in Medium. The Madelon data set is an artificial data set that contains 32 clusters placed on the vertices of a five-dimensional hyper-cube with sides of length 1. The clusters are randomly labeled 0 or 1 (2 classes).
The data set that we will generate will contain 30 features, where 5 of them will be informative, 15 will be redundant (but informative), 5 of them will be repeated, and the last 5 will be useless since they will be filled with random noise. The columns of the data set will be ordered as follows:
Informative features — Columns 1–5: These features are the only features you really need to built your model. Hence, a five-dimensional hyper-cube.Redundant features — Columns 6–20. These features are made by linearly combining the informative features with different random weights. You can think of these as engineered features.Repeated features — Columns 21–25: These features are drawn randomly from either the informative or redundant features.Useless features — Columns 26–30. These features are filled with random noise.
Informative features — Columns 1–5: These features are the only features you really need to built your model. Hence, a five-dimensional hyper-cube.
Redundant features — Columns 6–20. These features are made by linearly combining the informative features with different random weights. You can think of these as engineered features.
Repeated features — Columns 21–25: These features are drawn randomly from either the informative or redundant features.
Useless features — Columns 26–30. These features are filled with random noise.
Let’s start by importing the libraries.
Now we can generate the data.
Once we have our data, we can proceed with creating a training and test set.
Now we can scale our data set. We will do so via Z-score normalization.
We are done preprocessing the data set. In this example, we won’t go through the trouble of removing highly correlated, redundant, and noisy features. However, it is important that you take care of this in any project you might be tackling.
For the purpose of illustration, we will train a Support Vector Classifier (SVC), Multi-layer Perceptron (MLP) classifier, Nu-Support Vector classifier (NuSVC), and a Random Forest (RF) classifier— classifiers available in Scikit-learn. The hyper-parameters for these classifiers will be set — we will assume that we did our best tuning them. To put it bluntly, if your classifiers are trash, a stack of them would probably be trash too. Additionally, to obtain reproducible results, the random_state on each of these classifiers has been fixed.
To stack them, we will use the StackingCVClassifier from MLXTEND. I will recommend that you take a look at the official documentation since it goes in detail over useful examples of how to implement the StackingCVClassifier. For example, it shows you how to stack classifiers that operate on different feature subsets — that’s so cool. Finally, we will set the use_probas parameter in StackingCVClassifier to True. This means that the classifiers in the first level will pass predictions that are probabilities and not a binary output (0 or 1). However, this does not mean you should use this setting, it might be more beneficial for your work if you set use_probas to False; however, the only way to know that is to actually do it. As the meta_classifier we select a SVC and use it’s default parameters.
Finally, for convenience, we put all the classifiers in a dictionary.
We train each classifier and save it into dictionary labeled classifiers. After a classifier is trained, it will be saved into the same dictionary.
Now we are ready to make predictions on the test set. Here we first create results, a pandas DataFrame object. Then using a for loop, we iterate through the trained classifiers and store the predictions in results. Finally, in line 14, we add a new column labeled “Target” with the actual targets, either
Now is time to visualize the results. We will do so by creating a figure with 5 subplots. On each subplot, we will show the probability distribution obtained on the test set from each classifier. We will also report on the area under the receiver operating curve (AUC).
Nice! Each classifier individually obtained an AUC less than 0.909; however, by stacking them we obtained an AUC = 0.918. That’s a pretty nice boost don’t you think?
The StackingCVClassifier offers you the option to tune the parameters of each of the classifiers as well as the meta-estimators. However, I do not recommend to do a full blown search with the StackingCVClassifier. For example, suppose that you wanted to use four classifiers each with a parameter grid of 100 points — a fairly small grid to be honest. How long would it take to explore this space? Let’s do a simple calculation:
100 * 100 * 100 * 100 = 100 million models you have to fit
Assuming that each model takes 0.5 second to fit, that would take 50 million seconds or more simply put 1.6 years. Nobody haves time for that. This calculation did not considered the fact that the meta-classifier is not fixed and contains it’s own parameters that need to be tuned. That’s why I would recommend that you first tune your classifiers individually. After that, you can stack them and only tune the meta-classifier. If you do decide to tune the stack of classifiers, make sure you tune about the optimal point in parameter space for each one of them.
In this example, we first create a parameter grid for the meta-classifier — a Support Vector Classifier. Then we conduct an exhaustive search using GridSearchCV to determine the point in the parameter grid that yields the highest performance. The results are printed out to the console.
The AUC of the tuned Stacking classifier is 0.923
Nice, we manage to push the Stacking classifier AUC from 0.918 to 0.923 by tuning the meta-classifier. However, we are not done here. Let’s see if we can get more out of the Stacking classifier. To do so, we will create a set of Stacking classifiers each with a unique combination/stack of classifiers in the first layer. For each Stacking classifier, the meta-classifier will be tuned. The results will be printed out to the console.
AUC of stack ('SVC', 'MLP'): 0.876AUC of stack ('SVC', 'NuSVC'): 0.877AUC of stack ('SVC', 'RF'): 0.877AUC of stack ('MLP', 'NuSVC'): 0.876AUC of stack ('MLP', 'RF'): 0.877AUC of stack ('NuSVC', 'RF'): 0.877AUC of stack ('SVC', 'MLP', 'NuSVC'): 0.875AUC of stack ('SVC', 'MLP', 'RF'): 0.876AUC of stack ('SVC', 'NuSVC', 'RF'): 0.879AUC of stack ('MLP', 'NuSVC', 'RF'): 0.875AUC of stack ('SVC', 'MLP', 'NuSVC', 'RF'): 0.923
Well it turns out that the we obtain the highest AUC if we stack all of the classifiers together. However, this will not always be the case. Sometimes stacking less classifiers will yield a higher performance. It actually took me a whole day to figure out what classifiers to stack together in order to get this boost. Additionally, I noticed that sometimes by stacking I obtained lower performances.The trick is to stack classifiers that make up for the errors of each other and not work against each other.
I started this article to introduce the reader to technique of stacking. It was suppose to be short and quick but it turned to be quite long. If you made it this far, I appreciate your time. I hope this is of help in your endeavors. I would like to point out that stacking classifiers might not always work and it can be a tedious process for a small boost; however, if done correctly and luck is on your side, you will be able to gain a boost in performance. I recommend that you first explore other options to boost your performance. The process of stacking should be left to the end since it can be time consuming and the rewards might be minimal. Finally, if you stack trash, is very likely that trash will come out. The whole contents of this article can be found here. All the best and keep learning!
You can find me in LinkedIn. | [
{
"code": null,
"e": 323,
"s": 172,
"text": "Purpose: The purpose of this article is to provide the reader with the necessary tools to implement the ensemble learning technique known as stacking."
},
{
"code": null,
"e": 827,
"s": 323,
"text": "Materials and methods: Using Scikit-learn, we generate a Madelon-like data set for a classification task. Then a Support Vector classifier (SVC), Nu-Support Vector classifier (NuSVC), a Multi-layer perceptron (MLP), and a Random Forest classifier will be individually trained. The performance of each classifier will be measured using the area under the receiver operating curve (AUC). Finally, we stack the predictions of these classifiers using the StackingCVClassifier object and compare the results."
},
{
"code": null,
"e": 978,
"s": 827,
"text": "Hardware: We train and evaluate our models on a workstation equipped with Inter(R)Core(TM) i7–8700 with 12 CPU @ 3.70 Ghz and NVIDIA GeForce RTX 2080."
},
{
"code": null,
"e": 1302,
"s": 978,
"text": "Note: In the case you’re starting from scratch, I advise you follow this article to install all the necessary libraries. Finally, it will be assumed that the reader is familiar with Python, Pandas, Scikit-learn, and ensemble methods. The whole contents of this article can be found on my GitHub. You’re welcomed to fork it."
},
{
"code": null,
"e": 1547,
"s": 1302,
"text": "Notation: Bold text will represent either a list, dictionary, tuple, a Pandas DataFrame object, or will be referring to a figure or script. This notation will be used to represent parameters in an object or command lines to run in the terminal."
},
{
"code": null,
"e": 1999,
"s": 1547,
"text": "The simplest form of stacking can be described as an ensemble learning technique where the predictions of multiple classifiers (referred as level-one classifiers) are used as new features to train a meta-classifier. The meta-classifier can be any classifier of your choice. Figure 1 shows how three different classifiers get trained. Their predictions get stacked and are used as features to train the meta-classifier which makes the final prediction."
},
{
"code": null,
"e": 2172,
"s": 1999,
"text": "To prevent information from leaking into the training from the target (the thing you’re trying to predict), the following rule should be followed when stacking classifiers:"
},
{
"code": null,
"e": 2299,
"s": 2172,
"text": "The level one predictions should come from a subset of the training data that was not used to train the level one classifiers."
},
{
"code": null,
"e": 2426,
"s": 2299,
"text": "The level one predictions should come from a subset of the training data that was not used to train the level one classifiers."
},
{
"code": null,
"e": 2739,
"s": 2426,
"text": "A simple way to achieve this is to split your training set in half. Use the first half of your training data to train the level one classifiers. Then use the trained level one classifiers to make predictions on the second half of the training data. These predictions should then be used to train meta-classifier."
},
{
"code": null,
"e": 3125,
"s": 2739,
"text": "A more robust way to do this, is to use k-fold cross validation to generate the level one predictions. Here, the training data is split into k-folds. Then the first k-1 folds are used to train the level one classifiers. The validation fold is then used to generate a subset of the level one predictions. The process is repeated for each unique group. Figure 2 illustrates this process."
},
{
"code": null,
"e": 3317,
"s": 3125,
"text": "The avid reader might be wondering, why not stack another layer of classifiers? Well you can but this would add more complexity to your stack. For example consider the following architecture:"
},
{
"code": null,
"e": 3923,
"s": 3317,
"text": "This is starting to look like a neural network where each neuron is a classifier. The number and type of classifiers used in level two don’t necessary need to be the same than the ones used in level one — see how things are starting to get out of hand real quick. For example, the level one classifiers can be an Extra Trees classifier, a Decision Tree classifier, and a Support Vector Classifier, and the level two classifiers can be an artificial neural network, a Random Forest, and a Support Vector Classifier. In this article, we will implement the Stacking classifier architecture shown in Figure 2."
},
{
"code": null,
"e": 4150,
"s": 3923,
"text": "Before you start stacking classifiers, it’s advisable that you first consider all your other options to boost your predictive performance. As a guide, consider the following questions to determine if you should start stacking:"
},
{
"code": null,
"e": 4435,
"s": 4150,
"text": "Is it possible for you to get a hold of more data? In machine learning, data is king (that is the biggest boost in performance can be done by gathering more data); therefore, if it this is a possibility you should focus your efforts in putting together a bigger more diverse data set."
},
{
"code": null,
"e": 5009,
"s": 4435,
"text": "Is it possible to add more features to your data set? For example, you can use the pixel intensity values in an image as features. You could also extract texture features from these images, which considers how pixel intensity values are spatially distributed. Is important that you collect as many features as possible from the problem at hand. This should be done simply because you do not know which of these features are good predictors. Remember, the predictive power of any model should mainly stem from the features used to train it and not from the algorithm itself."
},
{
"code": null,
"e": 5464,
"s": 5009,
"text": "Have you correctly preprocess all of your data? If you push trash into a model, trash should come out. Make sure that you visually explore all of your features to gain a better understanding of them. Take care of missing values, outliers, and ensure that your data set is not grotesquely imbalanced. Scale your features, remove all redundant features, apply feature selection methods if your number of features is large, and consider feature engineering."
},
{
"code": null,
"e": 5603,
"s": 5464,
"text": "Have you explored the predictive performance of a large set of classifiers with your data set? Have you carefully tuned these classifiers?"
},
{
"code": null,
"e": 5742,
"s": 5603,
"text": "If your answer to all of this questions was a yes and you’re willing to do anything for a possible boost in performance consider stacking."
},
{
"code": null,
"e": 6064,
"s": 5742,
"text": "The easiest way to implement the stacking architecture shown in Figure 2 is to use the MLXTEND Python library. To install it read their GitHub ReadMe file found here. If you have Anaconda on Windows, launch Anaconda prompt, navigate to the conda environment you want to install this module, and run the following command:"
},
{
"code": null,
"e": 6101,
"s": 6064,
"text": "conda install -c conda-forge mlxtend"
},
{
"code": null,
"e": 6121,
"s": 6101,
"text": "or you can use pip:"
},
{
"code": null,
"e": 6141,
"s": 6121,
"text": "pip install mlxtend"
},
{
"code": null,
"e": 6375,
"s": 6141,
"text": "Disclaimer: I’m almost certain this won’t break your Python environment but if it does don’t blame me. Here is a guide in How to Install A Python Based Machine Learning Environment in Windows using Anaconda for the interested reader."
},
{
"code": null,
"e": 6802,
"s": 6375,
"text": "We will generate a Madelon-like synthetic data set using Scikit-learn for a classification task. This is the same data set I used to explore the performance of various models in a previous article I published in Medium. The Madelon data set is an artificial data set that contains 32 clusters placed on the vertices of a five-dimensional hyper-cube with sides of length 1. The clusters are randomly labeled 0 or 1 (2 classes)."
},
{
"code": null,
"e": 7100,
"s": 6802,
"text": "The data set that we will generate will contain 30 features, where 5 of them will be informative, 15 will be redundant (but informative), 5 of them will be repeated, and the last 5 will be useless since they will be filled with random noise. The columns of the data set will be ordered as follows:"
},
{
"code": null,
"e": 7628,
"s": 7100,
"text": "Informative features — Columns 1–5: These features are the only features you really need to built your model. Hence, a five-dimensional hyper-cube.Redundant features — Columns 6–20. These features are made by linearly combining the informative features with different random weights. You can think of these as engineered features.Repeated features — Columns 21–25: These features are drawn randomly from either the informative or redundant features.Useless features — Columns 26–30. These features are filled with random noise."
},
{
"code": null,
"e": 7776,
"s": 7628,
"text": "Informative features — Columns 1–5: These features are the only features you really need to built your model. Hence, a five-dimensional hyper-cube."
},
{
"code": null,
"e": 7960,
"s": 7776,
"text": "Redundant features — Columns 6–20. These features are made by linearly combining the informative features with different random weights. You can think of these as engineered features."
},
{
"code": null,
"e": 8080,
"s": 7960,
"text": "Repeated features — Columns 21–25: These features are drawn randomly from either the informative or redundant features."
},
{
"code": null,
"e": 8159,
"s": 8080,
"text": "Useless features — Columns 26–30. These features are filled with random noise."
},
{
"code": null,
"e": 8199,
"s": 8159,
"text": "Let’s start by importing the libraries."
},
{
"code": null,
"e": 8229,
"s": 8199,
"text": "Now we can generate the data."
},
{
"code": null,
"e": 8306,
"s": 8229,
"text": "Once we have our data, we can proceed with creating a training and test set."
},
{
"code": null,
"e": 8378,
"s": 8306,
"text": "Now we can scale our data set. We will do so via Z-score normalization."
},
{
"code": null,
"e": 8619,
"s": 8378,
"text": "We are done preprocessing the data set. In this example, we won’t go through the trouble of removing highly correlated, redundant, and noisy features. However, it is important that you take care of this in any project you might be tackling."
},
{
"code": null,
"e": 9165,
"s": 8619,
"text": "For the purpose of illustration, we will train a Support Vector Classifier (SVC), Multi-layer Perceptron (MLP) classifier, Nu-Support Vector classifier (NuSVC), and a Random Forest (RF) classifier— classifiers available in Scikit-learn. The hyper-parameters for these classifiers will be set — we will assume that we did our best tuning them. To put it bluntly, if your classifiers are trash, a stack of them would probably be trash too. Additionally, to obtain reproducible results, the random_state on each of these classifiers has been fixed."
},
{
"code": null,
"e": 9970,
"s": 9165,
"text": "To stack them, we will use the StackingCVClassifier from MLXTEND. I will recommend that you take a look at the official documentation since it goes in detail over useful examples of how to implement the StackingCVClassifier. For example, it shows you how to stack classifiers that operate on different feature subsets — that’s so cool. Finally, we will set the use_probas parameter in StackingCVClassifier to True. This means that the classifiers in the first level will pass predictions that are probabilities and not a binary output (0 or 1). However, this does not mean you should use this setting, it might be more beneficial for your work if you set use_probas to False; however, the only way to know that is to actually do it. As the meta_classifier we select a SVC and use it’s default parameters."
},
{
"code": null,
"e": 10040,
"s": 9970,
"text": "Finally, for convenience, we put all the classifiers in a dictionary."
},
{
"code": null,
"e": 10188,
"s": 10040,
"text": "We train each classifier and save it into dictionary labeled classifiers. After a classifier is trained, it will be saved into the same dictionary."
},
{
"code": null,
"e": 10493,
"s": 10188,
"text": "Now we are ready to make predictions on the test set. Here we first create results, a pandas DataFrame object. Then using a for loop, we iterate through the trained classifiers and store the predictions in results. Finally, in line 14, we add a new column labeled “Target” with the actual targets, either"
},
{
"code": null,
"e": 10763,
"s": 10493,
"text": "Now is time to visualize the results. We will do so by creating a figure with 5 subplots. On each subplot, we will show the probability distribution obtained on the test set from each classifier. We will also report on the area under the receiver operating curve (AUC)."
},
{
"code": null,
"e": 10929,
"s": 10763,
"text": "Nice! Each classifier individually obtained an AUC less than 0.909; however, by stacking them we obtained an AUC = 0.918. That’s a pretty nice boost don’t you think?"
},
{
"code": null,
"e": 11358,
"s": 10929,
"text": "The StackingCVClassifier offers you the option to tune the parameters of each of the classifiers as well as the meta-estimators. However, I do not recommend to do a full blown search with the StackingCVClassifier. For example, suppose that you wanted to use four classifiers each with a parameter grid of 100 points — a fairly small grid to be honest. How long would it take to explore this space? Let’s do a simple calculation:"
},
{
"code": null,
"e": 11417,
"s": 11358,
"text": "100 * 100 * 100 * 100 = 100 million models you have to fit"
},
{
"code": null,
"e": 11980,
"s": 11417,
"text": "Assuming that each model takes 0.5 second to fit, that would take 50 million seconds or more simply put 1.6 years. Nobody haves time for that. This calculation did not considered the fact that the meta-classifier is not fixed and contains it’s own parameters that need to be tuned. That’s why I would recommend that you first tune your classifiers individually. After that, you can stack them and only tune the meta-classifier. If you do decide to tune the stack of classifiers, make sure you tune about the optimal point in parameter space for each one of them."
},
{
"code": null,
"e": 12267,
"s": 11980,
"text": "In this example, we first create a parameter grid for the meta-classifier — a Support Vector Classifier. Then we conduct an exhaustive search using GridSearchCV to determine the point in the parameter grid that yields the highest performance. The results are printed out to the console."
},
{
"code": null,
"e": 12317,
"s": 12267,
"text": "The AUC of the tuned Stacking classifier is 0.923"
},
{
"code": null,
"e": 12752,
"s": 12317,
"text": "Nice, we manage to push the Stacking classifier AUC from 0.918 to 0.923 by tuning the meta-classifier. However, we are not done here. Let’s see if we can get more out of the Stacking classifier. To do so, we will create a set of Stacking classifiers each with a unique combination/stack of classifiers in the first layer. For each Stacking classifier, the meta-classifier will be tuned. The results will be printed out to the console."
},
{
"code": null,
"e": 13176,
"s": 12752,
"text": "AUC of stack ('SVC', 'MLP'): 0.876AUC of stack ('SVC', 'NuSVC'): 0.877AUC of stack ('SVC', 'RF'): 0.877AUC of stack ('MLP', 'NuSVC'): 0.876AUC of stack ('MLP', 'RF'): 0.877AUC of stack ('NuSVC', 'RF'): 0.877AUC of stack ('SVC', 'MLP', 'NuSVC'): 0.875AUC of stack ('SVC', 'MLP', 'RF'): 0.876AUC of stack ('SVC', 'NuSVC', 'RF'): 0.879AUC of stack ('MLP', 'NuSVC', 'RF'): 0.875AUC of stack ('SVC', 'MLP', 'NuSVC', 'RF'): 0.923"
},
{
"code": null,
"e": 13685,
"s": 13176,
"text": "Well it turns out that the we obtain the highest AUC if we stack all of the classifiers together. However, this will not always be the case. Sometimes stacking less classifiers will yield a higher performance. It actually took me a whole day to figure out what classifiers to stack together in order to get this boost. Additionally, I noticed that sometimes by stacking I obtained lower performances.The trick is to stack classifiers that make up for the errors of each other and not work against each other."
},
{
"code": null,
"e": 14492,
"s": 13685,
"text": "I started this article to introduce the reader to technique of stacking. It was suppose to be short and quick but it turned to be quite long. If you made it this far, I appreciate your time. I hope this is of help in your endeavors. I would like to point out that stacking classifiers might not always work and it can be a tedious process for a small boost; however, if done correctly and luck is on your side, you will be able to gain a boost in performance. I recommend that you first explore other options to boost your performance. The process of stacking should be left to the end since it can be time consuming and the rewards might be minimal. Finally, if you stack trash, is very likely that trash will come out. The whole contents of this article can be found here. All the best and keep learning!"
}
] |
Spring MVC - Error Handling Example | The following example shows how to use Error Handling and Validators in forms using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
package com.tutorialspoint;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class StudentValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Student.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"name", "required.name","Field name is required.");
}
}
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@Autowired
@Qualifier("studentValidator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("addStudent", "command", new Student());
}
@ModelAttribute("student")
public Student createStudentModel() {
return new Student();
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "addStudent";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id = "studentValidator" class = "com.tutorialspoint.StudentValidator" />
</beans>
Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when student() method is called, it returns addStudent.jsp view.
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering the result.jsp. In case there are errors generated using validator then same view "addStudent" is returned, Spring automatically injects error messages from BindingResult in view.
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent" commandName = "student">
<form:errors path = "*" cssClass = "errorblock" element = "div" />
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
<td><form:errors path = "name" cssClass = "error" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Here we are using <form:errors /> tag with path="*" to render error messages. For example
<form:errors path = "*" cssClass = "errorblock" element = "div" />
It will render the error messages for all input validations.
We are using <form:errors /> tag with path="name" to render error message for name field. For example
<form:errors path = "name" cssClass = "error" />
It will render error messages for the name field validations.
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat's webapps folder.
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL − http://localhost:8080/HelloWeb/addStudent and we will see the following screen, if everything is fine with the Spring Web Application.
After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3076,
"s": 2791,
"text": "The following example shows how to use Error Handling and Validators in forms using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework."
},
{
"code": null,
"e": 3550,
"s": 3076,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 4097,
"s": 3550,
"text": "package com.tutorialspoint;\n\nimport org.springframework.validation.Errors;\nimport org.springframework.validation.ValidationUtils;\nimport org.springframework.validation.Validator;\n\npublic class StudentValidator implements Validator {\n\n @Override\n public boolean supports(Class<?> clazz) {\n return Student.class.isAssignableFrom(clazz);\n }\n\n @Override\n public void validate(Object target, Errors errors) {\t\t\n ValidationUtils.rejectIfEmptyOrWhitespace(errors, \n \"name\", \"required.name\",\"Field name is required.\");\n }\n}\n"
},
{
"code": null,
"e": 5846,
"s": 4097,
"text": "package com.tutorialspoint;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.validation.BindingResult;\nimport org.springframework.validation.Validator;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.WebDataBinder;\nimport org.springframework.web.bind.annotation.InitBinder;\nimport org.springframework.web.bind.annotation.ModelAttribute;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.servlet.ModelAndView;\n\n@Controller\npublic class StudentController {\n\n @Autowired\n @Qualifier(\"studentValidator\")\n private Validator validator;\n\n @InitBinder\n private void initBinder(WebDataBinder binder) {\n binder.setValidator(validator);\n }\n\n @RequestMapping(value = \"/addStudent\", method = RequestMethod.GET)\n public ModelAndView student() {\n return new ModelAndView(\"addStudent\", \"command\", new Student());\n }\n\n @ModelAttribute(\"student\")\n public Student createStudentModel() {\t\n return new Student();\n }\n\n @RequestMapping(value = \"/addStudent\", method = RequestMethod.POST)\n public String addStudent(@ModelAttribute(\"student\") @Validated Student student, \n BindingResult bindingResult, Model model) {\n\n if (bindingResult.hasErrors()) {\n return \"addStudent\";\n }\n model.addAttribute(\"name\", student.getName());\n model.addAttribute(\"age\", student.getAge());\n model.addAttribute(\"id\", student.getId());\n\n return \"result\";\n }\n}\n"
},
{
"code": null,
"e": 6670,
"s": 5846,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:component-scan base-package = \"com.tutorialspoint\" />\n\n <bean class = \"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name = \"prefix\" value = \"/WEB-INF/jsp/\" />\n <property name = \"suffix\" value = \".jsp\" />\n </bean>\n \n <bean id = \"studentValidator\" class = \"com.tutorialspoint.StudentValidator\" />\n</beans>"
},
{
"code": null,
"e": 6990,
"s": 6670,
"text": "Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name \"command\", because the spring framework expects an object with name \"command\", if you are using <form:form> tags in your JSP file. So, when student() method is called, it returns addStudent.jsp view."
},
{
"code": null,
"e": 7447,
"s": 6990,
"text": "The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a \"result\" view will be returned from the service method, which will result in rendering the result.jsp. In case there are errors generated using validator then same view \"addStudent\" is returned, Spring automatically injects error messages from BindingResult in view."
},
{
"code": null,
"e": 8804,
"s": 7447,
"text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring MVC Form Handling</title>\n </head>\n <style>\n .error {\n color: #ff0000;\n }\n\n .errorblock {\n color: #000;\n background-color: #ffEEEE;\n border: 3px solid #ff0000;\n padding: 8px;\n margin: 16px;\n }\n </style>\n \n <body>\n <h2>Student Information</h2>\n <form:form method = \"POST\" action = \"/HelloWeb/addStudent\" commandName = \"student\">\n <form:errors path = \"*\" cssClass = \"errorblock\" element = \"div\" />\n <table>\n <tr>\n <td><form:label path = \"name\">Name</form:label></td>\n <td><form:input path = \"name\" /></td>\n <td><form:errors path = \"name\" cssClass = \"error\" /></td>\n </tr>\n <tr>\n <td><form:label path = \"age\">Age</form:label></td>\n <td><form:input path = \"age\" /></td>\n </tr>\n <tr>\n <td><form:label path = \"id\">id</form:label></td>\n <td><form:input path = \"id\" /></td>\n </tr>\n <tr>\n <td colspan = \"2\">\n <input type = \"submit\" value = \"Submit\"/>\n </td>\n </tr>\n </table> \n </form:form>\n </body>\n</html>"
},
{
"code": null,
"e": 8894,
"s": 8804,
"text": "Here we are using <form:errors /> tag with path=\"*\" to render error messages. For example"
},
{
"code": null,
"e": 8961,
"s": 8894,
"text": "<form:errors path = \"*\" cssClass = \"errorblock\" element = \"div\" />"
},
{
"code": null,
"e": 9022,
"s": 8961,
"text": "It will render the error messages for all input validations."
},
{
"code": null,
"e": 9124,
"s": 9022,
"text": "We are using <form:errors /> tag with path=\"name\" to render error message for name field. For example"
},
{
"code": null,
"e": 9173,
"s": 9124,
"text": "<form:errors path = \"name\" cssClass = \"error\" />"
},
{
"code": null,
"e": 9235,
"s": 9173,
"text": "It will render error messages for the name field validations."
},
{
"code": null,
"e": 9736,
"s": 9235,
"text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring MVC Form Handling</title>\n </head>\n <body>\n\n <h2>Submitted Student Information</h2>\n <table>\n <tr>\n <td>Name</td>\n <td>${name}</td>\n </tr>\n <tr>\n <td>Age</td>\n <td>${age}</td>\n </tr>\n <tr>\n <td>ID</td>\n <td>${id}</td>\n </tr>\n </table> \n </body>\n</html>"
},
{
"code": null,
"e": 9946,
"s": 9736,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 10221,
"s": 9946,
"text": "Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL − http://localhost:8080/HelloWeb/addStudent and we will see the following screen, if everything is fine with the Spring Web Application."
},
{
"code": null,
"e": 10403,
"s": 10221,
"text": "After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application."
},
{
"code": null,
"e": 10410,
"s": 10403,
"text": " Print"
},
{
"code": null,
"e": 10421,
"s": 10410,
"text": " Add Notes"
}
] |
Python Pandas - Fill NaN values using an interpolation method | Use the interpolate() method to fill NaN values. Let’s say the following is our CSV file opened in Microsoft Excel with some NaN values −
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
Fill NaN values with interpolate() −
dataFrame.interpolate()
Following is the code −
import pandas as pd
# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
print("DataFrame...\n",dataFrame)
# fill NaN values with interpolate()
res = dataFrame.interpolate()
print("\nDataFrame after interpolation...\n",res)
This will produce the following output −
DataFrame...
Car Reg_Price Units
0 BMW 2500 100.0
1 Lexus 3500 NaN
2 Audi 2500 120.0
3 Jaguar 2000 NaN
4 Mustang 2500 110.0
DataFrame after interpolation...
Car Reg_Price Units
0 BMW 2500 100.0
1 Lexus 3500 110.0
2 Audi 2500 120.0
3 Jaguar 2000 115.0
4 Mustang 2500 110.0 | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "Use the interpolate() method to fill NaN values. Let’s say the following is our CSV file opened in Microsoft Excel with some NaN values −"
},
{
"code": null,
"e": 1252,
"s": 1200,
"text": "Load data from a CSV file into a Pandas DataFrame −"
},
{
"code": null,
"e": 1320,
"s": 1252,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\SalesData.csv\")"
},
{
"code": null,
"e": 1357,
"s": 1320,
"text": "Fill NaN values with interpolate() −"
},
{
"code": null,
"e": 1381,
"s": 1357,
"text": "dataFrame.interpolate()"
},
{
"code": null,
"e": 1405,
"s": 1381,
"text": "Following is the code −"
},
{
"code": null,
"e": 1700,
"s": 1405,
"text": "import pandas as pd\n\n# Load data from a CSV file into a Pandas DataFrame\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\SalesData.csv\")\nprint(\"DataFrame...\\n\",dataFrame)\n\n# fill NaN values with interpolate()\nres = dataFrame.interpolate()\nprint(\"\\nDataFrame after interpolation...\\n\",res)\n\n"
},
{
"code": null,
"e": 1741,
"s": 1700,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2160,
"s": 1741,
"text": "DataFrame...\n Car Reg_Price Units\n0 BMW 2500 100.0\n1 Lexus 3500 NaN\n2 Audi 2500 120.0\n3 Jaguar 2000 NaN\n4 Mustang 2500 110.0\n\nDataFrame after interpolation...\n Car Reg_Price Units\n0 BMW 2500 100.0\n1 Lexus 3500 110.0\n2 Audi 2500 120.0\n3 Jaguar 2000 115.0\n4 Mustang 2500 110.0"
}
] |
java.time.LocalDate.compareTo() Method Example | The java.time.LocalDate.compareTo(ChronoLocalDate other) method compares this date to another date.
Following is the declaration for java.time.LocalDate.compareTo(ChronoLocalDate other) method.
public int compareTo(ChronoLocalDate other)
other − the other date to compare to, not null.
the comparator value, negative if less, positive if greater.
The following example shows the usage of java.time.LocalDate.compareTo(ChronoLocalDate other) method.
package com.tutorialspoint;
import java.time.LocalDate;
public class LocalDateDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2017-02-03");
System.out.println(date);
LocalDate date1 = LocalDate.parse("2017-03-03");
System.out.println(date1);
System.out.println(date1.compareTo(date));
}
}
Let us compile and run the above program, this will produce the following result −
2017-02-03
2017-03-03
1
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2015,
"s": 1915,
"text": "The java.time.LocalDate.compareTo(ChronoLocalDate other) method compares this date to another date."
},
{
"code": null,
"e": 2109,
"s": 2015,
"text": "Following is the declaration for java.time.LocalDate.compareTo(ChronoLocalDate other) method."
},
{
"code": null,
"e": 2154,
"s": 2109,
"text": "public int compareTo(ChronoLocalDate other)\n"
},
{
"code": null,
"e": 2202,
"s": 2154,
"text": "other − the other date to compare to, not null."
},
{
"code": null,
"e": 2263,
"s": 2202,
"text": "the comparator value, negative if less, positive if greater."
},
{
"code": null,
"e": 2365,
"s": 2263,
"text": "The following example shows the usage of java.time.LocalDate.compareTo(ChronoLocalDate other) method."
},
{
"code": null,
"e": 2733,
"s": 2365,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalDate;\n\npublic class LocalDateDemo {\n public static void main(String[] args) {\n\n LocalDate date = LocalDate.parse(\"2017-02-03\");\n System.out.println(date); \n LocalDate date1 = LocalDate.parse(\"2017-03-03\");\n System.out.println(date1); \n System.out.println(date1.compareTo(date)); \n }\n}"
},
{
"code": null,
"e": 2816,
"s": 2733,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2841,
"s": 2816,
"text": "2017-02-03\n2017-03-03\n1\n"
},
{
"code": null,
"e": 2848,
"s": 2841,
"text": " Print"
},
{
"code": null,
"e": 2859,
"s": 2848,
"text": " Add Notes"
}
] |
Predicting Titanic Survivors Using Data Science and Machine Learning | Towards Data Science | The purpose of this challenge is to predict the survivals and deaths of the Titanic disaster at the beginning of the 20th century. We will use two machine learning algorithms for this task, K-nearest neighbours classifier (KNN) and Decision Tree classifier. We will perform basic data clean and feature engineering and compare the results of these two algorithms.
You will practice two classification algorithms here, KNN and Decision Tree. You will learn how to prepare the data to achieve the best results by cleaning the data and advanced feature engineering.
We have two data sets. One for training (train.csv) containing survival and death information that we will use to train our model. One for testing (test.csv), without survival and death information, that we will use to test our models.
If you don’t have your computer set up for data science read my article How to set up your computer for Data Science.
Create a project folder
Create a folder for a project on your computer called “Titanic-Challenge”.
Download train.cs and test.csv data sets from Kaggle
https://www.kaggle.com/c/titanic/data
Place these data sets in a folder called “data” in your project folder.
Start a new notebook
Enter this folder and start Jupyter Notebook by typing a command in the Terminal/Command Prompt:
$ cd “Titanic-Challenge”
then
$ jupyter notebook
Click new in the top right corner and select Python 3.
This will open a new Jupyter Notebook in your browser. Rename the Untitled project name to your project name and you are ready to start.
If you have Anaconda installed on your computer you will already have all libraries needed for this project installed on your computer.
If you are using Google Colab, open a new notebook.
First thing we usually do in a new notebook is adding different libraries we will need to use when working on the project.
Now we need to load the data sets from the files we downloaded into variables as Pandas Data Frames.
It is always a good practice to look at the data.
Let’s look at the train and test data. The only difference between them is the Survived column which indicates if the passenger survived the disaster or not.
Below is also an explanation of each field in the data set.
PassengerId: unique ID of the passenger
Survived: 0 = No, 1 = Yes
Pclass: passenger class 1 = 1st, 2 = 2nd, 3 = 3rd
Name: name of the passenger
Sex: passenger’s sex
Age: passenger’s age
SibSp: number of siblings or spouses on the ship
Parch: number of parents or children on the ship
Ticket: Ticket ID
Fare: the amount paid for the ticket
Cabin: cabin number
Embarked: Port of embarkation (C = Cherbourg, Q = Queenstown, S = Southampton)
Let’s now look at the dimensionality of the train Data Frame.
# Output(891, 12)
We can see that the train data set has 891 records and 12 columns.
Let’s do the same for the test data set.
# Output(418, 11)
The only difference with the test data set is the number of records which is 418 and the number of columns which is 11. We are missing the Survived column in the test data set. We will be predicting the Survived column with the machine learning model we are going to build.
# OutputThere are 1309 passengers in both data sets.891 in train data set.418 in train data set.
What we can also see already is that we some missing data (NaN values) in our data sets. For our classification model to work effectively we will have to do something with the missing data. We will check this in details and deal with it a little bit later but for now let’s just look at the Pandas info() function so we can get an idea about the missing values.
# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 891 entries, 0 to 890Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 891 non-null int64 1 Survived 891 non-null int64 2 Pclass 891 non-null int64 3 Name 891 non-null object 4 Sex 891 non-null object 5 Age 714 non-null float64 6 SibSp 891 non-null int64 7 Parch 891 non-null int64 8 Ticket 891 non-null object 9 Fare 891 non-null float64 10 Cabin 204 non-null object 11 Embarked 889 non-null object dtypes: float64(2), int64(5), object(5)memory usage: 83.7+ KB
We can see that in the training data Age, Cabin and Embarked has some missing values.
# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 418 entries, 0 to 417Data columns (total 11 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 418 non-null int64 1 Pclass 418 non-null int64 2 Name 418 non-null object 3 Sex 418 non-null object 4 Age 332 non-null float64 5 SibSp 418 non-null int64 6 Parch 418 non-null int64 7 Ticket 418 non-null object 8 Fare 417 non-null float64 9 Cabin 91 non-null object 10 Embarked 418 non-null object dtypes: float64(2), int64(4), object(5)memory usage: 36.0+ KB
We have a similar situation in the test data set.
We can also check for null values using isnull() function.
# OutputPassengerId 0Survived 0Pclass 0Name 0Sex 0Age 177SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64
# OutputPassengerId 0Pclass 0Name 0Sex 0Age 86SibSp 0Parch 0Ticket 0Fare 1Cabin 327Embarked 0dtype: int64
Which confirms our earlier findings.
Now let’s look at it in a little bit more detail just to get an idea what is in it.
A good way to do it is to draw some charts from the data.
In our project we will use Matplotlib library to display charts.
We are primarily interested in characteristics of passengers who survived or not.
We will now create a function that will display whether the passangers survived or not the Titanic disaster, against a specified feature.
We will be using only train data set for that because only in this data set we have survival information.
And now let’s build the charts for selected features.
We can see that significantly more females survived than males. We have even more significant results for passengers that did not survive where females make a very small percentage in comparison to males.
Now let’s look at the passenger class.
We can see here that passengers from the 3rd class were more likely to die than passengers from the fist class, which had higher chances to survive.
These and other relationships between the features and the survival rate are very important to us and to our machine learning model.
Once we have loaded our data sets and have a good understanding of the data we are working with, we will perform some feature engineering.
Feature engineering is the process of extracting features from the existing features in the data set in order to improve the performance of the machine learning model.
Usually, that means not only creating new features but also replacing missing values and removing features that do not contribute to the performance of the model.
Let’s have a look again at the missing values in our train data set.
# OutputPassengerId 0Survived 0Pclass 0Name 0Sex 0Age 177SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64
We have many missing values in the Age column. We will fill all the missing values in the Age column with the median values for that column. Median value is “the middle” value for the columns. To make the values more accurate we will calculate the median value for each sex separately. We will also perform this for both train and test data set.
We can see that all NaN values were replaced with the number.
# OutputPassengerId 0Survived 0Pclass 0Name 0Sex 0Age 0SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64
And we no longer have null values in the train data set.
What we are also going to do here with age is that we can use a technique called data binning and put people of different age into different bins (groups). This usually improves the performance of machine learning models.
We are going to put the passengers in four age groups:
1: (age <= 18)
2: (age > 18 and <= 40)
3: (age > 40 and <= 60)
4: (age > 60)
We will perform this for train and test data.
Because machine learning models operate only on numeric values we need to replace test values for the column Sex with numbers to create numeric categories. These will be our categories:
0: male
1: female
One other thing that would be useful to do is to extract Title information like (Mr. Mrs. Miss.) from the Name column and create bins (groups) similar to what we have done with the Age column and after that drop the Name column.
Let’s display the created values.
# OutputMr 517Miss 182Mrs 125Master 40Dr 7Rev 6Col 2Major 2Mlle 2Sir 1Mme 1Ms 1Countess 1Capt 1Don 1Jonkheer 1Lady 1Name: Title, dtype: int64
# OutputMr 240Miss 78Mrs 72Master 21Col 2Rev 2Dr 1Ms 1Dona 1Name: Title, dtype: int64
As we can see we only really have 3 major groups here, Mr, Miss and Mrs. We will create four bins (grups) here with these groups and put everything else into the Other category. Our groups are going to look like this:
1: Mr
2: Miss
3: Mrs
4: everything else
Now let’s look at the graph of the Title data.
As we can see people with the Title Mr. has significantly less change to survive which should be a useful information for our machine learning model.
Now, let’s remove the features we don’t think we need to train the model. In our example it will be Name, Ticket, Fare, Cabin, Embarked. We could still probably extract some additional features from those but for now we decide to remove them and train our model without them.
Now we need to prepare our train data and target information with survivals to train our Machine Learning Models. In order to do this we need to create another data set without the Survived column and create a target variable only with survival information. This is how Machine Learning models typically require the data for training — input (or X or independent variable) and output (or Y or dependent variable).
Now we are ready to build and train our machine learning models.
We will use two different algorithms and compare the results to see which one performs better.
We are going to use K-nearest neighbors (KNN) classifier and Decision Tree classifier from Scikit-learn library.
We will create KNN model with 13 neighbors (n_neighbors = 13) and cross-validation technique to train our model by shuffling the data and splitting it into k-folds. Cross-validation technique helps to prevent unintentional ordering errors when training Machine Learning Models.
We will end up with several Machine Learning scores that we will need to average to achieve the final result of the model performance.
# Output[0.82222222 0.76404494 0.82022472 0.79775281 0.80898876 0.83146067 0.82022472 0.79775281 0.82022472 0.84269663]
# OutputOur KNN classifier score is 81.26%
We will do the same with the Decision Tree model and use cross-validation technique.
# Output[0.8 0.79775281 0.78651685 0.78651685 0.86516854 0.78651685 0.84269663 0.80898876 0.78651685 0.84269663]
Our Decision Tree classifier score is 81.03%
As we can see both our models achieved similar results and we have achieved quite good accuracy result of around 80% for both models which is good.
This result can be probably still improved by performing some more feature engineering with Fare, Cabin and Embarked columns which I encourage your to do.
Now we can run our model on the test data to predict the values.
# Outputarray([0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, [...], 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1])
We can now save the results to the file.
If you want you can upload your results here (https://www.kaggle.com/c/titanic) and take part in the Kaggle Titanic competition.
To read and display your results you can use the following code.
If you would like to learn more and experiment with Python and Data Science you can look at another of my articles Analysing Pharmaceutical Sales Data in Python, Introduction to Computer Vision with MNIST or Image Face Recognition in Python.
To consolidate your knowledge consider completing the task again from the beginning without looking at the code examples and see what results you will get. This is an excellent thing to do to solidify your knowledge.
Full Python code in Jupyter Notebook is available on GitHub:https://github.com/pjonline/Basic-Data-Science-Projects/tree/master/5-Titanic-Challenge
Happy coding!
Not subscribing to Medium yet? Consider signing up to become a Medium member. It’s only $5 a month and it will give you unlimited access to all stories on Medium. Subscribing to Medium supports me and other writers on Medium. | [
{
"code": null,
"e": 535,
"s": 171,
"text": "The purpose of this challenge is to predict the survivals and deaths of the Titanic disaster at the beginning of the 20th century. We will use two machine learning algorithms for this task, K-nearest neighbours classifier (KNN) and Decision Tree classifier. We will perform basic data clean and feature engineering and compare the results of these two algorithms."
},
{
"code": null,
"e": 734,
"s": 535,
"text": "You will practice two classification algorithms here, KNN and Decision Tree. You will learn how to prepare the data to achieve the best results by cleaning the data and advanced feature engineering."
},
{
"code": null,
"e": 970,
"s": 734,
"text": "We have two data sets. One for training (train.csv) containing survival and death information that we will use to train our model. One for testing (test.csv), without survival and death information, that we will use to test our models."
},
{
"code": null,
"e": 1088,
"s": 970,
"text": "If you don’t have your computer set up for data science read my article How to set up your computer for Data Science."
},
{
"code": null,
"e": 1112,
"s": 1088,
"text": "Create a project folder"
},
{
"code": null,
"e": 1187,
"s": 1112,
"text": "Create a folder for a project on your computer called “Titanic-Challenge”."
},
{
"code": null,
"e": 1240,
"s": 1187,
"text": "Download train.cs and test.csv data sets from Kaggle"
},
{
"code": null,
"e": 1278,
"s": 1240,
"text": "https://www.kaggle.com/c/titanic/data"
},
{
"code": null,
"e": 1350,
"s": 1278,
"text": "Place these data sets in a folder called “data” in your project folder."
},
{
"code": null,
"e": 1371,
"s": 1350,
"text": "Start a new notebook"
},
{
"code": null,
"e": 1468,
"s": 1371,
"text": "Enter this folder and start Jupyter Notebook by typing a command in the Terminal/Command Prompt:"
},
{
"code": null,
"e": 1493,
"s": 1468,
"text": "$ cd “Titanic-Challenge”"
},
{
"code": null,
"e": 1498,
"s": 1493,
"text": "then"
},
{
"code": null,
"e": 1517,
"s": 1498,
"text": "$ jupyter notebook"
},
{
"code": null,
"e": 1572,
"s": 1517,
"text": "Click new in the top right corner and select Python 3."
},
{
"code": null,
"e": 1709,
"s": 1572,
"text": "This will open a new Jupyter Notebook in your browser. Rename the Untitled project name to your project name and you are ready to start."
},
{
"code": null,
"e": 1845,
"s": 1709,
"text": "If you have Anaconda installed on your computer you will already have all libraries needed for this project installed on your computer."
},
{
"code": null,
"e": 1897,
"s": 1845,
"text": "If you are using Google Colab, open a new notebook."
},
{
"code": null,
"e": 2020,
"s": 1897,
"text": "First thing we usually do in a new notebook is adding different libraries we will need to use when working on the project."
},
{
"code": null,
"e": 2121,
"s": 2020,
"text": "Now we need to load the data sets from the files we downloaded into variables as Pandas Data Frames."
},
{
"code": null,
"e": 2171,
"s": 2121,
"text": "It is always a good practice to look at the data."
},
{
"code": null,
"e": 2329,
"s": 2171,
"text": "Let’s look at the train and test data. The only difference between them is the Survived column which indicates if the passenger survived the disaster or not."
},
{
"code": null,
"e": 2389,
"s": 2329,
"text": "Below is also an explanation of each field in the data set."
},
{
"code": null,
"e": 2429,
"s": 2389,
"text": "PassengerId: unique ID of the passenger"
},
{
"code": null,
"e": 2455,
"s": 2429,
"text": "Survived: 0 = No, 1 = Yes"
},
{
"code": null,
"e": 2505,
"s": 2455,
"text": "Pclass: passenger class 1 = 1st, 2 = 2nd, 3 = 3rd"
},
{
"code": null,
"e": 2533,
"s": 2505,
"text": "Name: name of the passenger"
},
{
"code": null,
"e": 2554,
"s": 2533,
"text": "Sex: passenger’s sex"
},
{
"code": null,
"e": 2575,
"s": 2554,
"text": "Age: passenger’s age"
},
{
"code": null,
"e": 2624,
"s": 2575,
"text": "SibSp: number of siblings or spouses on the ship"
},
{
"code": null,
"e": 2673,
"s": 2624,
"text": "Parch: number of parents or children on the ship"
},
{
"code": null,
"e": 2691,
"s": 2673,
"text": "Ticket: Ticket ID"
},
{
"code": null,
"e": 2728,
"s": 2691,
"text": "Fare: the amount paid for the ticket"
},
{
"code": null,
"e": 2748,
"s": 2728,
"text": "Cabin: cabin number"
},
{
"code": null,
"e": 2827,
"s": 2748,
"text": "Embarked: Port of embarkation (C = Cherbourg, Q = Queenstown, S = Southampton)"
},
{
"code": null,
"e": 2889,
"s": 2827,
"text": "Let’s now look at the dimensionality of the train Data Frame."
},
{
"code": null,
"e": 2907,
"s": 2889,
"text": "# Output(891, 12)"
},
{
"code": null,
"e": 2974,
"s": 2907,
"text": "We can see that the train data set has 891 records and 12 columns."
},
{
"code": null,
"e": 3015,
"s": 2974,
"text": "Let’s do the same for the test data set."
},
{
"code": null,
"e": 3033,
"s": 3015,
"text": "# Output(418, 11)"
},
{
"code": null,
"e": 3307,
"s": 3033,
"text": "The only difference with the test data set is the number of records which is 418 and the number of columns which is 11. We are missing the Survived column in the test data set. We will be predicting the Survived column with the machine learning model we are going to build."
},
{
"code": null,
"e": 3404,
"s": 3307,
"text": "# OutputThere are 1309 passengers in both data sets.891 in train data set.418 in train data set."
},
{
"code": null,
"e": 3766,
"s": 3404,
"text": "What we can also see already is that we some missing data (NaN values) in our data sets. For our classification model to work effectively we will have to do something with the missing data. We will check this in details and deal with it a little bit later but for now let’s just look at the Pandas info() function so we can get an idea about the missing values."
},
{
"code": null,
"e": 4512,
"s": 3766,
"text": "# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 891 entries, 0 to 890Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 891 non-null int64 1 Survived 891 non-null int64 2 Pclass 891 non-null int64 3 Name 891 non-null object 4 Sex 891 non-null object 5 Age 714 non-null float64 6 SibSp 891 non-null int64 7 Parch 891 non-null int64 8 Ticket 891 non-null object 9 Fare 891 non-null float64 10 Cabin 204 non-null object 11 Embarked 889 non-null object dtypes: float64(2), int64(5), object(5)memory usage: 83.7+ KB"
},
{
"code": null,
"e": 4598,
"s": 4512,
"text": "We can see that in the training data Age, Cabin and Embarked has some missing values."
},
{
"code": null,
"e": 5303,
"s": 4598,
"text": "# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 418 entries, 0 to 417Data columns (total 11 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 418 non-null int64 1 Pclass 418 non-null int64 2 Name 418 non-null object 3 Sex 418 non-null object 4 Age 332 non-null float64 5 SibSp 418 non-null int64 6 Parch 418 non-null int64 7 Ticket 418 non-null object 8 Fare 417 non-null float64 9 Cabin 91 non-null object 10 Embarked 418 non-null object dtypes: float64(2), int64(4), object(5)memory usage: 36.0+ KB"
},
{
"code": null,
"e": 5353,
"s": 5303,
"text": "We have a similar situation in the test data set."
},
{
"code": null,
"e": 5412,
"s": 5353,
"text": "We can also check for null values using isnull() function."
},
{
"code": null,
"e": 5649,
"s": 5412,
"text": "# OutputPassengerId 0Survived 0Pclass 0Name 0Sex 0Age 177SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64"
},
{
"code": null,
"e": 5868,
"s": 5649,
"text": "# OutputPassengerId 0Pclass 0Name 0Sex 0Age 86SibSp 0Parch 0Ticket 0Fare 1Cabin 327Embarked 0dtype: int64"
},
{
"code": null,
"e": 5905,
"s": 5868,
"text": "Which confirms our earlier findings."
},
{
"code": null,
"e": 5989,
"s": 5905,
"text": "Now let’s look at it in a little bit more detail just to get an idea what is in it."
},
{
"code": null,
"e": 6047,
"s": 5989,
"text": "A good way to do it is to draw some charts from the data."
},
{
"code": null,
"e": 6112,
"s": 6047,
"text": "In our project we will use Matplotlib library to display charts."
},
{
"code": null,
"e": 6194,
"s": 6112,
"text": "We are primarily interested in characteristics of passengers who survived or not."
},
{
"code": null,
"e": 6332,
"s": 6194,
"text": "We will now create a function that will display whether the passangers survived or not the Titanic disaster, against a specified feature."
},
{
"code": null,
"e": 6438,
"s": 6332,
"text": "We will be using only train data set for that because only in this data set we have survival information."
},
{
"code": null,
"e": 6492,
"s": 6438,
"text": "And now let’s build the charts for selected features."
},
{
"code": null,
"e": 6697,
"s": 6492,
"text": "We can see that significantly more females survived than males. We have even more significant results for passengers that did not survive where females make a very small percentage in comparison to males."
},
{
"code": null,
"e": 6736,
"s": 6697,
"text": "Now let’s look at the passenger class."
},
{
"code": null,
"e": 6885,
"s": 6736,
"text": "We can see here that passengers from the 3rd class were more likely to die than passengers from the fist class, which had higher chances to survive."
},
{
"code": null,
"e": 7018,
"s": 6885,
"text": "These and other relationships between the features and the survival rate are very important to us and to our machine learning model."
},
{
"code": null,
"e": 7157,
"s": 7018,
"text": "Once we have loaded our data sets and have a good understanding of the data we are working with, we will perform some feature engineering."
},
{
"code": null,
"e": 7325,
"s": 7157,
"text": "Feature engineering is the process of extracting features from the existing features in the data set in order to improve the performance of the machine learning model."
},
{
"code": null,
"e": 7488,
"s": 7325,
"text": "Usually, that means not only creating new features but also replacing missing values and removing features that do not contribute to the performance of the model."
},
{
"code": null,
"e": 7557,
"s": 7488,
"text": "Let’s have a look again at the missing values in our train data set."
},
{
"code": null,
"e": 7794,
"s": 7557,
"text": "# OutputPassengerId 0Survived 0Pclass 0Name 0Sex 0Age 177SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64"
},
{
"code": null,
"e": 8140,
"s": 7794,
"text": "We have many missing values in the Age column. We will fill all the missing values in the Age column with the median values for that column. Median value is “the middle” value for the columns. To make the values more accurate we will calculate the median value for each sex separately. We will also perform this for both train and test data set."
},
{
"code": null,
"e": 8202,
"s": 8140,
"text": "We can see that all NaN values were replaced with the number."
},
{
"code": null,
"e": 8439,
"s": 8202,
"text": "# OutputPassengerId 0Survived 0Pclass 0Name 0Sex 0Age 0SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64"
},
{
"code": null,
"e": 8496,
"s": 8439,
"text": "And we no longer have null values in the train data set."
},
{
"code": null,
"e": 8718,
"s": 8496,
"text": "What we are also going to do here with age is that we can use a technique called data binning and put people of different age into different bins (groups). This usually improves the performance of machine learning models."
},
{
"code": null,
"e": 8773,
"s": 8718,
"text": "We are going to put the passengers in four age groups:"
},
{
"code": null,
"e": 8788,
"s": 8773,
"text": "1: (age <= 18)"
},
{
"code": null,
"e": 8812,
"s": 8788,
"text": "2: (age > 18 and <= 40)"
},
{
"code": null,
"e": 8836,
"s": 8812,
"text": "3: (age > 40 and <= 60)"
},
{
"code": null,
"e": 8850,
"s": 8836,
"text": "4: (age > 60)"
},
{
"code": null,
"e": 8896,
"s": 8850,
"text": "We will perform this for train and test data."
},
{
"code": null,
"e": 9082,
"s": 8896,
"text": "Because machine learning models operate only on numeric values we need to replace test values for the column Sex with numbers to create numeric categories. These will be our categories:"
},
{
"code": null,
"e": 9090,
"s": 9082,
"text": "0: male"
},
{
"code": null,
"e": 9100,
"s": 9090,
"text": "1: female"
},
{
"code": null,
"e": 9329,
"s": 9100,
"text": "One other thing that would be useful to do is to extract Title information like (Mr. Mrs. Miss.) from the Name column and create bins (groups) similar to what we have done with the Age column and after that drop the Name column."
},
{
"code": null,
"e": 9363,
"s": 9329,
"text": "Let’s display the created values."
},
{
"code": null,
"e": 9652,
"s": 9363,
"text": "# OutputMr 517Miss 182Mrs 125Master 40Dr 7Rev 6Col 2Major 2Mlle 2Sir 1Mme 1Ms 1Countess 1Capt 1Don 1Jonkheer 1Lady 1Name: Title, dtype: int64"
},
{
"code": null,
"e": 9803,
"s": 9652,
"text": "# OutputMr 240Miss 78Mrs 72Master 21Col 2Rev 2Dr 1Ms 1Dona 1Name: Title, dtype: int64"
},
{
"code": null,
"e": 10021,
"s": 9803,
"text": "As we can see we only really have 3 major groups here, Mr, Miss and Mrs. We will create four bins (grups) here with these groups and put everything else into the Other category. Our groups are going to look like this:"
},
{
"code": null,
"e": 10027,
"s": 10021,
"text": "1: Mr"
},
{
"code": null,
"e": 10035,
"s": 10027,
"text": "2: Miss"
},
{
"code": null,
"e": 10042,
"s": 10035,
"text": "3: Mrs"
},
{
"code": null,
"e": 10061,
"s": 10042,
"text": "4: everything else"
},
{
"code": null,
"e": 10108,
"s": 10061,
"text": "Now let’s look at the graph of the Title data."
},
{
"code": null,
"e": 10258,
"s": 10108,
"text": "As we can see people with the Title Mr. has significantly less change to survive which should be a useful information for our machine learning model."
},
{
"code": null,
"e": 10534,
"s": 10258,
"text": "Now, let’s remove the features we don’t think we need to train the model. In our example it will be Name, Ticket, Fare, Cabin, Embarked. We could still probably extract some additional features from those but for now we decide to remove them and train our model without them."
},
{
"code": null,
"e": 10948,
"s": 10534,
"text": "Now we need to prepare our train data and target information with survivals to train our Machine Learning Models. In order to do this we need to create another data set without the Survived column and create a target variable only with survival information. This is how Machine Learning models typically require the data for training — input (or X or independent variable) and output (or Y or dependent variable)."
},
{
"code": null,
"e": 11013,
"s": 10948,
"text": "Now we are ready to build and train our machine learning models."
},
{
"code": null,
"e": 11108,
"s": 11013,
"text": "We will use two different algorithms and compare the results to see which one performs better."
},
{
"code": null,
"e": 11221,
"s": 11108,
"text": "We are going to use K-nearest neighbors (KNN) classifier and Decision Tree classifier from Scikit-learn library."
},
{
"code": null,
"e": 11499,
"s": 11221,
"text": "We will create KNN model with 13 neighbors (n_neighbors = 13) and cross-validation technique to train our model by shuffling the data and splitting it into k-folds. Cross-validation technique helps to prevent unintentional ordering errors when training Machine Learning Models."
},
{
"code": null,
"e": 11634,
"s": 11499,
"text": "We will end up with several Machine Learning scores that we will need to average to achieve the final result of the model performance."
},
{
"code": null,
"e": 11754,
"s": 11634,
"text": "# Output[0.82222222 0.76404494 0.82022472 0.79775281 0.80898876 0.83146067 0.82022472 0.79775281 0.82022472 0.84269663]"
},
{
"code": null,
"e": 11797,
"s": 11754,
"text": "# OutputOur KNN classifier score is 81.26%"
},
{
"code": null,
"e": 11882,
"s": 11797,
"text": "We will do the same with the Decision Tree model and use cross-validation technique."
},
{
"code": null,
"e": 12002,
"s": 11882,
"text": "# Output[0.8 0.79775281 0.78651685 0.78651685 0.86516854 0.78651685 0.84269663 0.80898876 0.78651685 0.84269663]"
},
{
"code": null,
"e": 12047,
"s": 12002,
"text": "Our Decision Tree classifier score is 81.03%"
},
{
"code": null,
"e": 12195,
"s": 12047,
"text": "As we can see both our models achieved similar results and we have achieved quite good accuracy result of around 80% for both models which is good."
},
{
"code": null,
"e": 12350,
"s": 12195,
"text": "This result can be probably still improved by performing some more feature engineering with Fare, Cabin and Embarked columns which I encourage your to do."
},
{
"code": null,
"e": 12415,
"s": 12350,
"text": "Now we can run our model on the test data to predict the values."
},
{
"code": null,
"e": 12564,
"s": 12415,
"text": "# Outputarray([0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, [...], 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1])"
},
{
"code": null,
"e": 12605,
"s": 12564,
"text": "We can now save the results to the file."
},
{
"code": null,
"e": 12734,
"s": 12605,
"text": "If you want you can upload your results here (https://www.kaggle.com/c/titanic) and take part in the Kaggle Titanic competition."
},
{
"code": null,
"e": 12799,
"s": 12734,
"text": "To read and display your results you can use the following code."
},
{
"code": null,
"e": 13041,
"s": 12799,
"text": "If you would like to learn more and experiment with Python and Data Science you can look at another of my articles Analysing Pharmaceutical Sales Data in Python, Introduction to Computer Vision with MNIST or Image Face Recognition in Python."
},
{
"code": null,
"e": 13258,
"s": 13041,
"text": "To consolidate your knowledge consider completing the task again from the beginning without looking at the code examples and see what results you will get. This is an excellent thing to do to solidify your knowledge."
},
{
"code": null,
"e": 13406,
"s": 13258,
"text": "Full Python code in Jupyter Notebook is available on GitHub:https://github.com/pjonline/Basic-Data-Science-Projects/tree/master/5-Titanic-Challenge"
},
{
"code": null,
"e": 13420,
"s": 13406,
"text": "Happy coding!"
}
] |
How to fully change the color of a Tkinter Listbox? | Tkinter Listbox widgets are very useful in the case of representing a large set of data items in form of list items. To configure the properties such as change the background color of the entire Listbox, we can use configure(**options) method to change the properties of the Listbox widget.
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
# Add a Listbox widget with number as the list items
listbox =Listbox(win)
listbox.insert(END,"C++", "Java", "Python", "Rust", "GoLang", "Ruby", "JavScript", "C# ", "SQL", "Dart")
listbox.pack(side=LEFT, fill=BOTH)
listbox.configure(background="skyblue4", foreground="white", font=('Aerial 13'))
win.mainloop()
Running the above code will display a customized Listbox with some list items in it. | [
{
"code": null,
"e": 1353,
"s": 1062,
"text": "Tkinter Listbox widgets are very useful in the case of representing a large set of data items in form of list items. To configure the properties such as change the background color of the entire Listbox, we can use configure(**options) method to change the properties of the Listbox widget."
},
{
"code": null,
"e": 1833,
"s": 1353,
"text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Add a Listbox widget with number as the list items\nlistbox =Listbox(win)\nlistbox.insert(END,\"C++\", \"Java\", \"Python\", \"Rust\", \"GoLang\", \"Ruby\", \"JavScript\", \"C# \", \"SQL\", \"Dart\")\nlistbox.pack(side=LEFT, fill=BOTH)\n\nlistbox.configure(background=\"skyblue4\", foreground=\"white\", font=('Aerial 13'))\n\nwin.mainloop()"
},
{
"code": null,
"e": 1918,
"s": 1833,
"text": "Running the above code will display a customized Listbox with some list items in it."
}
] |
How to use a global variable in a Python function? | The terms, global and local correspond to a variable's reach within a script or program. A global variable is one that can be accessed anywhere. A local variable can be accessed only within its frame. A local variable cannot be accessed globally.
Global variables are the one that are defined and declared outside a function and can be used anywhere.
If a variable with same name is defined inside the scope of a function then it will print the value given inside the function only and not the global value.
The given code is re-written to show how the global variable is accessed both inside and outside the function foo.
# This function uses global variable k
k = "I like green tea"
def foo():
print k #accessing global variable inside function
foo()
print k #accessing global variable outside function
C:/Users/TutorialsPoint1/~.py
I like green tea
I like green tea | [
{
"code": null,
"e": 1309,
"s": 1062,
"text": "The terms, global and local correspond to a variable's reach within a script or program. A global variable is one that can be accessed anywhere. A local variable can be accessed only within its frame. A local variable cannot be accessed globally."
},
{
"code": null,
"e": 1413,
"s": 1309,
"text": "Global variables are the one that are defined and declared outside a function and can be used anywhere."
},
{
"code": null,
"e": 1570,
"s": 1413,
"text": "If a variable with same name is defined inside the scope of a function then it will print the value given inside the function only and not the global value."
},
{
"code": null,
"e": 1685,
"s": 1570,
"text": "The given code is re-written to show how the global variable is accessed both inside and outside the function foo."
},
{
"code": null,
"e": 1873,
"s": 1685,
"text": "# This function uses global variable k\nk = \"I like green tea\"\ndef foo():\n print k #accessing global variable inside function\nfoo()\nprint k #accessing global variable outside function\n "
},
{
"code": null,
"e": 1937,
"s": 1873,
"text": "C:/Users/TutorialsPoint1/~.py\nI like green tea\nI like green tea"
}
] |
Limited-Memory Broyden-Fletcher-Goldfarb-Shanno Algorithm in ML.NET | by Robert Krzaczyński | Towards Data Science | Some time ago I published an article about the implementation of Naive Bayes using ML.NET. Continuing this series today I would like to introduce you to the Limited-Memory Broyden-Fletcher-Goldfarb-Shanno method. I will start with a theory and an explanation of what this method is about and what it is used for.
Some facts
The creator of the algorithm is Jorge Nocedal. It was created at the Optimization Center, a joint venture of Argonne National Laboratory and Northwestern University. The original source code was written in FORTRAN. It is referred to as software for large-scale unconstrained optimization. As you might expect from the name, this method is similar to BFGS, but it uses less memory. Therefore, it is perfect for large datasets.
L-BFGS
This is an algorithm from the Quasi-Newton family of methods. These are algorithms for finding local extrema of functions, which are based on Newton’s method of finding stationary points of functions.
Time for some math
In these methods, a second-degree approximation is used to find the minimum function f(x). Taylor series of function f(x) is as follows:
where delta f is a gradient of the function and H its hessian.
Taylor series of gradient looks like this:
We want to find the minimum, which is to solve the equation:
From here:
Now, Hessian should be appointed. Each method belonging to this family has a different way of appointing it. I think we can end this part. I don’t want to bore you with these formulas, but I wanted you to have a brief idea of what this is about.
The difference between BFGS and L-BFGS
As I mentioned earlier, the L-BFGS algorithm works well with large datasets because it needs less memory than the standard BFGS. Both algorithms use the Hessian inverse matrix estimation to control variable space searching. While BFGS stores a dense n x n approximation to the inverse Hessian, L-BFGS stores only a few vectors that represent the approximation implicitly. This is the difference that saves memory.
Dataset
I used the skin segmentation dataset from the UCI Machine Learning Repository for the experiment. The analyzed data set has 3 features and 2 classes. The classes determine if a sample is considered to be a skin or not. The dataset has 245057 instances, so the L-BFGS algorithm will work perfectly here.
Implementation
After creating a console application project and downloading ML.NET from NuGet Packages, you can proceed to implementation and model creation. In the beginning, you should create classes corresponding to the attributes of our dataset. Created classes are shown in the listing:
Then you can go on to load the dataset and divide it into a training and a testing set. I propose to adopt the popular division, i.e. 70% is a training set and 30% is a testing set.
var dataPath = "../../skin-segmentation.csv";var ml = new MLContext();var DataView = ml.Data.LoadFromTextFile<Features>(dataPath, hasHeader: true, separatorChar: ',');var partitions = ml.Data.TrainTestSplit(DataView, testFraction: 0.3);
Now you need to adapt the model structure to the standards proposed by the ML.NET library. This means that the property specifying the class must be called Label. The remaining attributes must be condensed under the name Features.
var pipeline = ml.Transforms.Conversion.MapValueToKey(inputColumnName: "Class", outputColumnName:"Label").Append(ml.Transforms.Concatenate("Features", "V1","V2","V3")).AppendCacheCheckpoint(ml);
Now is the time for creating a training pipeline. Here you choose a classifier in the form of L-BFGS, to which you specify in the parameters the column names of the label and features. You indicate the property that means the predicted label too.
var trainingPipeline = pipeline.Append(ml.MulticlassClassification.Trainers.LbfgsMaximumEntropy("Label","Features")).Append(ml.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
After completing the previous steps, you can now go to training and testing the model:
var trainedModel = trainingPipeline.Fit(partitions.TrainSet);var testMetrics = ml.MulticlassClassification.Evaluate(trainedModel.Transform(partitions.TestSet));
Results and summary
The accuracy of the L-BFGS algorithm was 91,8%. The result seems very good, but of course, deeper analysis and the use of other metrics are needed to confirm its value.In this article, I introduced you to the L-BFGS algorithm and showed you how to use it using ML.NET. Its use in ML.NET is limited to a few lines of code, but I think it’s worth having a view and knowledge of what this algorithm is about. | [
{
"code": null,
"e": 484,
"s": 171,
"text": "Some time ago I published an article about the implementation of Naive Bayes using ML.NET. Continuing this series today I would like to introduce you to the Limited-Memory Broyden-Fletcher-Goldfarb-Shanno method. I will start with a theory and an explanation of what this method is about and what it is used for."
},
{
"code": null,
"e": 495,
"s": 484,
"text": "Some facts"
},
{
"code": null,
"e": 921,
"s": 495,
"text": "The creator of the algorithm is Jorge Nocedal. It was created at the Optimization Center, a joint venture of Argonne National Laboratory and Northwestern University. The original source code was written in FORTRAN. It is referred to as software for large-scale unconstrained optimization. As you might expect from the name, this method is similar to BFGS, but it uses less memory. Therefore, it is perfect for large datasets."
},
{
"code": null,
"e": 928,
"s": 921,
"text": "L-BFGS"
},
{
"code": null,
"e": 1129,
"s": 928,
"text": "This is an algorithm from the Quasi-Newton family of methods. These are algorithms for finding local extrema of functions, which are based on Newton’s method of finding stationary points of functions."
},
{
"code": null,
"e": 1148,
"s": 1129,
"text": "Time for some math"
},
{
"code": null,
"e": 1285,
"s": 1148,
"text": "In these methods, a second-degree approximation is used to find the minimum function f(x). Taylor series of function f(x) is as follows:"
},
{
"code": null,
"e": 1348,
"s": 1285,
"text": "where delta f is a gradient of the function and H its hessian."
},
{
"code": null,
"e": 1391,
"s": 1348,
"text": "Taylor series of gradient looks like this:"
},
{
"code": null,
"e": 1452,
"s": 1391,
"text": "We want to find the minimum, which is to solve the equation:"
},
{
"code": null,
"e": 1463,
"s": 1452,
"text": "From here:"
},
{
"code": null,
"e": 1709,
"s": 1463,
"text": "Now, Hessian should be appointed. Each method belonging to this family has a different way of appointing it. I think we can end this part. I don’t want to bore you with these formulas, but I wanted you to have a brief idea of what this is about."
},
{
"code": null,
"e": 1748,
"s": 1709,
"text": "The difference between BFGS and L-BFGS"
},
{
"code": null,
"e": 2162,
"s": 1748,
"text": "As I mentioned earlier, the L-BFGS algorithm works well with large datasets because it needs less memory than the standard BFGS. Both algorithms use the Hessian inverse matrix estimation to control variable space searching. While BFGS stores a dense n x n approximation to the inverse Hessian, L-BFGS stores only a few vectors that represent the approximation implicitly. This is the difference that saves memory."
},
{
"code": null,
"e": 2170,
"s": 2162,
"text": "Dataset"
},
{
"code": null,
"e": 2473,
"s": 2170,
"text": "I used the skin segmentation dataset from the UCI Machine Learning Repository for the experiment. The analyzed data set has 3 features and 2 classes. The classes determine if a sample is considered to be a skin or not. The dataset has 245057 instances, so the L-BFGS algorithm will work perfectly here."
},
{
"code": null,
"e": 2488,
"s": 2473,
"text": "Implementation"
},
{
"code": null,
"e": 2765,
"s": 2488,
"text": "After creating a console application project and downloading ML.NET from NuGet Packages, you can proceed to implementation and model creation. In the beginning, you should create classes corresponding to the attributes of our dataset. Created classes are shown in the listing:"
},
{
"code": null,
"e": 2947,
"s": 2765,
"text": "Then you can go on to load the dataset and divide it into a training and a testing set. I propose to adopt the popular division, i.e. 70% is a training set and 30% is a testing set."
},
{
"code": null,
"e": 3184,
"s": 2947,
"text": "var dataPath = \"../../skin-segmentation.csv\";var ml = new MLContext();var DataView = ml.Data.LoadFromTextFile<Features>(dataPath, hasHeader: true, separatorChar: ',');var partitions = ml.Data.TrainTestSplit(DataView, testFraction: 0.3);"
},
{
"code": null,
"e": 3415,
"s": 3184,
"text": "Now you need to adapt the model structure to the standards proposed by the ML.NET library. This means that the property specifying the class must be called Label. The remaining attributes must be condensed under the name Features."
},
{
"code": null,
"e": 3610,
"s": 3415,
"text": "var pipeline = ml.Transforms.Conversion.MapValueToKey(inputColumnName: \"Class\", outputColumnName:\"Label\").Append(ml.Transforms.Concatenate(\"Features\", \"V1\",\"V2\",\"V3\")).AppendCacheCheckpoint(ml);"
},
{
"code": null,
"e": 3857,
"s": 3610,
"text": "Now is the time for creating a training pipeline. Here you choose a classifier in the form of L-BFGS, to which you specify in the parameters the column names of the label and features. You indicate the property that means the predicted label too."
},
{
"code": null,
"e": 4040,
"s": 3857,
"text": "var trainingPipeline = pipeline.Append(ml.MulticlassClassification.Trainers.LbfgsMaximumEntropy(\"Label\",\"Features\")).Append(ml.Transforms.Conversion.MapKeyToValue(\"PredictedLabel\"));"
},
{
"code": null,
"e": 4127,
"s": 4040,
"text": "After completing the previous steps, you can now go to training and testing the model:"
},
{
"code": null,
"e": 4288,
"s": 4127,
"text": "var trainedModel = trainingPipeline.Fit(partitions.TrainSet);var testMetrics = ml.MulticlassClassification.Evaluate(trainedModel.Transform(partitions.TestSet));"
},
{
"code": null,
"e": 4308,
"s": 4288,
"text": "Results and summary"
}
] |
Spring Boot & H2 - Console | As in previous chapter Application Setup, we've created the required files in spring boot project. Now let's update the application.properties lying in src/main/resources and pom.xml to use a different version of maven-resources-plugin.
application.properties
spring.datasource.url=jdbc:h2:mem:testdb
pom.xml
...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
</plugin>
</plugins>
</build>
...
In eclipse, run the Employee Application configuration as prepared during Application Setup
Eclipse console will show the similar output.
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------< com.tutorialspoint:sprint-boot-h2 >------------------
[INFO] Building sprint-boot-h2 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
...
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.2)
...
2021-07-24 20:51:11.347 INFO 9760 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer
: Tomcat initialized with port(s): 8080 (http)
...
2021-07-24 20:51:11.840 INFO 9760 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration
: H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
...
2021-07-24 20:51:14.805 INFO 9760 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer
: Tomcat started on port(s): 8080 (http) with context path ''
2021-07-24 20:51:14.823 INFO 9760 --- [ restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)
Once server is up and running, open localhost:8080/h2-console in a browser and click on Test Connection to verify the database connection.
Click on Connect button and H2 database window will appear as shown below −
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2333,
"s": 2096,
"text": "As in previous chapter Application Setup, we've created the required files in spring boot project. Now let's update the application.properties lying in src/main/resources and pom.xml to use a different version of maven-resources-plugin."
},
{
"code": null,
"e": 2356,
"s": 2333,
"text": "application.properties"
},
{
"code": null,
"e": 2398,
"s": 2356,
"text": "spring.datasource.url=jdbc:h2:mem:testdb\n"
},
{
"code": null,
"e": 2406,
"s": 2398,
"text": "pom.xml"
},
{
"code": null,
"e": 2776,
"s": 2406,
"text": "...\n<build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-resources-plugin</artifactId>\n <version>3.1.0</version>\n </plugin>\n </plugins>\n</build>\n..."
},
{
"code": null,
"e": 2868,
"s": 2776,
"text": "In eclipse, run the Employee Application configuration as prepared during Application Setup"
},
{
"code": null,
"e": 2914,
"s": 2868,
"text": "Eclipse console will show the similar output."
},
{
"code": null,
"e": 4115,
"s": 2914,
"text": "[INFO] Scanning for projects...\n[INFO] \n[INFO] -----------------< com.tutorialspoint:sprint-boot-h2 >------------------\n[INFO] Building sprint-boot-h2 0.0.1-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n...\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.5.2)\n\n...\n2021-07-24 20:51:11.347 INFO 9760 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer\n: Tomcat initialized with port(s): 8080 (http)\n...\n2021-07-24 20:51:11.840 INFO 9760 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration \n: H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'\n...\n2021-07-24 20:51:14.805 INFO 9760 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer\n: Tomcat started on port(s): 8080 (http) with context path ''\n2021-07-24 20:51:14.823 INFO 9760 --- [ restartedMain] c.t.s.SprintBootH2Application\n: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)\n"
},
{
"code": null,
"e": 4254,
"s": 4115,
"text": "Once server is up and running, open localhost:8080/h2-console in a browser and click on Test Connection to verify the database connection."
},
{
"code": null,
"e": 4330,
"s": 4254,
"text": "Click on Connect button and H2 database window will appear as shown below −"
},
{
"code": null,
"e": 4364,
"s": 4330,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4378,
"s": 4364,
"text": " Karthikeya T"
},
{
"code": null,
"e": 4411,
"s": 4378,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4426,
"s": 4411,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 4461,
"s": 4426,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4473,
"s": 4461,
"text": " Senol Atac"
},
{
"code": null,
"e": 4508,
"s": 4473,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4520,
"s": 4508,
"text": " Senol Atac"
},
{
"code": null,
"e": 4555,
"s": 4520,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4567,
"s": 4555,
"text": " Senol Atac"
},
{
"code": null,
"e": 4600,
"s": 4567,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4612,
"s": 4600,
"text": " Senol Atac"
},
{
"code": null,
"e": 4619,
"s": 4612,
"text": " Print"
},
{
"code": null,
"e": 4630,
"s": 4619,
"text": " Add Notes"
}
] |
Program to Reverse a String using Pointers - GeeksforGeeks | 12 Jan, 2019
Given a string, the task is to reverse this String using pointers.
Examples:
Input: Geeks
Output: skeeG
Input: GeeksForGeeks
Output: skeeGroFskeeG
Approach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two pointers.
Program:
#include <stdio.h>#include <string.h> // Function to reverse the string// using pointersvoid reverseString(char* str){ int l, i; char *begin_ptr, *end_ptr, ch; // Get the length of the string l = strlen(str); // Set the begin_ptr and end_ptr // initially to start of string begin_ptr = str; end_ptr = str; // Move the end_ptr to the last character for (i = 0; i < l - 1; i++) end_ptr++; // Swap the char from start and end // index using begin_ptr and end_ptr for (i = 0; i < l / 2; i++) { // swap character ch = *end_ptr; *end_ptr = *begin_ptr; *begin_ptr = ch; // update pointers positions begin_ptr++; end_ptr--; }} // Driver codeint main(){ // Get the string char str[100] = "GeeksForGeeks"; printf("Enter a string: %s\n", str); // Reverse the string reverseString(str); // Print the result printf("Reverse of the string: %s\n", str); return 0;}
Enter a string: GeeksForGeeks
Reverse of the string: skeeGroFskeeG
C-String
cpp-pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
fork() in C
Function Pointer in C
TCP Server-Client implementation in C
Substring in C++
Enumeration (or enum) in C
Structures in C | [
{
"code": null,
"e": 24498,
"s": 24470,
"text": "\n12 Jan, 2019"
},
{
"code": null,
"e": 24565,
"s": 24498,
"text": "Given a string, the task is to reverse this String using pointers."
},
{
"code": null,
"e": 24575,
"s": 24565,
"text": "Examples:"
},
{
"code": null,
"e": 24647,
"s": 24575,
"text": "Input: Geeks\nOutput: skeeG\n\nInput: GeeksForGeeks\nOutput: skeeGroFskeeG\n"
},
{
"code": null,
"e": 24863,
"s": 24647,
"text": "Approach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two pointers."
},
{
"code": null,
"e": 24872,
"s": 24863,
"text": "Program:"
},
{
"code": "#include <stdio.h>#include <string.h> // Function to reverse the string// using pointersvoid reverseString(char* str){ int l, i; char *begin_ptr, *end_ptr, ch; // Get the length of the string l = strlen(str); // Set the begin_ptr and end_ptr // initially to start of string begin_ptr = str; end_ptr = str; // Move the end_ptr to the last character for (i = 0; i < l - 1; i++) end_ptr++; // Swap the char from start and end // index using begin_ptr and end_ptr for (i = 0; i < l / 2; i++) { // swap character ch = *end_ptr; *end_ptr = *begin_ptr; *begin_ptr = ch; // update pointers positions begin_ptr++; end_ptr--; }} // Driver codeint main(){ // Get the string char str[100] = \"GeeksForGeeks\"; printf(\"Enter a string: %s\\n\", str); // Reverse the string reverseString(str); // Print the result printf(\"Reverse of the string: %s\\n\", str); return 0;}",
"e": 25866,
"s": 24872,
"text": null
},
{
"code": null,
"e": 25934,
"s": 25866,
"text": "Enter a string: GeeksForGeeks\nReverse of the string: skeeGroFskeeG\n"
},
{
"code": null,
"e": 25943,
"s": 25934,
"text": "C-String"
},
{
"code": null,
"e": 25955,
"s": 25943,
"text": "cpp-pointer"
},
{
"code": null,
"e": 25966,
"s": 25955,
"text": "C Language"
},
{
"code": null,
"e": 26064,
"s": 25966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26073,
"s": 26064,
"text": "Comments"
},
{
"code": null,
"e": 26086,
"s": 26073,
"text": "Old Comments"
},
{
"code": null,
"e": 26114,
"s": 26086,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26154,
"s": 26114,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26200,
"s": 26154,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26232,
"s": 26200,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26244,
"s": 26232,
"text": "fork() in C"
},
{
"code": null,
"e": 26266,
"s": 26244,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26304,
"s": 26266,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26321,
"s": 26304,
"text": "Substring in C++"
},
{
"code": null,
"e": 26348,
"s": 26321,
"text": "Enumeration (or enum) in C"
}
] |
Topic Modeling in Power BI using PyCaret | by Moez Ali | Towards Data Science | In our last post, we demonstrated how to implement clustering analysis in Power BI by integrating it with PyCaret, thus allowing analysts and data scientists to add a layer of machine learning to their reports and dashboards without any additional license costs.
In this post, we will see how we can implement topic modeling in Power BI using PyCaret. If you haven’t heard about PyCaret before, please read this announcement to learn more.
What is Natural Language Processing?
What is Topic Modeling?
Train and implement a Latent Dirichlet Allocation model in Power BI.
Analyze results and visualize information in a dashboard.
If you have used Python before, it is likely that you already have Anaconda Distribution installed on your computer. If not, click here to download Anaconda Distribution with Python 3.7 or greater.
Before we start using PyCaret’s machine learning capabilities in Power BI we have to create a virtual environment and install pycaret. It’s a four-step process:
✅ Step 1 — Create an anaconda environment
Open Anaconda Prompt from start menu and execute the following code:
conda create --name powerbi python=3.7
“powerbi” is the name of environment we have chosen. You can keep whatever name you would like.
✅ Step 2 — Install PyCaret
Execute the following code in Anaconda Prompt:
pip install pycaret
Installation may take 15–20 minutes. If you are having issues with installation, please see our GitHub page for known issues and resolutions.
✅Step 3 — Set Python Directory in Power BI
The virtual environment created must be linked with Power BI. This can be done using Global Settings in Power BI Desktop (File → Options → Global → Python scripting). Anaconda Environment by default is installed under:
C:\Users\username\Anaconda3\envs\
✅Step 4 — Install Language Model
In order to perform NLP tasks you must download language model by executing following code in your Anaconda Prompt.
First activate your conda environment in Anaconda Prompt:
conda activate powerbi
Download English Language Model:
python -m spacy download en_core_web_smpython -m textblob.download_corpora
Natural language processing (NLP) is a subfield of computer science and artificial intelligence that is concerned with the interactions between computers and human languages. In particular, NLP covers broad range of techniques on how to program computers to process and analyze large amounts of natural language data.
NLP-powered software helps us in our daily lives in various ways and it is likely that you have been using it without even knowing. Some examples are:
Personal assistants: Siri, Cortana, Alexa.
Auto-complete: In search engines (e.g: Google, Bing, Baidu, Yahoo).
Spell checking: Almost everywhere, in your browser, your IDE (e.g: Visual Studio), desktop apps (e.g: Microsoft Word).
Machine Translation: Google Translate.
Document Summarization Software: Text compactor, Autosummarizer.
Topic Modeling is a type of statistical model used for discovering abstract topics in text data. It is one of many practical applications within NLP.
A topic model is a type of statistical model that falls under unsupervised machine learning and is used for discovering abstract topics in text data. The goal of topic modeling is to automatically find the topics / themes in a set of documents.
Some common use-cases for topic modeling are:
Summarizing large text data by classifying documents into topics (the idea is pretty similar to clustering).
Exploratory Data Analysis to gain understanding of data such as customer feedback forms, amazon reviews, survey results etc.
Feature Engineering creating features for supervised machine learning experiments such as classification or regression
There are several algorithms used for topic modeling. Some common ones are Latent Dirichlet Allocation (LDA), Latent Semantic Analysis (LSA), and Non-Negative Matrix Factorization (NMF). Each algorithm has its own mathematical details which will not be covered in this tutorial. We will implement a Latent Dirichlet Allocation (LDA) model in Power BI using PyCaret’s NLP module.
If you are interested in learning the technical details of the LDA algorithm, you can read this paper.
In order to get meaningful results from topic modeling text data must be processed before feeding it to the algorithm. This is common with almost all NLP tasks. The preprocessing of text is different from the classical preprocessing techniques often used in machine learning when dealing with structured data (data in rows and columns).
PyCaret automatically preprocess text data by applying over 15 techniques such as stop word removal, tokenization, lemmatization, bi-gram/tri-gram extraction etc. If you would like to learn more about all the text preprocessing features available in PyCaret, click here.
Kiva is an international non-profit founded in 2005 in San Francisco. Its mission is to expand financial access to underserved communities in order to help them thrive.
In this tutorial we will use the open dataset from Kiva which contains loan information on 6,818 approved loan applicants. The dataset includes information such as loan amount, country, gender and some text data which is the application submitted by the borrower.
Our objective is to analyze the text data in the ‘en’ column to find abstract topics and then use them to evaluate the effect of certain topics (or certain types of loans) on the default rate.
Now that you have set up the Anaconda Environment, understand topic modeling and have the business context for this tutorial, let’s get started.
The first step is importing the dataset into Power BI Desktop. You can load the data using a web connector. (Power BI Desktop → Get Data → From Web).
Link to csv file:https://raw.githubusercontent.com/pycaret/pycaret/master/datasets/kiva.csv
To train a topic model in Power BI we will have to execute a Python script in Power Query Editor (Power Query Editor → Transform → Run python script). Run the following code as a Python script:
from pycaret.nlp import *dataset = get_topics(dataset, text='en')
There are 5 ready-to-use topic models available in PyCaret.
By default, PyCaret trains a Latent Dirichlet Allocation (LDA) model with 4 topics. Default values can be changed easily:
To change the model type use the model parameter within get_topics().
To change the number of topics, use the num_topics parameter.
See the example code for a Non-Negative Matrix Factorization model with 6 topics.
from pycaret.nlp import *dataset = get_topics(dataset, text='en', model='nmf', num_topics=6)
Output:
New columns containing topic weights are attached to the original dataset. Here’s how the final output looks like in Power BI once you apply the query.
Once you have topic weights in Power BI, here’s an example of how you can visualize it in dashboard to generate insights:
You can download the PBIX file and the data set from our GitHub.
If you would like to learn more about implementing Topic Modeling in Jupyter notebook using PyCaret, watch this 2 minute video tutorial:
If you are Interested in learning more about Topic Modeling, you can also checkout our NLP 101 Notebook Tutorial for beginners.
Follow our LinkedIn and subscribe to our Youtube channel to learn more about PyCaret.
User Guide / DocumentationGitHub RepositoryInstall PyCaretNotebook TutorialsContribute in PyCaret
As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
PyCaret getting started tutorials in Notebook:
ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification
PyCaret is an open source project. Everybody is welcome to contribute. If you would like to contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch.
Please give us ⭐️ on our GitHub repo if you like PyCaret.
Medium : https://medium.com/@moez_62905/
LinkedIn : https://www.linkedin.com/in/profile-moez/
Twitter : https://twitter.com/moezpycaretorg1 | [
{
"code": null,
"e": 434,
"s": 171,
"text": "In our last post, we demonstrated how to implement clustering analysis in Power BI by integrating it with PyCaret, thus allowing analysts and data scientists to add a layer of machine learning to their reports and dashboards without any additional license costs."
},
{
"code": null,
"e": 611,
"s": 434,
"text": "In this post, we will see how we can implement topic modeling in Power BI using PyCaret. If you haven’t heard about PyCaret before, please read this announcement to learn more."
},
{
"code": null,
"e": 648,
"s": 611,
"text": "What is Natural Language Processing?"
},
{
"code": null,
"e": 672,
"s": 648,
"text": "What is Topic Modeling?"
},
{
"code": null,
"e": 741,
"s": 672,
"text": "Train and implement a Latent Dirichlet Allocation model in Power BI."
},
{
"code": null,
"e": 799,
"s": 741,
"text": "Analyze results and visualize information in a dashboard."
},
{
"code": null,
"e": 997,
"s": 799,
"text": "If you have used Python before, it is likely that you already have Anaconda Distribution installed on your computer. If not, click here to download Anaconda Distribution with Python 3.7 or greater."
},
{
"code": null,
"e": 1158,
"s": 997,
"text": "Before we start using PyCaret’s machine learning capabilities in Power BI we have to create a virtual environment and install pycaret. It’s a four-step process:"
},
{
"code": null,
"e": 1200,
"s": 1158,
"text": "✅ Step 1 — Create an anaconda environment"
},
{
"code": null,
"e": 1269,
"s": 1200,
"text": "Open Anaconda Prompt from start menu and execute the following code:"
},
{
"code": null,
"e": 1308,
"s": 1269,
"text": "conda create --name powerbi python=3.7"
},
{
"code": null,
"e": 1404,
"s": 1308,
"text": "“powerbi” is the name of environment we have chosen. You can keep whatever name you would like."
},
{
"code": null,
"e": 1431,
"s": 1404,
"text": "✅ Step 2 — Install PyCaret"
},
{
"code": null,
"e": 1478,
"s": 1431,
"text": "Execute the following code in Anaconda Prompt:"
},
{
"code": null,
"e": 1498,
"s": 1478,
"text": "pip install pycaret"
},
{
"code": null,
"e": 1640,
"s": 1498,
"text": "Installation may take 15–20 minutes. If you are having issues with installation, please see our GitHub page for known issues and resolutions."
},
{
"code": null,
"e": 1683,
"s": 1640,
"text": "✅Step 3 — Set Python Directory in Power BI"
},
{
"code": null,
"e": 1902,
"s": 1683,
"text": "The virtual environment created must be linked with Power BI. This can be done using Global Settings in Power BI Desktop (File → Options → Global → Python scripting). Anaconda Environment by default is installed under:"
},
{
"code": null,
"e": 1936,
"s": 1902,
"text": "C:\\Users\\username\\Anaconda3\\envs\\"
},
{
"code": null,
"e": 1969,
"s": 1936,
"text": "✅Step 4 — Install Language Model"
},
{
"code": null,
"e": 2085,
"s": 1969,
"text": "In order to perform NLP tasks you must download language model by executing following code in your Anaconda Prompt."
},
{
"code": null,
"e": 2143,
"s": 2085,
"text": "First activate your conda environment in Anaconda Prompt:"
},
{
"code": null,
"e": 2166,
"s": 2143,
"text": "conda activate powerbi"
},
{
"code": null,
"e": 2199,
"s": 2166,
"text": "Download English Language Model:"
},
{
"code": null,
"e": 2274,
"s": 2199,
"text": "python -m spacy download en_core_web_smpython -m textblob.download_corpora"
},
{
"code": null,
"e": 2592,
"s": 2274,
"text": "Natural language processing (NLP) is a subfield of computer science and artificial intelligence that is concerned with the interactions between computers and human languages. In particular, NLP covers broad range of techniques on how to program computers to process and analyze large amounts of natural language data."
},
{
"code": null,
"e": 2743,
"s": 2592,
"text": "NLP-powered software helps us in our daily lives in various ways and it is likely that you have been using it without even knowing. Some examples are:"
},
{
"code": null,
"e": 2786,
"s": 2743,
"text": "Personal assistants: Siri, Cortana, Alexa."
},
{
"code": null,
"e": 2854,
"s": 2786,
"text": "Auto-complete: In search engines (e.g: Google, Bing, Baidu, Yahoo)."
},
{
"code": null,
"e": 2973,
"s": 2854,
"text": "Spell checking: Almost everywhere, in your browser, your IDE (e.g: Visual Studio), desktop apps (e.g: Microsoft Word)."
},
{
"code": null,
"e": 3012,
"s": 2973,
"text": "Machine Translation: Google Translate."
},
{
"code": null,
"e": 3077,
"s": 3012,
"text": "Document Summarization Software: Text compactor, Autosummarizer."
},
{
"code": null,
"e": 3227,
"s": 3077,
"text": "Topic Modeling is a type of statistical model used for discovering abstract topics in text data. It is one of many practical applications within NLP."
},
{
"code": null,
"e": 3472,
"s": 3227,
"text": "A topic model is a type of statistical model that falls under unsupervised machine learning and is used for discovering abstract topics in text data. The goal of topic modeling is to automatically find the topics / themes in a set of documents."
},
{
"code": null,
"e": 3518,
"s": 3472,
"text": "Some common use-cases for topic modeling are:"
},
{
"code": null,
"e": 3627,
"s": 3518,
"text": "Summarizing large text data by classifying documents into topics (the idea is pretty similar to clustering)."
},
{
"code": null,
"e": 3752,
"s": 3627,
"text": "Exploratory Data Analysis to gain understanding of data such as customer feedback forms, amazon reviews, survey results etc."
},
{
"code": null,
"e": 3871,
"s": 3752,
"text": "Feature Engineering creating features for supervised machine learning experiments such as classification or regression"
},
{
"code": null,
"e": 4250,
"s": 3871,
"text": "There are several algorithms used for topic modeling. Some common ones are Latent Dirichlet Allocation (LDA), Latent Semantic Analysis (LSA), and Non-Negative Matrix Factorization (NMF). Each algorithm has its own mathematical details which will not be covered in this tutorial. We will implement a Latent Dirichlet Allocation (LDA) model in Power BI using PyCaret’s NLP module."
},
{
"code": null,
"e": 4353,
"s": 4250,
"text": "If you are interested in learning the technical details of the LDA algorithm, you can read this paper."
},
{
"code": null,
"e": 4690,
"s": 4353,
"text": "In order to get meaningful results from topic modeling text data must be processed before feeding it to the algorithm. This is common with almost all NLP tasks. The preprocessing of text is different from the classical preprocessing techniques often used in machine learning when dealing with structured data (data in rows and columns)."
},
{
"code": null,
"e": 4961,
"s": 4690,
"text": "PyCaret automatically preprocess text data by applying over 15 techniques such as stop word removal, tokenization, lemmatization, bi-gram/tri-gram extraction etc. If you would like to learn more about all the text preprocessing features available in PyCaret, click here."
},
{
"code": null,
"e": 5130,
"s": 4961,
"text": "Kiva is an international non-profit founded in 2005 in San Francisco. Its mission is to expand financial access to underserved communities in order to help them thrive."
},
{
"code": null,
"e": 5394,
"s": 5130,
"text": "In this tutorial we will use the open dataset from Kiva which contains loan information on 6,818 approved loan applicants. The dataset includes information such as loan amount, country, gender and some text data which is the application submitted by the borrower."
},
{
"code": null,
"e": 5587,
"s": 5394,
"text": "Our objective is to analyze the text data in the ‘en’ column to find abstract topics and then use them to evaluate the effect of certain topics (or certain types of loans) on the default rate."
},
{
"code": null,
"e": 5732,
"s": 5587,
"text": "Now that you have set up the Anaconda Environment, understand topic modeling and have the business context for this tutorial, let’s get started."
},
{
"code": null,
"e": 5882,
"s": 5732,
"text": "The first step is importing the dataset into Power BI Desktop. You can load the data using a web connector. (Power BI Desktop → Get Data → From Web)."
},
{
"code": null,
"e": 5974,
"s": 5882,
"text": "Link to csv file:https://raw.githubusercontent.com/pycaret/pycaret/master/datasets/kiva.csv"
},
{
"code": null,
"e": 6168,
"s": 5974,
"text": "To train a topic model in Power BI we will have to execute a Python script in Power Query Editor (Power Query Editor → Transform → Run python script). Run the following code as a Python script:"
},
{
"code": null,
"e": 6234,
"s": 6168,
"text": "from pycaret.nlp import *dataset = get_topics(dataset, text='en')"
},
{
"code": null,
"e": 6294,
"s": 6234,
"text": "There are 5 ready-to-use topic models available in PyCaret."
},
{
"code": null,
"e": 6416,
"s": 6294,
"text": "By default, PyCaret trains a Latent Dirichlet Allocation (LDA) model with 4 topics. Default values can be changed easily:"
},
{
"code": null,
"e": 6486,
"s": 6416,
"text": "To change the model type use the model parameter within get_topics()."
},
{
"code": null,
"e": 6548,
"s": 6486,
"text": "To change the number of topics, use the num_topics parameter."
},
{
"code": null,
"e": 6630,
"s": 6548,
"text": "See the example code for a Non-Negative Matrix Factorization model with 6 topics."
},
{
"code": null,
"e": 6723,
"s": 6630,
"text": "from pycaret.nlp import *dataset = get_topics(dataset, text='en', model='nmf', num_topics=6)"
},
{
"code": null,
"e": 6731,
"s": 6723,
"text": "Output:"
},
{
"code": null,
"e": 6883,
"s": 6731,
"text": "New columns containing topic weights are attached to the original dataset. Here’s how the final output looks like in Power BI once you apply the query."
},
{
"code": null,
"e": 7005,
"s": 6883,
"text": "Once you have topic weights in Power BI, here’s an example of how you can visualize it in dashboard to generate insights:"
},
{
"code": null,
"e": 7070,
"s": 7005,
"text": "You can download the PBIX file and the data set from our GitHub."
},
{
"code": null,
"e": 7207,
"s": 7070,
"text": "If you would like to learn more about implementing Topic Modeling in Jupyter notebook using PyCaret, watch this 2 minute video tutorial:"
},
{
"code": null,
"e": 7335,
"s": 7207,
"text": "If you are Interested in learning more about Topic Modeling, you can also checkout our NLP 101 Notebook Tutorial for beginners."
},
{
"code": null,
"e": 7421,
"s": 7335,
"text": "Follow our LinkedIn and subscribe to our Youtube channel to learn more about PyCaret."
},
{
"code": null,
"e": 7519,
"s": 7421,
"text": "User Guide / DocumentationGitHub RepositoryInstall PyCaretNotebook TutorialsContribute in PyCaret"
},
{
"code": null,
"e": 7685,
"s": 7519,
"text": "As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python."
},
{
"code": null,
"e": 7787,
"s": 7685,
"text": "ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining"
},
{
"code": null,
"e": 7834,
"s": 7787,
"text": "PyCaret getting started tutorials in Notebook:"
},
{
"code": null,
"e": 7936,
"s": 7834,
"text": "ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification"
},
{
"code": null,
"e": 8145,
"s": 7936,
"text": "PyCaret is an open source project. Everybody is welcome to contribute. If you would like to contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch."
},
{
"code": null,
"e": 8203,
"s": 8145,
"text": "Please give us ⭐️ on our GitHub repo if you like PyCaret."
},
{
"code": null,
"e": 8244,
"s": 8203,
"text": "Medium : https://medium.com/@moez_62905/"
},
{
"code": null,
"e": 8297,
"s": 8244,
"text": "LinkedIn : https://www.linkedin.com/in/profile-moez/"
}
] |
Display text on an OpenCV window by using the function putText() | In this program, we will write text on an image using the opencv function putText(). This function takes in the image, font, coordinates of where to put the text, color, thickness, etc.
Step 1: Import cv2
Step 2: Define the parameters for the puttext( ) function.
Step 3: Pass the parameters in to the puttext() function.
Step 4: Display the image.
import cv2
image = cv2.imread("testimage.jpg")
text = "TutorialsPoint"
coordinates = (100,100)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
color = (255,0,255)
thickness = 2
image = cv2.putText(image, text, coordinates, font, fontScale, color, thickness, cv2.LINE_AA)
cv2.imshow("Text", image) | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "In this program, we will write text on an image using the opencv function putText(). This function takes in the image, font, coordinates of where to put the text, color, thickness, etc."
},
{
"code": null,
"e": 1411,
"s": 1248,
"text": "Step 1: Import cv2\nStep 2: Define the parameters for the puttext( ) function.\nStep 3: Pass the parameters in to the puttext() function.\nStep 4: Display the image."
},
{
"code": null,
"e": 1706,
"s": 1411,
"text": "import cv2\nimage = cv2.imread(\"testimage.jpg\")\ntext = \"TutorialsPoint\"\ncoordinates = (100,100)\nfont = cv2.FONT_HERSHEY_SIMPLEX\nfontScale = 1\ncolor = (255,0,255)\nthickness = 2\nimage = cv2.putText(image, text, coordinates, font, fontScale, color, thickness, cv2.LINE_AA)\ncv2.imshow(\"Text\", image)"
}
] |
Angular7 - Forms | In this chapter, we will see how forms are used in Angular 7. We will discuss two ways of working with forms −
Template driven form
Model driven form
With a template driven form, most of the work is done in the template. With the model driven form, most of the work is done in the component class.
Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit button in the form. To start with, we need to import to FormsModule from @angular/forms which is done in app.module.ts as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective,
RoutingComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ScrollDispatchModule,
DragDropModule,
FormsModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code.
Let us now create our form in the app.component.html file.
<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)">
<input type = "text" name = "emailid" placeholder = "emailid" ngModel>
<br/>
<input type = "password" name = "passwd" placeholder = "passwd" ngModel>
<br/>
<input type = "submit" value = "submit">
</form>
We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it.
In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it.
If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it.
Let us now create the function in the app.component.ts and fetch the values entered in the form.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
constructor(private myservice: MyserviceService) { }
ngOnInit() { }
onClickSubmit(data) {
alert("Entered Email id : " + data.emailid);
}
}
In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function.
The css for the login form is added in app.component.css −
input[type = text], input[type = password] {
width: 40%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #B3A9A9;
box-sizing: border-box;
}
input[type = submit] {
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #B3A9A9;
box-sizing: border-box;
}
This is how the browser is displayed −
The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is alerted as shown below −
In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array.
There is a change which goes in app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective,
RoutingComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ScrollDispatchModule,
DragDropModule,
ReactiveFormsModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from '@angular/forms'.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
emailid;
formdata;
constructor(private myservice: MyserviceService) { }
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("[email protected]"),
passwd: new FormControl("abcd1234")
});
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
The variable form data is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to.
This is how the values will be seen in the form UI.
We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html.
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid"
formControlName = "emailid">
<br/>
<input type = "password" class = "fortextbox" name = "passwd"
placeholder = "passwd" formControlName = "passwd">
<br/>
<input type = "submit" class = "forsubmit" value = "Log In">
</form>
</div>
<p> Email entered is : {{emailid}} </p>
In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup] = ”formdata”. On submit, the function is called onClickSubmit for which formdata.value is passed.
The input tag formControlName is used. It is given a value that we have used in the app.component.ts file.
On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file.
On clicking Login, the value will be displayed as shown in the above screenshot.
Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that we created in one of our previous sections. With Angular 7, we need to import Validators from @angular/forms as shown below −
import { FormGroup, FormControl, Validators} from '@angular/forms'
Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to be accessed using the Validators module.
You can just add validators or an array of validators required to tell Angular if a particular field is mandatory. Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following validation parameters −
Required
Pattern matching
This is how a code undergoes validation in app.component.ts.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
todaydate;
componentproperty;
emailid;
formdata;
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("", Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^ @]*")
])),
passwd: new FormControl("")
});
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we have added the required and the pattern matching parameters to take only valid email.
In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done as follows −
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)">
<input type = "text" class = "fortextbox" name = "emailid"
placeholder = "emailid" formControlName = "emailid">
<br/>
<input type = "password" class = "fortextbox" name = "passwd"
placeholder = "passwd" formControlName = "passwd">
<br/>
<input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit"
value = "Log In">
</form>
</div>
<p> Email entered is : {{emailid}} </p>
For the submit button, we have added disabled in the square bracket, which is given the following value.
!formdata.valid.
Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it.
Let us see how this works in the browser −
In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the valid email id and see the difference.
Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit it. With this, the email id entered is displayed at the bottom.
Let us now try custom validation with the same form. For custom validation, we can define our own custom function and add the required details in it. We will now see the below example for the same.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
todaydate;
componentproperty;
emailid;
formdata;
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("", Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^ @]*")
])),
passwd: new FormControl("", this.passwordvalidation)
});
}
passwordvalidation(formcontrol) {
if (formcontrol.value.length < 5) {
return {"passwd" : true};
}
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
In the above example, we have created a function passwordvalidation and the same is used in a previous section in the formcontrol - passwd: new FormControl("", this.passwordvalidation).
In the function that we have created, we will check if the length of the characters entered is appropriate. If the characters are less than five, it will return with the passwd true as shown above - return {"passwd" : true};. If the characters are more than five, it will consider it as valid and the login will be enabled.
Let us now see how this is displayed in the browser −
We have entered only three characters in the password and the login is disabled. To enable login, we need more than five characters. Let us now enter a valid length of characters and check.
The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2172,
"s": 2061,
"text": "In this chapter, we will see how forms are used in Angular 7. We will discuss two ways of working with forms −"
},
{
"code": null,
"e": 2193,
"s": 2172,
"text": "Template driven form"
},
{
"code": null,
"e": 2211,
"s": 2193,
"text": "Model driven form"
},
{
"code": null,
"e": 2359,
"s": 2211,
"text": "With a template driven form, most of the work is done in the template. With the model driven form, most of the work is done in the component class."
},
{
"code": null,
"e": 2625,
"s": 2359,
"text": "Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit button in the form. To start with, we need to import to FormsModule from @angular/forms which is done in app.module.ts as follows −"
},
{
"code": null,
"e": 3717,
"s": 2625,
"text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule , RoutingComponent} from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from './new-cmp/new-cmp.component'; \nimport { ChangeTextDirective } from './change-text.directive'; \nimport { SqrtPipe } from './app.sqrt'; \nimport { MyserviceService } from './myservice.service'; \nimport { HttpClientModule } from '@angular/common/http'; \nimport { ScrollDispatchModule } from '@angular/cdk/scrolling'; \nimport { DragDropModule } from '@angular/cdk/drag-drop'; \nimport { FormsModule } from '@angular/forms';\n\n@NgModule({ \n declarations: [\n SqrtPipe, \n AppComponent, \n NewCmpComponent, \n ChangeTextDirective, \n RoutingComponent \n ],\n imports: [ \n BrowserModule, \n AppRoutingModule, \n HttpClientModule, \n ScrollDispatchModule, \n DragDropModule, \n FormsModule \n ], \n providers: [MyserviceService], \n bootstrap: [AppComponent] \n}) \nexport class AppModule { }"
},
{
"code": null,
"e": 3848,
"s": 3717,
"text": "So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code."
},
{
"code": null,
"e": 3907,
"s": 3848,
"text": "Let us now create our form in the app.component.html file."
},
{
"code": null,
"e": 4208,
"s": 3907,
"text": "<form #userlogin = \"ngForm\" (ngSubmit) = \"onClickSubmit(userlogin.value)\"> \n <input type = \"text\" name = \"emailid\" placeholder = \"emailid\" ngModel> \n <br/> \n <input type = \"password\" name = \"passwd\" placeholder = \"passwd\" ngModel> \n <br/> \n <input type = \"submit\" value = \"submit\"> \n</form>"
},
{
"code": null,
"e": 4355,
"s": 4208,
"text": "We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it."
},
{
"code": null,
"e": 4667,
"s": 4355,
"text": "In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it."
},
{
"code": null,
"e": 4888,
"s": 4667,
"text": "If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it."
},
{
"code": null,
"e": 4985,
"s": 4888,
"text": "Let us now create the function in the app.component.ts and fetch the values entered in the form."
},
{
"code": null,
"e": 5431,
"s": 4985,
"text": "import { Component } from '@angular/core'; \nimport { MyserviceService } from './myservice.service';\n\n@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css']\n})\nexport class AppComponent { \n title = 'Angular 7 Project!'; \n constructor(private myservice: MyserviceService) { } \n ngOnInit() { } \n onClickSubmit(data) {\n alert(\"Entered Email id : \" + data.emailid); \n }\n}"
},
{
"code": null,
"e": 5598,
"s": 5431,
"text": "In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function."
},
{
"code": null,
"e": 5657,
"s": 5598,
"text": "The css for the login form is added in app.component.css −"
},
{
"code": null,
"e": 6006,
"s": 5657,
"text": "input[type = text], input[type = password] { \n width: 40%; \n padding: 12px 20px; \n margin: 8px 0; \n display: inline-block; \n border: 1px solid #B3A9A9; \n box-sizing: border-box; \n} \ninput[type = submit] { \n padding: 12px 20px; \n margin: 8px 0; \n display: inline-block; \n border: 1px solid #B3A9A9; \n box-sizing: border-box; \n}"
},
{
"code": null,
"e": 6045,
"s": 6006,
"text": "This is how the browser is displayed −"
},
{
"code": null,
"e": 6178,
"s": 6045,
"text": "The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is alerted as shown below −"
},
{
"code": null,
"e": 6305,
"s": 6178,
"text": "In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array."
},
{
"code": null,
"e": 6352,
"s": 6305,
"text": "There is a change which goes in app.module.ts."
},
{
"code": null,
"e": 7460,
"s": 6352,
"text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule , RoutingComponent} from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from './new-cmp/new-cmp.component'; \nimport { ChangeTextDirective } from './change-text.directive'; \nimport { SqrtPipe } from './app.sqrt'; \nimport { MyserviceService } from './myservice.service'; \nimport { HttpClientModule } from '@angular/common/http'; \nimport { ScrollDispatchModule } from '@angular/cdk/scrolling'; \nimport { DragDropModule } from '@angular/cdk/drag-drop';\nimport { ReactiveFormsModule } from '@angular/forms';\n\n@NgModule({ \n declarations: [ \n SqrtPipe, \n AppComponent, \n NewCmpComponent, \n ChangeTextDirective, \n RoutingComponent \n ],\n imports: [ \n BrowserModule, \n AppRoutingModule, \n HttpClientModule, \n ScrollDispatchModule, \n DragDropModule, \n ReactiveFormsModule \n ], \n providers: [MyserviceService], \n bootstrap: [AppComponent] \n}) \nexport class AppModule { }"
},
{
"code": null,
"e": 7610,
"s": 7460,
"text": "In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from '@angular/forms'."
},
{
"code": null,
"e": 8269,
"s": 7610,
"text": "import { Component } from '@angular/core'; \nimport { MyserviceService } from './myservice.service'; \nimport { FormGroup, FormControl } from '@angular/forms';\n\n@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n})\nexport class AppComponent {\n title = 'Angular 7 Project!'; \n emailid; \n formdata;\n constructor(private myservice: MyserviceService) { } \n ngOnInit() { \n this.formdata = new FormGroup({ \n emailid: new FormControl(\"[email protected]\"),\n passwd: new FormControl(\"abcd1234\") \n }); \n } \n onClickSubmit(data) {this.emailid = data.emailid;}\n}"
},
{
"code": null,
"e": 8533,
"s": 8269,
"text": "The variable form data is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to."
},
{
"code": null,
"e": 8585,
"s": 8533,
"text": "This is how the values will be seen in the form UI."
},
{
"code": null,
"e": 8697,
"s": 8585,
"text": "We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html."
},
{
"code": null,
"e": 9211,
"s": 8697,
"text": "<div> \n <form [formGroup] = \"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" > \n <input type = \"text\" class = \"fortextbox\" name = \"emailid\" placeholder = \"emailid\" \n formControlName = \"emailid\"> \n <br/> \n \n <input type = \"password\" class = \"fortextbox\" name = \"passwd\" \n placeholder = \"passwd\" formControlName = \"passwd\"> \n <br/>\n \n <input type = \"submit\" class = \"forsubmit\" value = \"Log In\"> \n </form>\n</div> \n<p> Email entered is : {{emailid}} </p>"
},
{
"code": null,
"e": 9408,
"s": 9211,
"text": "In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup] = ”formdata”. On submit, the function is called onClickSubmit for which formdata.value is passed."
},
{
"code": null,
"e": 9515,
"s": 9408,
"text": "The input tag formControlName is used. It is given a value that we have used in the app.component.ts file."
},
{
"code": null,
"e": 9635,
"s": 9515,
"text": "On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file."
},
{
"code": null,
"e": 9716,
"s": 9635,
"text": "On clicking Login, the value will be displayed as shown in the above screenshot."
},
{
"code": null,
"e": 10076,
"s": 9716,
"text": "Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that we created in one of our previous sections. With Angular 7, we need to import Validators from @angular/forms as shown below −"
},
{
"code": null,
"e": 10144,
"s": 10076,
"text": "import { FormGroup, FormControl, Validators} from '@angular/forms'\n"
},
{
"code": null,
"e": 10290,
"s": 10144,
"text": "Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to be accessed using the Validators module."
},
{
"code": null,
"e": 10546,
"s": 10290,
"text": "You can just add validators or an array of validators required to tell Angular if a particular field is mandatory. Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following validation parameters −"
},
{
"code": null,
"e": 10555,
"s": 10546,
"text": "Required"
},
{
"code": null,
"e": 10572,
"s": 10555,
"text": "Pattern matching"
},
{
"code": null,
"e": 10633,
"s": 10572,
"text": "This is how a code undergoes validation in app.component.ts."
},
{
"code": null,
"e": 11302,
"s": 10633,
"text": "import { Component } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n ngOnInit() {\n this.formdata = new FormGroup({\n emailid: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.pattern(\"[^ @]*@[^ @]*\")\n ])),\n passwd: new FormControl(\"\")\n });\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}"
},
{
"code": null,
"e": 11497,
"s": 11302,
"text": "In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we have added the required and the pattern matching parameters to take only valid email."
},
{
"code": null,
"e": 11621,
"s": 11497,
"text": "In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done as follows −"
},
{
"code": null,
"e": 12173,
"s": 11621,
"text": "<div> \n <form [formGroup] = \"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\"> \n <input type = \"text\" class = \"fortextbox\" name = \"emailid\" \n placeholder = \"emailid\" formControlName = \"emailid\"> \n <br/> \n \n <input type = \"password\" class = \"fortextbox\" name = \"passwd\" \n placeholder = \"passwd\" formControlName = \"passwd\">\n <br/> \n \n <input type = \"submit\" [disabled] = \"!formdata.valid\" class = \"forsubmit\" \n value = \"Log In\"> \n </form> \n</div>\n<p> Email entered is : {{emailid}} </p>"
},
{
"code": null,
"e": 12278,
"s": 12173,
"text": "For the submit button, we have added disabled in the square bracket, which is given the following value."
},
{
"code": null,
"e": 12296,
"s": 12278,
"text": "!formdata.valid.\n"
},
{
"code": null,
"e": 12414,
"s": 12296,
"text": "Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it."
},
{
"code": null,
"e": 12457,
"s": 12414,
"text": "Let us see how this works in the browser −"
},
{
"code": null,
"e": 12612,
"s": 12457,
"text": "In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the valid email id and see the difference."
},
{
"code": null,
"e": 12793,
"s": 12612,
"text": "Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit it. With this, the email id entered is displayed at the bottom."
},
{
"code": null,
"e": 12991,
"s": 12793,
"text": "Let us now try custom validation with the same form. For custom validation, we can define our own custom function and add the required details in it. We will now see the below example for the same."
},
{
"code": null,
"e": 13812,
"s": 12991,
"text": "import { Component } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n ngOnInit() {\n this.formdata = new FormGroup({\n emailid: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.pattern(\"[^ @]*@[^ @]*\")\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n passwordvalidation(formcontrol) {\n if (formcontrol.value.length < 5) {\n return {\"passwd\" : true};\n }\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}"
},
{
"code": null,
"e": 13998,
"s": 13812,
"text": "In the above example, we have created a function passwordvalidation and the same is used in a previous section in the formcontrol - passwd: new FormControl(\"\", this.passwordvalidation)."
},
{
"code": null,
"e": 14322,
"s": 13998,
"text": "In the function that we have created, we will check if the length of the characters entered is appropriate. If the characters are less than five, it will return with the passwd true as shown above - return {\"passwd\" : true};. If the characters are more than five, it will consider it as valid and the login will be enabled."
},
{
"code": null,
"e": 14376,
"s": 14322,
"text": "Let us now see how this is displayed in the browser −"
},
{
"code": null,
"e": 14566,
"s": 14376,
"text": "We have entered only three characters in the password and the login is disabled. To enable login, we need more than five characters. Let us now enter a valid length of characters and check."
},
{
"code": null,
"e": 14687,
"s": 14566,
"text": "The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in."
},
{
"code": null,
"e": 14722,
"s": 14687,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14736,
"s": 14722,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 14771,
"s": 14736,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14785,
"s": 14771,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 14820,
"s": 14785,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 14840,
"s": 14820,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 14875,
"s": 14840,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14892,
"s": 14875,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 14925,
"s": 14892,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 14937,
"s": 14925,
"text": " Senol Atac"
},
{
"code": null,
"e": 14972,
"s": 14937,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 14984,
"s": 14972,
"text": " Senol Atac"
},
{
"code": null,
"e": 14991,
"s": 14984,
"text": " Print"
},
{
"code": null,
"e": 15002,
"s": 14991,
"text": " Add Notes"
}
] |
BeanFactory Example in Spring - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In order to instantiate the Spring core container, we can we create an object of the BeanFactory or ApplicationContext implementation classes by passing the Spring configuration.
The Spring Framework comes with two distinct types of containers:
BeanFactory Interface
ApplicationContext Interface
BeanFactory Interface
ApplicationContext Interface
BeanFactory is an interface, which is coming from the org.springframework.beans.factory package. This is a root interface for accessing the spring bean container. The name itself suggested that the BeanFactory is an implementation of the Factory design pattern.
The BeanFactory interface is implemented by objects that hold a number of bean definitions, and each bean is uniquely identified by the name or id. Based on the bean definition the factory will create and return the bean instances.
The BeanFactory interface provides the basic endpoint for the spring core container towards the applications can access the core container services.
There are several implementations of BeanFactory interface. But the most useful one is org.springframework.context.support.ClassPathXmlApplicationContext.
In the below example, we are going to implement the Spring application step by step, using maven.
Step 1 :
Create pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>SpringCoreExmples</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringCoreExmples</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
</project>
Step 2 :
Create Employee class :
package com.onlinetutorialspoint.springcoreapplication;
public class Employee {
private int employeeId;
private String employeeName;
public Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
public int getEmployeeId() {
return employeeId;
}
public String getEmployeeName() {
return employeeName;
}
}
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="employee" class="com.onlinetutorialspoint.springcoreapplication.Employee">
<constructor-arg value="200" />
<constructor-arg value="chandrashekhar" />
</bean>
</beans>
package com.onlinetutorialspoint.springcoreapplication;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("Spring-Bean.xml");
Employee employee = (Employee) beanFactory.getBean("employee");
System.out.println("employee Id : " + employee.getEmployeeId());
System.out.println("employee Name : " + employee.getEmployeeName());
}
}
On the above example, by creating the ClassPathXmlApplicationContext object we obtain the BeanFactory. By using the getBean() method available in the BeanFactory, we can get the actual bean by passing the bean name, which is already defined in the Spring-Bean.xml.
Done!
Happy Learning 🙂
BeanFactory Example with Maven
File size: 17 KB
Downloads: 1041
Dependency Injection (IoC) in spring with Example
Spring Collection Map Dependency Example
@Qualifier annotation example in Spring
Spring Collection Dependency List Example
Spring Bean Autowire By Constructor Example
Types of Spring Bean Scopes Example
Spring Bean Autowire ByName Example
Spring AOP ThrowsAdvice Example XML
spring expression language example
Spring AOP Example Before and After Advice XML
Spring Bean Autowire ByType Example
How to Get All Spring Beans Details Loaded in ICO
Spring AOP Around Advice Example XML
@Component,@Service,@Repository,@Controller in spring
Spring MVC HelloWorld
Dependency Injection (IoC) in spring with Example
Spring Collection Map Dependency Example
@Qualifier annotation example in Spring
Spring Collection Dependency List Example
Spring Bean Autowire By Constructor Example
Types of Spring Bean Scopes Example
Spring Bean Autowire ByName Example
Spring AOP ThrowsAdvice Example XML
spring expression language example
Spring AOP Example Before and After Advice XML
Spring Bean Autowire ByType Example
How to Get All Spring Beans Details Loaded in ICO
Spring AOP Around Advice Example XML
@Component,@Service,@Repository,@Controller in spring
Spring MVC HelloWorld
prasanna
October 24, 2018 at 4:18 pm - Reply
well written easy to understand
prasanna
October 24, 2018 at 4:18 pm - Reply
well written easy to understand
well written easy to understand | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 577,
"s": 398,
"text": "In order to instantiate the Spring core container, we can we create an object of the BeanFactory or ApplicationContext implementation classes by passing the Spring configuration."
},
{
"code": null,
"e": 643,
"s": 577,
"text": "The Spring Framework comes with two distinct types of containers:"
},
{
"code": null,
"e": 696,
"s": 643,
"text": "\nBeanFactory Interface\nApplicationContext Interface\n"
},
{
"code": null,
"e": 718,
"s": 696,
"text": "BeanFactory Interface"
},
{
"code": null,
"e": 747,
"s": 718,
"text": "ApplicationContext Interface"
},
{
"code": null,
"e": 1009,
"s": 747,
"text": "BeanFactory is an interface, which is coming from the org.springframework.beans.factory package. This is a root interface for accessing the spring bean container. The name itself suggested that the BeanFactory is an implementation of the Factory design pattern."
},
{
"code": null,
"e": 1241,
"s": 1009,
"text": "The BeanFactory interface is implemented by objects that hold a number of bean definitions, and each bean is uniquely identified by the name or id. Based on the bean definition the factory will create and return the bean instances."
},
{
"code": null,
"e": 1390,
"s": 1241,
"text": "The BeanFactory interface provides the basic endpoint for the spring core container towards the applications can access the core container services."
},
{
"code": null,
"e": 1545,
"s": 1390,
"text": "There are several implementations of BeanFactory interface. But the most useful one is org.springframework.context.support.ClassPathXmlApplicationContext."
},
{
"code": null,
"e": 1643,
"s": 1545,
"text": "In the below example, we are going to implement the Spring application step by step, using maven."
},
{
"code": null,
"e": 1652,
"s": 1643,
"text": "Step 1 :"
},
{
"code": null,
"e": 1667,
"s": 1652,
"text": "Create pom.xml"
},
{
"code": null,
"e": 2703,
"s": 1667,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringCoreExmples</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>SpringCoreExmples</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n <!-- Spring framework -->\n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring</artifactId>\n <version>2.5.6</version>\n </dependency>\n </dependencies>\n</project>"
},
{
"code": null,
"e": 2712,
"s": 2703,
"text": "Step 2 :"
},
{
"code": null,
"e": 2736,
"s": 2712,
"text": "Create Employee class :"
},
{
"code": null,
"e": 3169,
"s": 2736,
"text": "package com.onlinetutorialspoint.springcoreapplication;\n\npublic class Employee {\n\n private int employeeId;\n private String employeeName;\n\n public Employee(int employeeId, String employeeName) {\n this.employeeId = employeeId;\n this.employeeName = employeeName;\n }\n\n public int getEmployeeId() {\n return employeeId;\n }\n\n public String getEmployeeName() {\n return employeeName;\n }\n\n}"
},
{
"code": null,
"e": 3630,
"s": 3169,
"text": "<beans xmlns=\"http://www.springframework.org/schema/beans\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\">\n <bean id=\"employee\" class=\"com.onlinetutorialspoint.springcoreapplication.Employee\">\n <constructor-arg value=\"200\" />\n <constructor-arg value=\"chandrashekhar\" />\n </bean>\n</beans>"
},
{
"code": null,
"e": 4204,
"s": 3630,
"text": "package com.onlinetutorialspoint.springcoreapplication;\n\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class Client {\n\n public static void main(String[] args) {\n BeanFactory beanFactory = new ClassPathXmlApplicationContext(\"Spring-Bean.xml\");\n Employee employee = (Employee) beanFactory.getBean(\"employee\");\n System.out.println(\"employee Id : \" + employee.getEmployeeId());\n System.out.println(\"employee Name : \" + employee.getEmployeeName());\n }\n}"
},
{
"code": null,
"e": 4469,
"s": 4204,
"text": "On the above example, by creating the ClassPathXmlApplicationContext object we obtain the BeanFactory. By using the getBean() method available in the BeanFactory, we can get the actual bean by passing the bean name, which is already defined in the Spring-Bean.xml."
},
{
"code": null,
"e": 4475,
"s": 4469,
"text": "Done!"
},
{
"code": null,
"e": 4492,
"s": 4475,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4560,
"s": 4492,
"text": "\n\nBeanFactory Example with Maven\n\nFile size: 17 KB\nDownloads: 1041\n"
},
{
"code": null,
"e": 5168,
"s": 4560,
"text": "\nDependency Injection (IoC) in spring with Example\nSpring Collection Map Dependency Example\n@Qualifier annotation example in Spring\nSpring Collection Dependency List Example\nSpring Bean Autowire By Constructor Example\nTypes of Spring Bean Scopes Example\nSpring Bean Autowire ByName Example\nSpring AOP ThrowsAdvice Example XML\nspring expression language example\nSpring AOP Example Before and After Advice XML\nSpring Bean Autowire ByType Example\nHow to Get All Spring Beans Details Loaded in ICO\nSpring AOP Around Advice Example XML\n@Component,@Service,@Repository,@Controller in spring\nSpring MVC HelloWorld\n"
},
{
"code": null,
"e": 5218,
"s": 5168,
"text": "Dependency Injection (IoC) in spring with Example"
},
{
"code": null,
"e": 5259,
"s": 5218,
"text": "Spring Collection Map Dependency Example"
},
{
"code": null,
"e": 5299,
"s": 5259,
"text": "@Qualifier annotation example in Spring"
},
{
"code": null,
"e": 5341,
"s": 5299,
"text": "Spring Collection Dependency List Example"
},
{
"code": null,
"e": 5385,
"s": 5341,
"text": "Spring Bean Autowire By Constructor Example"
},
{
"code": null,
"e": 5421,
"s": 5385,
"text": "Types of Spring Bean Scopes Example"
},
{
"code": null,
"e": 5457,
"s": 5421,
"text": "Spring Bean Autowire ByName Example"
},
{
"code": null,
"e": 5493,
"s": 5457,
"text": "Spring AOP ThrowsAdvice Example XML"
},
{
"code": null,
"e": 5528,
"s": 5493,
"text": "spring expression language example"
},
{
"code": null,
"e": 5575,
"s": 5528,
"text": "Spring AOP Example Before and After Advice XML"
},
{
"code": null,
"e": 5611,
"s": 5575,
"text": "Spring Bean Autowire ByType Example"
},
{
"code": null,
"e": 5661,
"s": 5611,
"text": "How to Get All Spring Beans Details Loaded in ICO"
},
{
"code": null,
"e": 5698,
"s": 5661,
"text": "Spring AOP Around Advice Example XML"
},
{
"code": null,
"e": 5752,
"s": 5698,
"text": "@Component,@Service,@Repository,@Controller in spring"
},
{
"code": null,
"e": 5774,
"s": 5752,
"text": "Spring MVC HelloWorld"
},
{
"code": null,
"e": 5864,
"s": 5774,
"text": "\n\n\n\n\n\nprasanna\nOctober 24, 2018 at 4:18 pm - Reply \n\nwell written easy to understand\n\n\n\n\n"
},
{
"code": null,
"e": 5952,
"s": 5864,
"text": "\n\n\n\n\nprasanna\nOctober 24, 2018 at 4:18 pm - Reply \n\nwell written easy to understand\n\n\n\n"
}
] |
C# Program to Delete an Empty and a Non-Empty Directory - GeeksforGeeks | 30 Nov, 2021
Given a directory(empty or non-empty), now we have to delete the given directory. Here, an empty directory means the directory is present without any files or subdirectories. We can define a directory as a collection of files and subdirectories, a directory may have data or not contain no data. The non-empty directory means the directory with files or subdirectories. We can delete the directory by using the Delete() method of the Directory class. This method is overloaded in two different ways:
Delete(String)
Delete(String, Boolean)
Let’s discuss them one by one.
This method is used to delete an empty directory from a given path or location.
Syntax:
public static void Delete (string Mypath);
Where Mypath is the location of the given directory that we want to remove and the type of this parameter is a string.
Exceptions:
It can have the following exceptions
IOException: This exception occurs when a file with the same name and location given by Mypath exists. Or the directory is read-only.
UnauthorizedAccessException: This exception will occur when the caller does not have the specified permission.
ArgumentNullException: This exception will occur when the Mypath is null.
PathTooLongException: This exception will occur when the given Mypath, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: This exception will occur when the Mypath does not exist or could not be found. Or the given path is invalid.
Example 1:
Let us consider an empty directory named “sravan” in the D drive. Now using Delete(String) method we delete the “sravan” directory.
C#
// C# program to delete the empty directory// Using Delete(string) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete empty directory // Using Delete() method Directory.Delete("D:/sravan"); Console.WriteLine("Deleted");}}
Output:
Deleted
Example 2:
Let us consider a non-empty directory named “vignan” with a file named “test” in the D drive. Now using Delete(String) method we will delete the “vignan” directory.
C#
// C# program to delete the empty directory// Using Delete(string) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete empty directory // Using Delete() method Directory.Delete("D:/vignan"); Console.WriteLine("Deleted");}}
Output:
Deleted
This method is used to delete the given directory and if indicated, any subdirectories and files in the directory.
Syntax:
public static void Delete (string Mypath, bool recursive);
Where Mypath is the directory path and recursive is used to remove files, directories, etc if it is true. Otherwise false.
Exceptions:
It can have the following exceptions
IOException: This exception occurs when a file with the same name and location specified by Mypath exists. Or the directory is read-only.
UnauthorizedAccessException: This exception will occur when the caller does not have the required permission.
ArgumentNullException: This exception will occur when the Mypath is null.
PathTooLongException: This exception will occur when the specified Mypath, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: This exception will occur when the Mypath does not exist or could not be found.
Example 1:
Let us consider an empty directory named “vignan” in the D drive. Now using Delete(String, Boolean) method we will delete the “vignan” directory.
C#
// C# program to delete the empty directory// Using Delete(String, Boolean) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete empty directory // Using Delete(String, Boolean) method Directory.Delete("D:/vignan", true); Console.WriteLine("Deleted");}}
Output:
Deleted
Example 2:
Let us consider a non-empty directory named “sravan” with a file named “test” in the D drive. Now using Delete(String, Boolean) method we will delete the “sravan” directory.
C#
// C# program to delete the non-empty directory// Using Delete(String, Boolean) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete non-empty directory // Using Delete(String, Boolean) method Directory.Delete("D:/sravan", true); Console.WriteLine("Deleted");}}
Output:
Deleted
CSharp-File-Handling
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to Print a New Line in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 24411,
"s": 23911,
"text": "Given a directory(empty or non-empty), now we have to delete the given directory. Here, an empty directory means the directory is present without any files or subdirectories. We can define a directory as a collection of files and subdirectories, a directory may have data or not contain no data. The non-empty directory means the directory with files or subdirectories. We can delete the directory by using the Delete() method of the Directory class. This method is overloaded in two different ways:"
},
{
"code": null,
"e": 24426,
"s": 24411,
"text": "Delete(String)"
},
{
"code": null,
"e": 24450,
"s": 24426,
"text": "Delete(String, Boolean)"
},
{
"code": null,
"e": 24481,
"s": 24450,
"text": "Let’s discuss them one by one."
},
{
"code": null,
"e": 24561,
"s": 24481,
"text": "This method is used to delete an empty directory from a given path or location."
},
{
"code": null,
"e": 24569,
"s": 24561,
"text": "Syntax:"
},
{
"code": null,
"e": 24612,
"s": 24569,
"text": "public static void Delete (string Mypath);"
},
{
"code": null,
"e": 24731,
"s": 24612,
"text": "Where Mypath is the location of the given directory that we want to remove and the type of this parameter is a string."
},
{
"code": null,
"e": 24743,
"s": 24731,
"text": "Exceptions:"
},
{
"code": null,
"e": 24780,
"s": 24743,
"text": "It can have the following exceptions"
},
{
"code": null,
"e": 24914,
"s": 24780,
"text": "IOException: This exception occurs when a file with the same name and location given by Mypath exists. Or the directory is read-only."
},
{
"code": null,
"e": 25025,
"s": 24914,
"text": "UnauthorizedAccessException: This exception will occur when the caller does not have the specified permission."
},
{
"code": null,
"e": 25099,
"s": 25025,
"text": "ArgumentNullException: This exception will occur when the Mypath is null."
},
{
"code": null,
"e": 25232,
"s": 25099,
"text": "PathTooLongException: This exception will occur when the given Mypath, file name, or both exceed the system-defined maximum length. "
},
{
"code": null,
"e": 25370,
"s": 25232,
"text": "DirectoryNotFoundException: This exception will occur when the Mypath does not exist or could not be found. Or the given path is invalid."
},
{
"code": null,
"e": 25381,
"s": 25370,
"text": "Example 1:"
},
{
"code": null,
"e": 25513,
"s": 25381,
"text": "Let us consider an empty directory named “sravan” in the D drive. Now using Delete(String) method we delete the “sravan” directory."
},
{
"code": null,
"e": 25516,
"s": 25513,
"text": "C#"
},
{
"code": "// C# program to delete the empty directory// Using Delete(string) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete empty directory // Using Delete() method Directory.Delete(\"D:/sravan\"); Console.WriteLine(\"Deleted\");}}",
"e": 25784,
"s": 25516,
"text": null
},
{
"code": null,
"e": 25792,
"s": 25784,
"text": "Output:"
},
{
"code": null,
"e": 25800,
"s": 25792,
"text": "Deleted"
},
{
"code": null,
"e": 25811,
"s": 25800,
"text": "Example 2:"
},
{
"code": null,
"e": 25976,
"s": 25811,
"text": "Let us consider a non-empty directory named “vignan” with a file named “test” in the D drive. Now using Delete(String) method we will delete the “vignan” directory."
},
{
"code": null,
"e": 25979,
"s": 25976,
"text": "C#"
},
{
"code": "// C# program to delete the empty directory// Using Delete(string) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete empty directory // Using Delete() method Directory.Delete(\"D:/vignan\"); Console.WriteLine(\"Deleted\");}}",
"e": 26251,
"s": 25979,
"text": null
},
{
"code": null,
"e": 26259,
"s": 26251,
"text": "Output:"
},
{
"code": null,
"e": 26267,
"s": 26259,
"text": "Deleted"
},
{
"code": null,
"e": 26382,
"s": 26267,
"text": "This method is used to delete the given directory and if indicated, any subdirectories and files in the directory."
},
{
"code": null,
"e": 26390,
"s": 26382,
"text": "Syntax:"
},
{
"code": null,
"e": 26449,
"s": 26390,
"text": "public static void Delete (string Mypath, bool recursive);"
},
{
"code": null,
"e": 26572,
"s": 26449,
"text": "Where Mypath is the directory path and recursive is used to remove files, directories, etc if it is true. Otherwise false."
},
{
"code": null,
"e": 26584,
"s": 26572,
"text": "Exceptions:"
},
{
"code": null,
"e": 26621,
"s": 26584,
"text": "It can have the following exceptions"
},
{
"code": null,
"e": 26759,
"s": 26621,
"text": "IOException: This exception occurs when a file with the same name and location specified by Mypath exists. Or the directory is read-only."
},
{
"code": null,
"e": 26869,
"s": 26759,
"text": "UnauthorizedAccessException: This exception will occur when the caller does not have the required permission."
},
{
"code": null,
"e": 26943,
"s": 26869,
"text": "ArgumentNullException: This exception will occur when the Mypath is null."
},
{
"code": null,
"e": 27079,
"s": 26943,
"text": "PathTooLongException: This exception will occur when the specified Mypath, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 27187,
"s": 27079,
"text": "DirectoryNotFoundException: This exception will occur when the Mypath does not exist or could not be found."
},
{
"code": null,
"e": 27198,
"s": 27187,
"text": "Example 1:"
},
{
"code": null,
"e": 27344,
"s": 27198,
"text": "Let us consider an empty directory named “vignan” in the D drive. Now using Delete(String, Boolean) method we will delete the “vignan” directory."
},
{
"code": null,
"e": 27347,
"s": 27344,
"text": "C#"
},
{
"code": "// C# program to delete the empty directory// Using Delete(String, Boolean) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete empty directory // Using Delete(String, Boolean) method Directory.Delete(\"D:/vignan\", true); Console.WriteLine(\"Deleted\");}}",
"e": 27645,
"s": 27347,
"text": null
},
{
"code": null,
"e": 27653,
"s": 27645,
"text": "Output:"
},
{
"code": null,
"e": 27661,
"s": 27653,
"text": "Deleted"
},
{
"code": null,
"e": 27672,
"s": 27661,
"text": "Example 2:"
},
{
"code": null,
"e": 27846,
"s": 27672,
"text": "Let us consider a non-empty directory named “sravan” with a file named “test” in the D drive. Now using Delete(String, Boolean) method we will delete the “sravan” directory."
},
{
"code": null,
"e": 27849,
"s": 27846,
"text": "C#"
},
{
"code": "// C# program to delete the non-empty directory// Using Delete(String, Boolean) methodusing System;using System.IO; class GFG{ static void Main(){ // Delete non-empty directory // Using Delete(String, Boolean) method Directory.Delete(\"D:/sravan\", true); Console.WriteLine(\"Deleted\");}}",
"e": 28159,
"s": 27849,
"text": null
},
{
"code": null,
"e": 28167,
"s": 28159,
"text": "Output:"
},
{
"code": null,
"e": 28175,
"s": 28167,
"text": "Deleted"
},
{
"code": null,
"e": 28196,
"s": 28175,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 28203,
"s": 28196,
"text": "Picked"
},
{
"code": null,
"e": 28206,
"s": 28203,
"text": "C#"
},
{
"code": null,
"e": 28218,
"s": 28206,
"text": "C# Programs"
},
{
"code": null,
"e": 28316,
"s": 28218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28325,
"s": 28316,
"text": "Comments"
},
{
"code": null,
"e": 28338,
"s": 28325,
"text": "Old Comments"
},
{
"code": null,
"e": 28378,
"s": 28338,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28401,
"s": 28378,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28429,
"s": 28401,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28451,
"s": 28429,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28468,
"s": 28451,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28508,
"s": 28468,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28554,
"s": 28508,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 28579,
"s": 28554,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 28613,
"s": 28579,
"text": "Program to Print a New Line in C#"
}
] |
Name Your Favorite Excel Function and I’ll Teach You its Pandas Equivalent | by Britt | Towards Data Science | So since no one has named one yet, I’ll start! One of my favorite excel formulas to date is a Match function that is nested in an Index function. But before I teach you its Pandas equivalent, let’s get some background on the INDEX/MATCH function and why it’s better than a VLOOKUP.
Two reasons why INDEX/MATCH is better than VLOOKUP:
You can search a whole spreadsheet for values instead of being forced to only search the left-most column. (more on this below)It’s more computationally-efficient by 3% with unsorted data, by 30% with sorted data and an approximate match, and by 13% with sorted data and an exact match! (source)
You can search a whole spreadsheet for values instead of being forced to only search the left-most column. (more on this below)
It’s more computationally-efficient by 3% with unsorted data, by 30% with sorted data and an approximate match, and by 13% with sorted data and an exact match! (source)
By combining the INDEX/MATCH formulas, you can get around the restrictions of a VLOOKUP. In a nutshell, VLOOKUP scans the leftmost column of a given range until it lands on the first instance of a given “search_key”. It then returns the value of the cell in the index provided, which will always be to the right. But again, as I said above, with INDEX/MATCH you can search a whole spreadsheet (by column or by row) for values instead of being forced to only search the left-most column with a VLOOKUP.
Check out this monthly podcast dashboard I built for Recode while working as a Traffic Analyst at Vox Media to see how I leveraged a SMALL function nested in a INDEX/MATCH function to display episode-level data.
Now let’s move on to the fun part... how to do this with Pandas!
I’ll show you four ways to code this in Python leveraging the Pandas library, but first, let’s get some context on our goal. We have two DataFrames named df_1 and df_2 (seen below).
Our goal is to match the last_name column in df_2 with the correct rows in df_1 to get something like this:
code: df_1[‘last_name’] = df_1.id.map(df_2.set_index(‘id’)[‘last_name’].to_dict())2.3 ms ± 131 μs per loop
Here we create a new column, last_name, for df_1. The values of that new column are created by mapping the ids from df_1 to the last names in df_2 where those ids match. By calling the .to_dict() method on our series df_2.last_name we get a key : value pair of the index which would be: {0: ‘Snow’, 1: ‘Targaryen’, 2: ‘Tyrell’, 3: ‘Lannister’, 4: ‘Stark’}. In this case the .map() method would not work, as the values in our id column for df_1 do not match the keys in this dictionary. So we passed the .set_index() method first to change the index to the ids of df_2 which would give us this dictionary: {1003: ‘Snow’, 1004: ‘Targaryen’, 1005: ‘Tyrell’, 1002: ‘Lannister’, 1006: ‘Stark’}. We can now use the .map() method to map the values of our Series (id) to the corresponding values of our new dictionary.
A fellow data scientist, Bernard Kurka, helped me figure out this first solution. Check out some of his Medium posts too.
code: df_1 = df_1.set_index('id').join(df_2.set_index('id'))39.2 ns ± 0.709 ns per loop
The .join() method will join columns of another DataFrame. By default it does a left join, but you can specify this by passing the how= hyperparameter and changing it to ‘right’, ‘outer’, or ‘inner’}. We needed to call the .set_index() method on df_1 and df_2 so we could join on the right index.
code: df_1 = df_1.merge(df_2, how='left', on='id')38 ns ± 0.369 ns per loop
The .merge() method merges a DataFrame or named Series objects with a database-style join. Here I specified how I wanted it joined with how= and on what column/index by specifying the on= hyperparameter.
code: df_1 = pd.concat([df_1.set_index('id'), df_2.set_index('id').last_name], axis=1, sort='id', join='inner')38.5 ns ± 0.379 ns per loop
The pd.concat() method concatenates pandas objects along a particular axis with optional set logic along the other axes. So here I passed the pandas objects I wanted concatenated as a list. The first being a DataFrame where I set the index to the id column and the second being a Series but also indexed on the id column. By setting axis=1, I specified the axis to concatenate along, with 1 pertaining to columns and 0 to index (rows). Since the id column is not sorted on df_2 I had to specify the sort= hyperparameter as well. The join= hyperparameter specifies how to handle indexes on other axis(es).
I think it is really cool that we’ve seen there are several ways to do the exact same thing. So now the question remains, which of these methods is the most computationally efficient? I included the times above, but I’ll rank them here so you don’t have to scroll back up. They’ll be ranked from fastest run time to slowest.
.merge()38 ns ± 0.369 ns per loop.concat() 38.5 ns ± 0.379 ns per loop.join() 39.2 ns ± 0.709 ns per loop.map() 2.3 ms ± 131 μs per loop
.merge()38 ns ± 0.369 ns per loop
.concat() 38.5 ns ± 0.379 ns per loop
.join() 39.2 ns ± 0.709 ns per loop
.map() 2.3 ms ± 131 μs per loop
If you ever find yourself needing to use one of these methods I hope you can reference this (or my code — if on mobile, scroll to the bottom and select “show desktop version” on the right) as a guide on how to do so. I’d love to turn this into a series where I teach you how to do more things you love doing in Excel with Python and libraries like Pandas, so let me know in the comments below what you’d like to see next. As always, thanks for reading. | [
{
"code": null,
"e": 454,
"s": 172,
"text": "So since no one has named one yet, I’ll start! One of my favorite excel formulas to date is a Match function that is nested in an Index function. But before I teach you its Pandas equivalent, let’s get some background on the INDEX/MATCH function and why it’s better than a VLOOKUP."
},
{
"code": null,
"e": 506,
"s": 454,
"text": "Two reasons why INDEX/MATCH is better than VLOOKUP:"
},
{
"code": null,
"e": 802,
"s": 506,
"text": "You can search a whole spreadsheet for values instead of being forced to only search the left-most column. (more on this below)It’s more computationally-efficient by 3% with unsorted data, by 30% with sorted data and an approximate match, and by 13% with sorted data and an exact match! (source)"
},
{
"code": null,
"e": 930,
"s": 802,
"text": "You can search a whole spreadsheet for values instead of being forced to only search the left-most column. (more on this below)"
},
{
"code": null,
"e": 1099,
"s": 930,
"text": "It’s more computationally-efficient by 3% with unsorted data, by 30% with sorted data and an approximate match, and by 13% with sorted data and an exact match! (source)"
},
{
"code": null,
"e": 1601,
"s": 1099,
"text": "By combining the INDEX/MATCH formulas, you can get around the restrictions of a VLOOKUP. In a nutshell, VLOOKUP scans the leftmost column of a given range until it lands on the first instance of a given “search_key”. It then returns the value of the cell in the index provided, which will always be to the right. But again, as I said above, with INDEX/MATCH you can search a whole spreadsheet (by column or by row) for values instead of being forced to only search the left-most column with a VLOOKUP."
},
{
"code": null,
"e": 1813,
"s": 1601,
"text": "Check out this monthly podcast dashboard I built for Recode while working as a Traffic Analyst at Vox Media to see how I leveraged a SMALL function nested in a INDEX/MATCH function to display episode-level data."
},
{
"code": null,
"e": 1878,
"s": 1813,
"text": "Now let’s move on to the fun part... how to do this with Pandas!"
},
{
"code": null,
"e": 2060,
"s": 1878,
"text": "I’ll show you four ways to code this in Python leveraging the Pandas library, but first, let’s get some context on our goal. We have two DataFrames named df_1 and df_2 (seen below)."
},
{
"code": null,
"e": 2168,
"s": 2060,
"text": "Our goal is to match the last_name column in df_2 with the correct rows in df_1 to get something like this:"
},
{
"code": null,
"e": 2275,
"s": 2168,
"text": "code: df_1[‘last_name’] = df_1.id.map(df_2.set_index(‘id’)[‘last_name’].to_dict())2.3 ms ± 131 μs per loop"
},
{
"code": null,
"e": 3086,
"s": 2275,
"text": "Here we create a new column, last_name, for df_1. The values of that new column are created by mapping the ids from df_1 to the last names in df_2 where those ids match. By calling the .to_dict() method on our series df_2.last_name we get a key : value pair of the index which would be: {0: ‘Snow’, 1: ‘Targaryen’, 2: ‘Tyrell’, 3: ‘Lannister’, 4: ‘Stark’}. In this case the .map() method would not work, as the values in our id column for df_1 do not match the keys in this dictionary. So we passed the .set_index() method first to change the index to the ids of df_2 which would give us this dictionary: {1003: ‘Snow’, 1004: ‘Targaryen’, 1005: ‘Tyrell’, 1002: ‘Lannister’, 1006: ‘Stark’}. We can now use the .map() method to map the values of our Series (id) to the corresponding values of our new dictionary."
},
{
"code": null,
"e": 3208,
"s": 3086,
"text": "A fellow data scientist, Bernard Kurka, helped me figure out this first solution. Check out some of his Medium posts too."
},
{
"code": null,
"e": 3296,
"s": 3208,
"text": "code: df_1 = df_1.set_index('id').join(df_2.set_index('id'))39.2 ns ± 0.709 ns per loop"
},
{
"code": null,
"e": 3593,
"s": 3296,
"text": "The .join() method will join columns of another DataFrame. By default it does a left join, but you can specify this by passing the how= hyperparameter and changing it to ‘right’, ‘outer’, or ‘inner’}. We needed to call the .set_index() method on df_1 and df_2 so we could join on the right index."
},
{
"code": null,
"e": 3669,
"s": 3593,
"text": "code: df_1 = df_1.merge(df_2, how='left', on='id')38 ns ± 0.369 ns per loop"
},
{
"code": null,
"e": 3873,
"s": 3669,
"text": "The .merge() method merges a DataFrame or named Series objects with a database-style join. Here I specified how I wanted it joined with how= and on what column/index by specifying the on= hyperparameter."
},
{
"code": null,
"e": 4012,
"s": 3873,
"text": "code: df_1 = pd.concat([df_1.set_index('id'), df_2.set_index('id').last_name], axis=1, sort='id', join='inner')38.5 ns ± 0.379 ns per loop"
},
{
"code": null,
"e": 4617,
"s": 4012,
"text": "The pd.concat() method concatenates pandas objects along a particular axis with optional set logic along the other axes. So here I passed the pandas objects I wanted concatenated as a list. The first being a DataFrame where I set the index to the id column and the second being a Series but also indexed on the id column. By setting axis=1, I specified the axis to concatenate along, with 1 pertaining to columns and 0 to index (rows). Since the id column is not sorted on df_2 I had to specify the sort= hyperparameter as well. The join= hyperparameter specifies how to handle indexes on other axis(es)."
},
{
"code": null,
"e": 4942,
"s": 4617,
"text": "I think it is really cool that we’ve seen there are several ways to do the exact same thing. So now the question remains, which of these methods is the most computationally efficient? I included the times above, but I’ll rank them here so you don’t have to scroll back up. They’ll be ranked from fastest run time to slowest."
},
{
"code": null,
"e": 5079,
"s": 4942,
"text": ".merge()38 ns ± 0.369 ns per loop.concat() 38.5 ns ± 0.379 ns per loop.join() 39.2 ns ± 0.709 ns per loop.map() 2.3 ms ± 131 μs per loop"
},
{
"code": null,
"e": 5113,
"s": 5079,
"text": ".merge()38 ns ± 0.369 ns per loop"
},
{
"code": null,
"e": 5151,
"s": 5113,
"text": ".concat() 38.5 ns ± 0.379 ns per loop"
},
{
"code": null,
"e": 5187,
"s": 5151,
"text": ".join() 39.2 ns ± 0.709 ns per loop"
},
{
"code": null,
"e": 5219,
"s": 5187,
"text": ".map() 2.3 ms ± 131 μs per loop"
}
] |
Combine Multiple Excel Worksheets Into a Single Pandas Dataframe - GeeksforGeeks | 05 Sep, 2020
Prerequisites: Working with excel files using Pandas
In these articles, we will discuss how to Import multiple excel sheet into a single DataFrame and save into a new excel file. Let’s suppose we have two Excel files with the same structure (Excel_1.xlsx, Excel_2.xlsx), then merge both of the sheets into a new Excel file.
Approach :
Import-Module
Read Excel file and store into a DataFrame
Concat both DataFrame into a new DataFrame
Export DataFrame into an Excel File with DataFrame.to_excel() function
Below is the implementation.
Python3
# import moduleimport pandas as pd # Read excel file# and store into a DataFramedf1 = pd.read_excel('excel_work\sample_data\Book_1.xlsx')df2 = pd.read_excel('excel_work\sample_data\Book_2.xlsx') # concat both DataFrame into a single DataFramedf = pd.concat([df1, df2]) # Export Dataframe into Excel filedf.to_excel('final_output.xlsx', index=False)
Output :
Python pandas-io
Python-pandas
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 25054,
"s": 25026,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 25107,
"s": 25054,
"text": "Prerequisites: Working with excel files using Pandas"
},
{
"code": null,
"e": 25378,
"s": 25107,
"text": "In these articles, we will discuss how to Import multiple excel sheet into a single DataFrame and save into a new excel file. Let’s suppose we have two Excel files with the same structure (Excel_1.xlsx, Excel_2.xlsx), then merge both of the sheets into a new Excel file."
},
{
"code": null,
"e": 25390,
"s": 25378,
"text": " Approach :"
},
{
"code": null,
"e": 25404,
"s": 25390,
"text": "Import-Module"
},
{
"code": null,
"e": 25447,
"s": 25404,
"text": "Read Excel file and store into a DataFrame"
},
{
"code": null,
"e": 25490,
"s": 25447,
"text": "Concat both DataFrame into a new DataFrame"
},
{
"code": null,
"e": 25561,
"s": 25490,
"text": "Export DataFrame into an Excel File with DataFrame.to_excel() function"
},
{
"code": null,
"e": 25590,
"s": 25561,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25598,
"s": 25590,
"text": "Python3"
},
{
"code": "# import moduleimport pandas as pd # Read excel file# and store into a DataFramedf1 = pd.read_excel('excel_work\\sample_data\\Book_1.xlsx')df2 = pd.read_excel('excel_work\\sample_data\\Book_2.xlsx') # concat both DataFrame into a single DataFramedf = pd.concat([df1, df2]) # Export Dataframe into Excel filedf.to_excel('final_output.xlsx', index=False)",
"e": 25950,
"s": 25598,
"text": null
},
{
"code": null,
"e": 25959,
"s": 25950,
"text": "Output :"
},
{
"code": null,
"e": 25976,
"s": 25959,
"text": "Python pandas-io"
},
{
"code": null,
"e": 25990,
"s": 25976,
"text": "Python-pandas"
},
{
"code": null,
"e": 25997,
"s": 25990,
"text": "Python"
},
{
"code": null,
"e": 26095,
"s": 25997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26113,
"s": 26095,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26148,
"s": 26113,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26170,
"s": 26148,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26202,
"s": 26170,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26232,
"s": 26202,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26274,
"s": 26232,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26300,
"s": 26274,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26337,
"s": 26300,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26380,
"s": 26337,
"text": "Python program to convert a list to string"
}
] |
Drawing an image in canvas using in JavaScript | Following is the code for drawing an image in canvas using JavaScript −
Live Demo
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
</style>
</head>
<body>
<h1>Drawing an image in canvas</h1>
<img class="flower" width="300" height="300"
src="https://i.picsum.photos/id/976/300/300.jpg?hmac=Gwae8T0kvhjbWyNIAiYgOckWbK
BHGr2p_6EEE29uDDg" />
<canvas class="canvas1" width="300" height="300" style="border: 1px solid #d3d3d3;">
</canvas><br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to draw the image in canvas</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
BtnEle.addEventListener("click", () => {
var c = document.querySelector(".canvas1");
var ctx = c.getContext("2d");
var img = document.querySelector(".flower");
ctx.drawImage(img, 10, 10);
});
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button − | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Following is the code for drawing an image in canvas using JavaScript −"
},
{
"code": null,
"e": 1145,
"s": 1134,
"text": " Live Demo"
},
{
"code": null,
"e": 2167,
"s": 1145,
"text": "<DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n</style>\n</head>\n<body>\n<h1>Drawing an image in canvas</h1>\n<img class=\"flower\" width=\"300\" height=\"300\"\n src=\"https://i.picsum.photos/id/976/300/300.jpg?hmac=Gwae8T0kvhjbWyNIAiYgOckWbK\nBHGr2p_6EEE29uDDg\" />\n<canvas class=\"canvas1\" width=\"300\" height=\"300\" style=\"border: 1px solid #d3d3d3;\">\n</canvas><br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to draw the image in canvas</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n BtnEle.addEventListener(\"click\", () => {\n var c = document.querySelector(\".canvas1\");\n var ctx = c.getContext(\"2d\");\n var img = document.querySelector(\".flower\");\n ctx.drawImage(img, 10, 10);\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2205,
"s": 2167,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
Find objects between two dates in MongoDB? | Use operator gteandlt to find objects between two dates in MongoDB. To understand these
operators, let us create a collection.
Creating a collection here:
>db.order.insert({"OrderId":1,"OrderAddrees":"US","OrderDateTime":ISODate("2019-02-19")};
WriteResult({ "nInserted" : 1 })
>db.order.insert({"OrderId":2,"OrderAddrees":"UK","OrderDateTime":ISODate("2019-02-26")};
WriteResult({ "nInserted" : 1 })
Display all documents from the collection with the help of find() method. The query is as follows:
> db.order.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6c072068174aae23f5ef57"),
"OrderId" : 1,
"OrderAddrees" : "US",
"OrderDateTime" : ISODate("2019-02-19T00:00:00Z")
}
{
"_id" : ObjectId("5c6c073568174aae23f5ef58"),
"OrderId" : 2,
"OrderAddrees" : "UK",
"OrderDateTime" : ISODate("2019-02-26T00:00:00Z")
}
Here is the query to find objects between two dates:
> db.order.find({"OrderDateTime":{ $gte:ISODate("2019-02-10"), $lt:ISODate("2019-02-21") }
}).pretty();
The following is the output:
{
"_id" : ObjectId("5c6c072068174aae23f5ef57"),
"OrderId" : 1,
"OrderAddrees" : "US",
"OrderDateTime" : ISODate("2019-02-19T00:00:00Z")
} | [
{
"code": null,
"e": 1189,
"s": 1062,
"text": "Use operator gteandlt to find objects between two dates in MongoDB. To understand these\noperators, let us create a collection."
},
{
"code": null,
"e": 1217,
"s": 1189,
"text": "Creating a collection here:"
},
{
"code": null,
"e": 1464,
"s": 1217,
"text": ">db.order.insert({\"OrderId\":1,\"OrderAddrees\":\"US\",\"OrderDateTime\":ISODate(\"2019-02-19\")};\nWriteResult({ \"nInserted\" : 1 })\n\n>db.order.insert({\"OrderId\":2,\"OrderAddrees\":\"UK\",\"OrderDateTime\":ISODate(\"2019-02-26\")};\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 1563,
"s": 1464,
"text": "Display all documents from the collection with the help of find() method. The query is as follows:"
},
{
"code": null,
"e": 1591,
"s": 1563,
"text": "> db.order.find().pretty();"
},
{
"code": null,
"e": 1620,
"s": 1591,
"text": "The following is the output:"
},
{
"code": null,
"e": 1920,
"s": 1620,
"text": "{\n \"_id\" : ObjectId(\"5c6c072068174aae23f5ef57\"),\n \"OrderId\" : 1,\n \"OrderAddrees\" : \"US\",\n \"OrderDateTime\" : ISODate(\"2019-02-19T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c6c073568174aae23f5ef58\"),\n \"OrderId\" : 2,\n \"OrderAddrees\" : \"UK\",\n \"OrderDateTime\" : ISODate(\"2019-02-26T00:00:00Z\")\n}"
},
{
"code": null,
"e": 1973,
"s": 1920,
"text": "Here is the query to find objects between two dates:"
},
{
"code": null,
"e": 2077,
"s": 1973,
"text": "> db.order.find({\"OrderDateTime\":{ $gte:ISODate(\"2019-02-10\"), $lt:ISODate(\"2019-02-21\") }\n}).pretty();"
},
{
"code": null,
"e": 2106,
"s": 2077,
"text": "The following is the output:"
},
{
"code": null,
"e": 2256,
"s": 2106,
"text": "{\n \"_id\" : ObjectId(\"5c6c072068174aae23f5ef57\"),\n \"OrderId\" : 1,\n \"OrderAddrees\" : \"US\",\n \"OrderDateTime\" : ISODate(\"2019-02-19T00:00:00Z\")\n}"
}
] |
iText - Tiling PDF Pages | The following Java program demonstrates how to tile the contents of a PDF page to different pages using the iText library. It creates a PDF document with the name tilingPdfPages.pdf and saves it in the path C:/itextExamples/.
Save this code in a file with the name TilingPDFPages.java.
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
public class TilingPDFPages {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/tilingPdfPages.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfReader
String src = "C:/itextExamples/pdfWithImage.pdf";
PdfReader reader = new PdfReader(src);
// Creating a PdfDocument objects
PdfDocument destpdf = new PdfDocument(writer);
PdfDocument srcPdf = new PdfDocument(reader);
// Opening a page from the existing PDF
PdfPage origPage = srcPdf.getPage(1);
// Getting the page size
Rectangle orig = origPage.getPageSizeWithRotation();
// Getting the size of the page
PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf);
// Tile size
Rectangle tileSize = PageSize.A4.rotate();
AffineTransform transformationMatrix =
AffineTransform.getScaleInstance(tileSize.getWidth() / orig.getWidth() *
2f, tileSize.getHeight() / orig.getHeight() * 2f);
// The first tile
PdfPage page =
destpdf.addNewPage(PageSize.A4.rotate());
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f);
// The second tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
// The third tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
// The fourth tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);
// closing the documents
destpdf.close();
srcPdf.close();
System.out.println("PDF created successfully..");
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TilingPDFPages.java
java TilingPDFPages
Upon execution, the above program creates a PDF document, displaying the following message.
PDF created successfully..
If you verify the specified path, you can find the created PDF document, as shown below −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2594,
"s": 2368,
"text": "The following Java program demonstrates how to tile the contents of a PDF page to different pages using the iText library. It creates a PDF document with the name tilingPdfPages.pdf and saves it in the path C:/itextExamples/."
},
{
"code": null,
"e": 2654,
"s": 2594,
"text": "Save this code in a file with the name TilingPDFPages.java."
},
{
"code": null,
"e": 5529,
"s": 2654,
"text": "import com.itextpdf.kernel.geom.AffineTransform; \nimport com.itextpdf.kernel.geom.PageSize; \nimport com.itextpdf.kernel.geom.Rectangle; \n\nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfPage; \nimport com.itextpdf.kernel.pdf.PdfReader; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.kernel.pdf.canvas.PdfCanvas; \nimport com.itextpdf.kernel.pdf.xobject.PdfFormXObject; \n\npublic class TilingPDFPages { \n public static void main(String args[]) throws Exception { \n // Creating a PdfWriter object \n String dest = \"C:/itextExamples/tilingPdfPages.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfReader \n String src = \"C:/itextExamples/pdfWithImage.pdf\"; \n PdfReader reader = new PdfReader(src); \n \n // Creating a PdfDocument objects \n PdfDocument destpdf = new PdfDocument(writer); \n PdfDocument srcPdf = new PdfDocument(reader); \n \n // Opening a page from the existing PDF \n PdfPage origPage = srcPdf.getPage(1); \n \n // Getting the page size \n Rectangle orig = origPage.getPageSizeWithRotation(); \n \n // Getting the size of the page \n PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf); \n \n // Tile size \n Rectangle tileSize = PageSize.A4.rotate(); \n AffineTransform transformationMatrix = \n AffineTransform.getScaleInstance(tileSize.getWidth() / orig.getWidth() * \n 2f, tileSize.getHeight() / orig.getHeight() * 2f); \n \n // The first tile \n PdfPage page = \n destpdf.addNewPage(PageSize.A4.rotate()); \n \n PdfCanvas canvas = new PdfCanvas(page); \n canvas.concatMatrix(transformationMatrix); \n canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f); \n \n // The second tile \n page = destpdf.addNewPage(PageSize.A4.rotate()); \n canvas = new PdfCanvas(page); \n canvas.concatMatrix(transformationMatrix); \n canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);\n \n // The third tile\n page = destpdf.addNewPage(PageSize.A4.rotate());\n canvas = new PdfCanvas(page);\n canvas.concatMatrix(transformationMatrix);\n canvas.addXObject(pageCopy, 0, 0); \n \n // The fourth tile\n page = destpdf.addNewPage(PageSize.A4.rotate());\n canvas = new PdfCanvas(page);\n canvas.concatMatrix(transformationMatrix);\n canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);\n \n // closing the documents\n destpdf.close();\n srcPdf.close();\n \n System.out.println(\"PDF created successfully..\");\n }\n}"
},
{
"code": null,
"e": 5624,
"s": 5529,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 5672,
"s": 5624,
"text": "javac TilingPDFPages.java \njava TilingPDFPages\n"
},
{
"code": null,
"e": 5764,
"s": 5672,
"text": "Upon execution, the above program creates a PDF document, displaying the following message."
},
{
"code": null,
"e": 5792,
"s": 5764,
"text": "PDF created successfully..\n"
},
{
"code": null,
"e": 5882,
"s": 5792,
"text": "If you verify the specified path, you can find the created PDF document, as shown below −"
},
{
"code": null,
"e": 5889,
"s": 5882,
"text": " Print"
},
{
"code": null,
"e": 5900,
"s": 5889,
"text": " Add Notes"
}
] |
How to create a sphere in R? | To create a sphere, we can use spheres3d function of rgl package. The rgl package is specifically designed to create real-time interactive 3D plots. If we want to create a sphere then we need to pass the values for the three axes and the radius of the sphere. We can also change the color of the sphere by introducing color argument inside spheres3d function.
Loading rgl package and creating a sphere:
> library(rgl)
> spheres3d(x=1,y=1,z=1,radius=1)
> spheres3d(0,0,0,radius=1,color="blue")
> spheres3d(0,0,0,radius=1,color="red") | [
{
"code": null,
"e": 1422,
"s": 1062,
"text": "To create a sphere, we can use spheres3d function of rgl package. The rgl package is specifically designed to create real-time interactive 3D plots. If we want to create a sphere then we need to pass the values for the three axes and the radius of the sphere. We can also change the color of the sphere by introducing color argument inside spheres3d function."
},
{
"code": null,
"e": 1465,
"s": 1422,
"text": "Loading rgl package and creating a sphere:"
},
{
"code": null,
"e": 1514,
"s": 1465,
"text": "> library(rgl)\n> spheres3d(x=1,y=1,z=1,radius=1)"
},
{
"code": null,
"e": 1555,
"s": 1514,
"text": "> spheres3d(0,0,0,radius=1,color=\"blue\")"
},
{
"code": null,
"e": 1595,
"s": 1555,
"text": "> spheres3d(0,0,0,radius=1,color=\"red\")"
}
] |
Binary Search Program in C | Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in a sorted form.
#include <stdio.h>
#define MAX 20
// array of items on which linear search will be conducted.
int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};
void printline(int count) {
int i;
for(i = 0;i <count-1;i++) {
printf("=");
}
printf("=\n");
}
int find(int data) {
int lowerBound = 0;
int upperBound = MAX -1;
int midPoint = -1;
int comparisons = 0;
int index = -1;
while(lowerBound <= upperBound) {
printf("Comparison %d\n" , (comparisons +1) );
printf("lowerBound : %d, intArray[%d] = %d\n",lowerBound,lowerBound,
intArray[lowerBound]);
printf("upperBound : %d, intArray[%d] = %d\n",upperBound,upperBound,
intArray[upperBound]);
comparisons++;
// compute the mid point
// midPoint = (lowerBound + upperBound) / 2;
midPoint = lowerBound + (upperBound - lowerBound) / 2;
// data found
if(intArray[midPoint] == data) {
index = midPoint;
break;
} else {
// if data is larger
if(intArray[midPoint] < data) {
// data is in upper half
lowerBound = midPoint + 1;
}
// data is smaller
else {
// data is in lower half
upperBound = midPoint -1;
}
}
}
printf("Total comparisons made: %d" , comparisons);
return index;
}
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0;i<MAX;i++) {
printf("%d ",intArray[i]);
}
printf("]\n");
}
void main() {
printf("Input Array: ");
display();
printline(50);
//find location of 1
int location = find(55);
// if element was found
if(location != -1)
printf("\nElement found at location: %d" ,(location+1));
else
printf("\nElement not found.");
}
If we compile and run the above program then it would produce following result −
Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]
==================================================
Comparison 1
lowerBound : 0, intArray[0] = 1
upperBound : 19, intArray[19] = 66
Comparison 2
lowerBound : 10, intArray[10] = 15
upperBound : 19, intArray[19] = 66
Comparison 3
lowerBound : 15, intArray[15] = 34
upperBound : 19, intArray[19] = 66
Comparison 4
lowerBound : 18, intArray[18] = 55
upperBound : 19, intArray[19] = 66
Total comparisons made: 4
Element found at location: 19
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2812,
"s": 2580,
"text": "Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in a sorted form."
},
{
"code": null,
"e": 4691,
"s": 2812,
"text": "#include <stdio.h>\n\n#define MAX 20\n\n// array of items on which linear search will be conducted. \nint intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};\n\nvoid printline(int count) {\n int i;\n\t\n for(i = 0;i <count-1;i++) {\n printf(\"=\");\n }\n\t\n printf(\"=\\n\");\n}\n\nint find(int data) {\n int lowerBound = 0;\n int upperBound = MAX -1;\n int midPoint = -1;\n int comparisons = 0; \n int index = -1;\n\t\n while(lowerBound <= upperBound) {\n printf(\"Comparison %d\\n\" , (comparisons +1) );\n printf(\"lowerBound : %d, intArray[%d] = %d\\n\",lowerBound,lowerBound,\n intArray[lowerBound]);\n printf(\"upperBound : %d, intArray[%d] = %d\\n\",upperBound,upperBound,\n intArray[upperBound]);\n comparisons++;\n\t\t\n // compute the mid point\n // midPoint = (lowerBound + upperBound) / 2;\n midPoint = lowerBound + (upperBound - lowerBound) / 2;\t\n\t\t\n // data found\n if(intArray[midPoint] == data) {\n index = midPoint;\n break;\n } else {\n // if data is larger \n if(intArray[midPoint] < data) {\n // data is in upper half\n lowerBound = midPoint + 1;\n }\n // data is smaller \n else {\n // data is in lower half \n upperBound = midPoint -1;\n }\n } \n }\n printf(\"Total comparisons made: %d\" , comparisons);\n return index;\n}\n\nvoid display() {\n int i;\n printf(\"[\");\n\t\n // navigate through all items \n for(i = 0;i<MAX;i++) {\n printf(\"%d \",intArray[i]);\n }\n\t\n printf(\"]\\n\");\n}\n\nvoid main() {\n printf(\"Input Array: \");\n display();\n printline(50);\n\t\n //find location of 1\n int location = find(55);\n\n // if element was found \n if(location != -1)\n printf(\"\\nElement found at location: %d\" ,(location+1));\n else\n printf(\"\\nElement not found.\");\n}"
},
{
"code": null,
"e": 4772,
"s": 4691,
"text": "If we compile and run the above program then it would produce following result −"
},
{
"code": null,
"e": 5278,
"s": 4772,
"text": "Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]\n==================================================\nComparison 1\nlowerBound : 0, intArray[0] = 1\nupperBound : 19, intArray[19] = 66\nComparison 2\nlowerBound : 10, intArray[10] = 15\nupperBound : 19, intArray[19] = 66\nComparison 3\nlowerBound : 15, intArray[15] = 34\nupperBound : 19, intArray[19] = 66\nComparison 4\nlowerBound : 18, intArray[18] = 55\nupperBound : 19, intArray[19] = 66\nTotal comparisons made: 4\nElement found at location: 19\n"
},
{
"code": null,
"e": 5313,
"s": 5278,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5325,
"s": 5313,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 5360,
"s": 5325,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5379,
"s": 5360,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5414,
"s": 5379,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5429,
"s": 5414,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5462,
"s": 5429,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5481,
"s": 5462,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5515,
"s": 5481,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5543,
"s": 5515,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5579,
"s": 5543,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5607,
"s": 5579,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5614,
"s": 5607,
"text": " Print"
},
{
"code": null,
"e": 5625,
"s": 5614,
"text": " Add Notes"
}
] |
Python Group by matching second tuple value in list of tuples | In this tutorial, we are going to write a program that groups all the tuples from a list that have same element as a second element. Let's see an example to understand it clearly.
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React',
'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
We have to group the tuples from the list. Let's see the steps to solve the problem.
Initiate a list with required tuples.
Create an empty dictionary.
Iterate through the list of tuples.Check if the second element of the tuple is already present in the dictionary or not.If it already present, then append the current tuple to its list.Else initialize the key with a list with the current tuple.
Check if the second element of the tuple is already present in the dictionary or not.
If it already present, then append the current tuple to its list.
Else initialize the key with a list with the current tuple.
At the end, you will get a dictionary with the required modifications.
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict
result = {}
# iterating over the list of tuples
for tup in tuples:
# checking the tuple element in the dict
if tup[1] in result:
# add the current tuple to dict
result[tup[1]].append(tup)
else:
# initiate the key with list
result[tup[1]] = [tup]
# priting the result
print(result)
If you run the above code, then you will get the following result.
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}
We skip the if condition in the above program using defaultdict. Let's solve it using the defaultdict.
# importing defaultdict from collections
from collections import defaultdict
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict with defaultdict
result = defaultdict(list)
# iterating over the list of tuples
for tup in tuples:
result[tup[1]].append(tup)
# priting the result
print(dict(result))
If you run the above code, then you will get the following result.
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}
You can solve it different in ways as you like. We have seen two ways here. If you have any doubts in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "In this tutorial, we are going to write a program that groups all the tuples from a list that have same element as a second element. Let's see an example to understand it clearly."
},
{
"code": null,
"e": 1404,
"s": 1242,
"text": "[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React',\n'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]"
},
{
"code": null,
"e": 1597,
"s": 1404,
"text": "{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],\n'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}"
},
{
"code": null,
"e": 1682,
"s": 1597,
"text": "We have to group the tuples from the list. Let's see the steps to solve the problem."
},
{
"code": null,
"e": 1720,
"s": 1682,
"text": "Initiate a list with required tuples."
},
{
"code": null,
"e": 1748,
"s": 1720,
"text": "Create an empty dictionary."
},
{
"code": null,
"e": 1993,
"s": 1748,
"text": "Iterate through the list of tuples.Check if the second element of the tuple is already present in the dictionary or not.If it already present, then append the current tuple to its list.Else initialize the key with a list with the current tuple."
},
{
"code": null,
"e": 2079,
"s": 1993,
"text": "Check if the second element of the tuple is already present in the dictionary or not."
},
{
"code": null,
"e": 2145,
"s": 2079,
"text": "If it already present, then append the current tuple to its list."
},
{
"code": null,
"e": 2205,
"s": 2145,
"text": "Else initialize the key with a list with the current tuple."
},
{
"code": null,
"e": 2276,
"s": 2205,
"text": "At the end, you will get a dictionary with the required modifications."
},
{
"code": null,
"e": 2808,
"s": 2276,
"text": "# initializing the list with tuples\ntuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't\nialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe\nr')]\n# empty dict\nresult = {}\n# iterating over the list of tuples\nfor tup in tuples:\n # checking the tuple element in the dict\n if tup[1] in result:\n # add the current tuple to dict\n result[tup[1]].append(tup)\n else:\n # initiate the key with list\n result[tup[1]] = [tup]\n# priting the result\nprint(result)"
},
{
"code": null,
"e": 2875,
"s": 2808,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3067,
"s": 2875,
"text": "{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints\n('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other\n'), ('Business', 'other')]}"
},
{
"code": null,
"e": 3170,
"s": 3067,
"text": "We skip the if condition in the above program using defaultdict. Let's solve it using the defaultdict."
},
{
"code": null,
"e": 3641,
"s": 3170,
"text": "# importing defaultdict from collections\nfrom collections import defaultdict\n# initializing the list with tuples\ntuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't\nialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe\nr')]\n# empty dict with defaultdict\nresult = defaultdict(list)\n# iterating over the list of tuples\nfor tup in tuples:\n result[tup[1]].append(tup)\n # priting the result\n print(dict(result))"
},
{
"code": null,
"e": 3708,
"s": 3641,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3900,
"s": 3708,
"text": "{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints\n('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other\n'), ('Business', 'other')]}"
},
{
"code": null,
"e": 4053,
"s": 3900,
"text": "You can solve it different in ways as you like. We have seen two ways here. If you have any doubts in the tutorial, mention them in the comment section."
}
] |
MySQL query to return all records with a datetime older than 1 week | To get dates older than 1 week, you can use the following syntax −
select *from yourTableName where yourColumnName < now() - interval 1 week;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table DatesOfOneWeek
−> (
−> ArrivalTime datetime
−> );
Query OK, 0 rows affected (0.87 sec)
Insert some records in the table −
mysql> insert into DatesOfOneWeek values(date_add(now(),interval 2 week));
Query OK, 1 row affected (0.11 sec)
mysql> insert into DatesOfOneWeek values('2018-11-04');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DatesOfOneWeek values('2018-11-25');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DatesOfOneWeek values(date_add(now(),interval -1 week));
Query OK, 1 row affected (0.14 sec)
mysql> insert into DatesOfOneWeek values(date_add(now(),interval 1 week));
Query OK, 1 row affected (0.11 sec)
Let us check the records which we have inserted above are present or not. The query to display all records from the table is as follows −
mysql> select *from DatesOfOneWeek;
The following is the output −
+---------------------+
| ArrivalTime |
+---------------------+
| 2018-12-20 18:11:02 |
| 2018-11-04 00:00:00 |
| 2018-11-25 00:00:00 |
| 2018-11-29 18:11:40 |
| 2018-12-13 18:11:46 |
+---------------------+
5 rows in set (0.00 sec)
Here is the MySQL query to get a date which was in the past i.e. all the date before 1 week −
mysql> select *from DatesOfOneWeek where ArrivalTime < now() - interval 1 week;
The following is the output −
+---------------------+
| ArrivalTime |
+---------------------+
| 2018-11-04 00:00:00 |
| 2018-11-25 00:00:00 |
| 2018-11-29 18:11:40 |
+---------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To get dates older than 1 week, you can use the following syntax −"
},
{
"code": null,
"e": 1204,
"s": 1129,
"text": "select *from yourTableName where yourColumnName < now() - interval 1 week;"
},
{
"code": null,
"e": 1304,
"s": 1204,
"text": "To understand the above concept, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1420,
"s": 1304,
"text": "mysql> create table DatesOfOneWeek\n −> (\n −> ArrivalTime datetime\n −> );\nQuery OK, 0 rows affected (0.87 sec)"
},
{
"code": null,
"e": 1455,
"s": 1420,
"text": "Insert some records in the table −"
},
{
"code": null,
"e": 1977,
"s": 1455,
"text": "mysql> insert into DatesOfOneWeek values(date_add(now(),interval 2 week));\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DatesOfOneWeek values('2018-11-04');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DatesOfOneWeek values('2018-11-25');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DatesOfOneWeek values(date_add(now(),interval -1 week));\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DatesOfOneWeek values(date_add(now(),interval 1 week));\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 2115,
"s": 1977,
"text": "Let us check the records which we have inserted above are present or not. The query to display all records from the table is as follows −"
},
{
"code": null,
"e": 2151,
"s": 2115,
"text": "mysql> select *from DatesOfOneWeek;"
},
{
"code": null,
"e": 2181,
"s": 2151,
"text": "The following is the output −"
},
{
"code": null,
"e": 2422,
"s": 2181,
"text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2018-12-20 18:11:02 |\n| 2018-11-04 00:00:00 |\n| 2018-11-25 00:00:00 |\n| 2018-11-29 18:11:40 |\n| 2018-12-13 18:11:46 |\n+---------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2516,
"s": 2422,
"text": "Here is the MySQL query to get a date which was in the past i.e. all the date before 1 week −"
},
{
"code": null,
"e": 2596,
"s": 2516,
"text": "mysql> select *from DatesOfOneWeek where ArrivalTime < now() - interval 1 week;"
},
{
"code": null,
"e": 2626,
"s": 2596,
"text": "The following is the output −"
},
{
"code": null,
"e": 2819,
"s": 2626,
"text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2018-11-04 00:00:00 |\n| 2018-11-25 00:00:00 |\n| 2018-11-29 18:11:40 |\n+---------------------+\n3 rows in set (0.00 sec)"
}
] |
jQuery - Widget AutoComplete | The Widget AutoComplete function can be used with widgets in JqueryUI.The Autocomplete widgets provides suggestions while you type into the field.For suppose give Ja as an input, it will provides an output as Java or JavaScript.
Here is the simple syntax to use Autocomplete −
$( "#tags" ).autocomplete({
source: availableTags
});
Following is a simple example showing the usage of Autocomplete −
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel = "stylesheet"
href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
</script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class = "ui-widget">
<label for = "tags">Tags: </label>
<input id = "tags">
</div>
</body>
</html>
This will produce following result −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2551,
"s": 2322,
"text": "The Widget AutoComplete function can be used with widgets in JqueryUI.The Autocomplete widgets provides suggestions while you type into the field.For suppose give Ja as an input, it will provides an output as Java or JavaScript."
},
{
"code": null,
"e": 2599,
"s": 2551,
"text": "Here is the simple syntax to use Autocomplete −"
},
{
"code": null,
"e": 2657,
"s": 2599,
"text": "$( \"#tags\" ).autocomplete({\n source: availableTags\n});\n"
},
{
"code": null,
"e": 2723,
"s": 2657,
"text": "Following is a simple example showing the usage of Autocomplete −"
},
{
"code": null,
"e": 4202,
"s": 2723,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete - Default functionality</title>\n\t\t\n <link rel = \"stylesheet\" \n href = \"//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\">\n\t\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n \n <script>\n $(function() {\n var availableTags = [\n \"ActionScript\",\n \"AppleScript\",\n \"Asp\",\n \"BASIC\",\n \"C\",\n \"C++\",\n \"Clojure\",\n \"COBOL\",\n \"ColdFusion\",\n \"Erlang\",\n \"Fortran\",\n \"Groovy\",\n \"Haskell\",\n \"Java\",\n \"JavaScript\",\n \"Lisp\",\n \"Perl\",\n \"PHP\",\n \"Python\",\n \"Ruby\",\n \"Scala\",\n \"Scheme\"\n ];\n\t\t\t\t\n $( \"#tags\" ).autocomplete({\n source: availableTags\n });\n\t\t\t\t\n });\n </script>\n </head>\n\n <body>\n <div class = \"ui-widget\">\n <label for = \"tags\">Tags: </label>\n <input id = \"tags\">\n </div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4239,
"s": 4202,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4272,
"s": 4239,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4286,
"s": 4272,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4321,
"s": 4286,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4335,
"s": 4321,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4370,
"s": 4335,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4387,
"s": 4370,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4420,
"s": 4387,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4448,
"s": 4420,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4481,
"s": 4448,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4502,
"s": 4481,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4534,
"s": 4502,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4551,
"s": 4534,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4558,
"s": 4551,
"text": " Print"
},
{
"code": null,
"e": 4569,
"s": 4558,
"text": " Add Notes"
}
] |
Least number to be added to or subtracted from N to make it a Perfect Square - GeeksforGeeks | 20 May, 2021
Given a number N, find the minimum number that needs to be added to or subtracted from N, to make it a perfect square. If the number is to be added, print it with a + sign, else if the number is to be subtracted, print it with a – sign.
Examples:
Input: N = 14 Output: 2 Nearest perfect square before 14 = 9 Nearest perfect square after 14 = 16 Therefore, 2 needs to be added to 14 to get the closest perfect square.
Input: N = 18 Output: -2 Nearest perfect square before 18 = 16 Nearest perfect square after 18 = 25 Therefore, 2 needs to be subtracted from 18 to get the closest perfect square.
Approach:
Get the number.Find the square root of the number and convert the result as an integer.After converting the double value to an integer, it will contain the root of the perfect square above N, i.e. floor(square root(N)).Then find the square of this number, which will be the perfect square before N.Find the root of the perfect square after N, i.e. the ceil(square root(N)).Then find the square of this number, which will be the perfect square after N.Check whether the square of floor value is nearest to N or the ceil value.If the square of floor value is nearest to N, print the difference with a -sign. Else print the difference between the square of the ceil value and N with a + sign.
Get the number.
Find the square root of the number and convert the result as an integer.
After converting the double value to an integer, it will contain the root of the perfect square above N, i.e. floor(square root(N)).
Then find the square of this number, which will be the perfect square before N.
Find the root of the perfect square after N, i.e. the ceil(square root(N)).
Then find the square of this number, which will be the perfect square after N.
Check whether the square of floor value is nearest to N or the ceil value.
If the square of floor value is nearest to N, print the difference with a -sign. Else print the difference between the square of the ceil value and N with a + sign.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the Least numberint nearest(int n){ // Get the perfect square // before and after N int prevSquare = sqrt(n); int nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N int ans = (n - prevSquare) < (nextSquare - n) ? (prevSquare - n) : (nextSquare - n); // return the result return ans;} // Driver codeint main(){ int n = 14; cout << nearest(n) << endl; n = 16; cout << nearest(n) << endl; n = 18; cout << nearest(n) << endl; return 0;}
// Java implementation of the approachclass GFG { // Function to return the Least number static int nearest(int n) { // Get the perfect square // before and after N int prevSquare = (int)Math.sqrt(n); int nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N int ans = (n - prevSquare) < (nextSquare - n)? (prevSquare - n): (nextSquare - n); // return the result return ans; } // Driver code public static void main (String[] args) { int n = 14; System.out.println(nearest(n)); n = 16; System.out.println(nearest(n)) ; n = 18; System.out.println(nearest(n)) ; }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachfrom math import sqrt # Function to return the Least numberdef nearest(n) : # Get the perfect square # before and after N prevSquare = int(sqrt(n)); nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; # Check which is nearest to N ans = (prevSquare - n) if (n - prevSquare) < (nextSquare - n) else (nextSquare - n); # return the result return ans; # Driver codeif __name__ == "__main__" : n = 14; print(nearest(n)) ; n = 16; print(nearest(n)); n = 18; print(nearest(n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG { // Function to return the Least number static int nearest(int n) { // Get the perfect square // before and after N int prevSquare = (int)Math.Sqrt(n); int nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N int ans = (n - prevSquare) < (nextSquare - n)? (prevSquare - n): (nextSquare - n); // return the result return ans; } // Driver code public static void Main (string[] args) { int n = 14; Console.WriteLine(nearest(n)); n = 16; Console.WriteLine(nearest(n)) ; n = 18; Console.WriteLine(nearest(n)) ; }} // This code is contributed by AnkitRai01
<script>// Javascript implementation of the above approach // Function to return the Least numberfunction nearest( n){ // Get the perfect square // before and after N var prevSquare = parseInt(Math.sqrt(n)); var nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N if((n - prevSquare) < (nextSquare - n)) { ans = parseInt((prevSquare - n)); } else ans = parseInt((nextSquare - n)); // return the result return ans;} var n = 14;document.write( nearest(n) + "<br>"); n = 16;document.write( nearest(n) + "<br>"); n = 18;document.write( nearest(n) + "<br>"); // This code is contributed by SoumikMondal</script>
2
0
-2
ankthon
SoumikMondal
maths-perfect-square
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Fizz Buzz Implementation
Program to print prime numbers from 1 to N.
Find all pairs in an Array in sorted order with minimum absolute difference
Modular multiplicative inverse
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 24929,
"s": 24692,
"text": "Given a number N, find the minimum number that needs to be added to or subtracted from N, to make it a perfect square. If the number is to be added, print it with a + sign, else if the number is to be subtracted, print it with a – sign."
},
{
"code": null,
"e": 24941,
"s": 24929,
"text": "Examples: "
},
{
"code": null,
"e": 25111,
"s": 24941,
"text": "Input: N = 14 Output: 2 Nearest perfect square before 14 = 9 Nearest perfect square after 14 = 16 Therefore, 2 needs to be added to 14 to get the closest perfect square."
},
{
"code": null,
"e": 25292,
"s": 25111,
"text": "Input: N = 18 Output: -2 Nearest perfect square before 18 = 16 Nearest perfect square after 18 = 25 Therefore, 2 needs to be subtracted from 18 to get the closest perfect square. "
},
{
"code": null,
"e": 25304,
"s": 25292,
"text": "Approach: "
},
{
"code": null,
"e": 25994,
"s": 25304,
"text": "Get the number.Find the square root of the number and convert the result as an integer.After converting the double value to an integer, it will contain the root of the perfect square above N, i.e. floor(square root(N)).Then find the square of this number, which will be the perfect square before N.Find the root of the perfect square after N, i.e. the ceil(square root(N)).Then find the square of this number, which will be the perfect square after N.Check whether the square of floor value is nearest to N or the ceil value.If the square of floor value is nearest to N, print the difference with a -sign. Else print the difference between the square of the ceil value and N with a + sign."
},
{
"code": null,
"e": 26010,
"s": 25994,
"text": "Get the number."
},
{
"code": null,
"e": 26083,
"s": 26010,
"text": "Find the square root of the number and convert the result as an integer."
},
{
"code": null,
"e": 26216,
"s": 26083,
"text": "After converting the double value to an integer, it will contain the root of the perfect square above N, i.e. floor(square root(N))."
},
{
"code": null,
"e": 26296,
"s": 26216,
"text": "Then find the square of this number, which will be the perfect square before N."
},
{
"code": null,
"e": 26372,
"s": 26296,
"text": "Find the root of the perfect square after N, i.e. the ceil(square root(N))."
},
{
"code": null,
"e": 26451,
"s": 26372,
"text": "Then find the square of this number, which will be the perfect square after N."
},
{
"code": null,
"e": 26526,
"s": 26451,
"text": "Check whether the square of floor value is nearest to N or the ceil value."
},
{
"code": null,
"e": 26691,
"s": 26526,
"text": "If the square of floor value is nearest to N, print the difference with a -sign. Else print the difference between the square of the ceil value and N with a + sign."
},
{
"code": null,
"e": 26743,
"s": 26691,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26747,
"s": 26743,
"text": "C++"
},
{
"code": null,
"e": 26752,
"s": 26747,
"text": "Java"
},
{
"code": null,
"e": 26760,
"s": 26752,
"text": "Python3"
},
{
"code": null,
"e": 26763,
"s": 26760,
"text": "C#"
},
{
"code": null,
"e": 26774,
"s": 26763,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the Least numberint nearest(int n){ // Get the perfect square // before and after N int prevSquare = sqrt(n); int nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N int ans = (n - prevSquare) < (nextSquare - n) ? (prevSquare - n) : (nextSquare - n); // return the result return ans;} // Driver codeint main(){ int n = 14; cout << nearest(n) << endl; n = 16; cout << nearest(n) << endl; n = 18; cout << nearest(n) << endl; return 0;}",
"e": 27487,
"s": 26774,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the Least number static int nearest(int n) { // Get the perfect square // before and after N int prevSquare = (int)Math.sqrt(n); int nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N int ans = (n - prevSquare) < (nextSquare - n)? (prevSquare - n): (nextSquare - n); // return the result return ans; } // Driver code public static void main (String[] args) { int n = 14; System.out.println(nearest(n)); n = 16; System.out.println(nearest(n)) ; n = 18; System.out.println(nearest(n)) ; }} // This code is contributed by AnkitRai01",
"e": 28354,
"s": 27487,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom math import sqrt # Function to return the Least numberdef nearest(n) : # Get the perfect square # before and after N prevSquare = int(sqrt(n)); nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; # Check which is nearest to N ans = (prevSquare - n) if (n - prevSquare) < (nextSquare - n) else (nextSquare - n); # return the result return ans; # Driver codeif __name__ == \"__main__\" : n = 14; print(nearest(n)) ; n = 16; print(nearest(n)); n = 18; print(nearest(n)); # This code is contributed by AnkitRai01",
"e": 29016,
"s": 28354,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to return the Least number static int nearest(int n) { // Get the perfect square // before and after N int prevSquare = (int)Math.Sqrt(n); int nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N int ans = (n - prevSquare) < (nextSquare - n)? (prevSquare - n): (nextSquare - n); // return the result return ans; } // Driver code public static void Main (string[] args) { int n = 14; Console.WriteLine(nearest(n)); n = 16; Console.WriteLine(nearest(n)) ; n = 18; Console.WriteLine(nearest(n)) ; }} // This code is contributed by AnkitRai01",
"e": 29892,
"s": 29016,
"text": null
},
{
"code": "<script>// Javascript implementation of the above approach // Function to return the Least numberfunction nearest( n){ // Get the perfect square // before and after N var prevSquare = parseInt(Math.sqrt(n)); var nextSquare = prevSquare + 1; prevSquare = prevSquare * prevSquare; nextSquare = nextSquare * nextSquare; // Check which is nearest to N if((n - prevSquare) < (nextSquare - n)) { ans = parseInt((prevSquare - n)); } else ans = parseInt((nextSquare - n)); // return the result return ans;} var n = 14;document.write( nearest(n) + \"<br>\"); n = 16;document.write( nearest(n) + \"<br>\"); n = 18;document.write( nearest(n) + \"<br>\"); // This code is contributed by SoumikMondal</script>",
"e": 30646,
"s": 29892,
"text": null
},
{
"code": null,
"e": 30653,
"s": 30646,
"text": "2\n0\n-2"
},
{
"code": null,
"e": 30663,
"s": 30655,
"text": "ankthon"
},
{
"code": null,
"e": 30676,
"s": 30663,
"text": "SoumikMondal"
},
{
"code": null,
"e": 30697,
"s": 30676,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 30710,
"s": 30697,
"text": "Mathematical"
},
{
"code": null,
"e": 30729,
"s": 30710,
"text": "School Programming"
},
{
"code": null,
"e": 30742,
"s": 30729,
"text": "Mathematical"
},
{
"code": null,
"e": 30840,
"s": 30742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30872,
"s": 30840,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30897,
"s": 30872,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30941,
"s": 30897,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31017,
"s": 30941,
"text": "Find all pairs in an Array in sorted order with minimum absolute difference"
},
{
"code": null,
"e": 31048,
"s": 31017,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31066,
"s": 31048,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31082,
"s": 31066,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 31101,
"s": 31082,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31126,
"s": 31101,
"text": "Reverse a string in Java"
}
] |
Data normalization in machine learning | by Mahbubul Alam | Towards Data Science | I wrote about cluster analysis in the previous article (Clustering: concepts, tools and algorithms), where I had a short discussion on data normalization. I touched upon how data normalization impacts clustering, and unsupervised algorithms generally.
But I felt that I missed the opportunity to go into more details. But of course, that wasn’t the focus of that article, so today I want to pick up on that.
Let’s first define what exactly is normalization.
Let’s say we have a dataset containing two variables: time traveled and distance covered. Time is measured in hours (e.g. 5, 10, 25 hours ) and distance in miles (e.g. 500, 800, 1200 miles). Do you see the problem?
One obvious problem of course is that these two variables are measured in two different units — one in hours and the other in miles. The other problem — which is not obvious but if you take a closer look you'll find it — is the distribution of data, which is quite different in these two variables (both within and between variables).
The purpose of normalization is to transform data in a way that they are either dimensionless and/or have similar distributions. This process of normalization is known by other names such as standardization, feature scaling etc. Normalization is an essential step in data pre-processing in any machine learning application and model fitting.
Now the question is how (on earth) exactly does this transformation help?
The short answer is — it dramatically improves model accuracy.
Normalization gives equal weights/importance to each variable so that no single variable steers model performance in one direction just because they are bigger numbers.
As an example, clustering algorithms use distance measures to determine if an observation should belong to a certain cluster. “Euclidean distance” is often used to measure those distances. If a variable has significantly higher values, it can dominate distance measures, suppressing other variables with small values.
Several methods are applied for normalization, three popular and widely used techniques are as follows:
Rescaling: also known as “min-max normalization”, it is the simplest of all methods and calculated as:
Mean normalization: This method uses the mean of the observations in the transformation process:
Z-score normalization: Also known as standardization, this technic uses Z-score or “standard score”. It is widely used in machine learning algorithms such as SVM and logistic regression:
Here, z is the standard score, μ is the population mean and ϭ is the population standard deviation.
Let’s do an experiment, it’s always good to see an algorithm in action. The example is not going to be dramatic, I’m just showing it as an illustration to give an intuition.
Let’s import some libraries — pandas for data wrangling, matplotlib for visualization and preprocessing and KMeans from the sklearn library.
Let’s also import data from a GitHub repo as a csv file. That’s the Iris dataset, already cleaned, so you can import and follow along right away.
I’m going to use two features — petal_length and sepal_length — for clustering of data points.
# importing librariesimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn import preprocessingfrom sklearn.cluster import KMeans# importing **cleaned** datadf=pd.read_csv("iris.csv")# feature selectiondf = df[["petal_length", "sepal_length"]]
After importing libraries and data, first we’ll implement the KMeans clustering algorithm without normalization. I’ve annotated each line of code so you know what’s going on.
# inputs (NOT normalized)X_not_norm = df.values# instantiate modelmodel = KMeans(n_clusters = 3)# fit predicty_model = model.fit_predict(X_not_norm)# visualizing clustersplt.scatter(X_not_norm[:,0], X_not_norm[:,1], c=model.labels_, cmap='viridis')# counts per clusterprint("Value Counts")print(pd.value_counts(y_model))
The outputs are the count of data points in each cluster and the visualization of those clusters.
Now let’s re-run the model, this time after normalizing the inputs using preprocessing from the sklearn library.
# normalizing inputsX_norm = preprocessing.scale(df)# instantiate modelmodel = KMeans(n_clusters = 3)# fit predicty_model = model.fit_predict(X_norm)print("Value Counts")print(pd.value_counts(y_model))# visualize clustersplt.scatter(X_norm[:,0], X_norm[:,1], c=model.labels_, cmap='viridis')
In the following are the outputs before and after the normalization of data. First, if you compare the value counts there are some changes — for example, counts cluster 0 is reduced by 4 members.
If you closely examine the data points in the left and the right figures you might be able to see which data points shifted from pre-normalized to post-normalized model. These changes are often at the boundaries rather than at either end of the spectrum in the distribution. Again, as I said, it’s not too dramatic, but you get the point.
So far we’ve got the impression that normalization is absolutely a great thing to happen in data science! Not really, it does some good things but creates some bad side effects along the way.
Normalization compresses data within a certain range, reduces the variance and applies equal weights to all features. You lose a lot of important information in the process.
One example is what happens to outliers — normalization lease absolutely no traces of outliers. We perceive outliers as bad guys and we need to get rid of them ASAP. But remember, outliers are real data points, once you lose that just to get a better model, you lose information.
In the process of normalization, the variables lose their units of measurements too. So at the end of modeling, you can’t really tell what are the key differences between the variables.
I hope this was a useful article. If you have comments feel free to write them down below. You can follow me on Medium, Twitter or LinkedIn. | [
{
"code": null,
"e": 424,
"s": 172,
"text": "I wrote about cluster analysis in the previous article (Clustering: concepts, tools and algorithms), where I had a short discussion on data normalization. I touched upon how data normalization impacts clustering, and unsupervised algorithms generally."
},
{
"code": null,
"e": 580,
"s": 424,
"text": "But I felt that I missed the opportunity to go into more details. But of course, that wasn’t the focus of that article, so today I want to pick up on that."
},
{
"code": null,
"e": 630,
"s": 580,
"text": "Let’s first define what exactly is normalization."
},
{
"code": null,
"e": 845,
"s": 630,
"text": "Let’s say we have a dataset containing two variables: time traveled and distance covered. Time is measured in hours (e.g. 5, 10, 25 hours ) and distance in miles (e.g. 500, 800, 1200 miles). Do you see the problem?"
},
{
"code": null,
"e": 1180,
"s": 845,
"text": "One obvious problem of course is that these two variables are measured in two different units — one in hours and the other in miles. The other problem — which is not obvious but if you take a closer look you'll find it — is the distribution of data, which is quite different in these two variables (both within and between variables)."
},
{
"code": null,
"e": 1522,
"s": 1180,
"text": "The purpose of normalization is to transform data in a way that they are either dimensionless and/or have similar distributions. This process of normalization is known by other names such as standardization, feature scaling etc. Normalization is an essential step in data pre-processing in any machine learning application and model fitting."
},
{
"code": null,
"e": 1596,
"s": 1522,
"text": "Now the question is how (on earth) exactly does this transformation help?"
},
{
"code": null,
"e": 1659,
"s": 1596,
"text": "The short answer is — it dramatically improves model accuracy."
},
{
"code": null,
"e": 1828,
"s": 1659,
"text": "Normalization gives equal weights/importance to each variable so that no single variable steers model performance in one direction just because they are bigger numbers."
},
{
"code": null,
"e": 2146,
"s": 1828,
"text": "As an example, clustering algorithms use distance measures to determine if an observation should belong to a certain cluster. “Euclidean distance” is often used to measure those distances. If a variable has significantly higher values, it can dominate distance measures, suppressing other variables with small values."
},
{
"code": null,
"e": 2250,
"s": 2146,
"text": "Several methods are applied for normalization, three popular and widely used techniques are as follows:"
},
{
"code": null,
"e": 2353,
"s": 2250,
"text": "Rescaling: also known as “min-max normalization”, it is the simplest of all methods and calculated as:"
},
{
"code": null,
"e": 2450,
"s": 2353,
"text": "Mean normalization: This method uses the mean of the observations in the transformation process:"
},
{
"code": null,
"e": 2637,
"s": 2450,
"text": "Z-score normalization: Also known as standardization, this technic uses Z-score or “standard score”. It is widely used in machine learning algorithms such as SVM and logistic regression:"
},
{
"code": null,
"e": 2737,
"s": 2637,
"text": "Here, z is the standard score, μ is the population mean and ϭ is the population standard deviation."
},
{
"code": null,
"e": 2911,
"s": 2737,
"text": "Let’s do an experiment, it’s always good to see an algorithm in action. The example is not going to be dramatic, I’m just showing it as an illustration to give an intuition."
},
{
"code": null,
"e": 3052,
"s": 2911,
"text": "Let’s import some libraries — pandas for data wrangling, matplotlib for visualization and preprocessing and KMeans from the sklearn library."
},
{
"code": null,
"e": 3198,
"s": 3052,
"text": "Let’s also import data from a GitHub repo as a csv file. That’s the Iris dataset, already cleaned, so you can import and follow along right away."
},
{
"code": null,
"e": 3293,
"s": 3198,
"text": "I’m going to use two features — petal_length and sepal_length — for clustering of data points."
},
{
"code": null,
"e": 3546,
"s": 3293,
"text": "# importing librariesimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn import preprocessingfrom sklearn.cluster import KMeans# importing **cleaned** datadf=pd.read_csv(\"iris.csv\")# feature selectiondf = df[[\"petal_length\", \"sepal_length\"]]"
},
{
"code": null,
"e": 3721,
"s": 3546,
"text": "After importing libraries and data, first we’ll implement the KMeans clustering algorithm without normalization. I’ve annotated each line of code so you know what’s going on."
},
{
"code": null,
"e": 4042,
"s": 3721,
"text": "# inputs (NOT normalized)X_not_norm = df.values# instantiate modelmodel = KMeans(n_clusters = 3)# fit predicty_model = model.fit_predict(X_not_norm)# visualizing clustersplt.scatter(X_not_norm[:,0], X_not_norm[:,1], c=model.labels_, cmap='viridis')# counts per clusterprint(\"Value Counts\")print(pd.value_counts(y_model))"
},
{
"code": null,
"e": 4140,
"s": 4042,
"text": "The outputs are the count of data points in each cluster and the visualization of those clusters."
},
{
"code": null,
"e": 4253,
"s": 4140,
"text": "Now let’s re-run the model, this time after normalizing the inputs using preprocessing from the sklearn library."
},
{
"code": null,
"e": 4545,
"s": 4253,
"text": "# normalizing inputsX_norm = preprocessing.scale(df)# instantiate modelmodel = KMeans(n_clusters = 3)# fit predicty_model = model.fit_predict(X_norm)print(\"Value Counts\")print(pd.value_counts(y_model))# visualize clustersplt.scatter(X_norm[:,0], X_norm[:,1], c=model.labels_, cmap='viridis')"
},
{
"code": null,
"e": 4741,
"s": 4545,
"text": "In the following are the outputs before and after the normalization of data. First, if you compare the value counts there are some changes — for example, counts cluster 0 is reduced by 4 members."
},
{
"code": null,
"e": 5080,
"s": 4741,
"text": "If you closely examine the data points in the left and the right figures you might be able to see which data points shifted from pre-normalized to post-normalized model. These changes are often at the boundaries rather than at either end of the spectrum in the distribution. Again, as I said, it’s not too dramatic, but you get the point."
},
{
"code": null,
"e": 5272,
"s": 5080,
"text": "So far we’ve got the impression that normalization is absolutely a great thing to happen in data science! Not really, it does some good things but creates some bad side effects along the way."
},
{
"code": null,
"e": 5446,
"s": 5272,
"text": "Normalization compresses data within a certain range, reduces the variance and applies equal weights to all features. You lose a lot of important information in the process."
},
{
"code": null,
"e": 5726,
"s": 5446,
"text": "One example is what happens to outliers — normalization lease absolutely no traces of outliers. We perceive outliers as bad guys and we need to get rid of them ASAP. But remember, outliers are real data points, once you lose that just to get a better model, you lose information."
},
{
"code": null,
"e": 5912,
"s": 5726,
"text": "In the process of normalization, the variables lose their units of measurements too. So at the end of modeling, you can’t really tell what are the key differences between the variables."
}
] |
Instant query() Method in Java with Examples - GeeksforGeeks | 08 Jan, 2019
query() method of an Instant class used to query this instant using the specified query as parameter.The TemporalQuery object passed as parameter define the logic to be used to obtain the result from this instant.
Syntax:
public <R> R query(TemporalQuery<R> query)
Parameters: This method accepts only one parameter query which is the query to invoke.
Return value: This method returns the query result, null may be returned.
Exception: This method throws following Exceptions:
DateTimeException – if unable to query .
ArithmeticException – if numeric overflow occurs.
Below programs illustrate the query() method:
Program 1:
// Java program to demonstrate// Instant.query() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create Instant object Instant instant = Instant.parse("2018-12-31T10:15:30.00Z"); // apply query method of Instant class String value = instant.query(TemporalQueries.precision()) .toString(); // print the result System.out.println("Precision value for Instant is " + value); }}
Precision value for Instant is Nanos
Program 2: Showing if query did not found the required object then it returns null.
// Java program to demonstrate// Instant.query() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create Instant object Instant instant = Instant.parse("2018-12-31T10:15:30.00Z"); // apply query method of Instant class // print the result System.out.println("Zone value for Instant is " + instant.query(TemporalQueries.offset())); }}
Zone value for Instant is null
Reference:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#query(java.time.temporal.TemporalQuery)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 24125,
"s": 24097,
"text": "\n08 Jan, 2019"
},
{
"code": null,
"e": 24339,
"s": 24125,
"text": "query() method of an Instant class used to query this instant using the specified query as parameter.The TemporalQuery object passed as parameter define the logic to be used to obtain the result from this instant."
},
{
"code": null,
"e": 24347,
"s": 24339,
"text": "Syntax:"
},
{
"code": null,
"e": 24391,
"s": 24347,
"text": "public <R> R query(TemporalQuery<R> query)\n"
},
{
"code": null,
"e": 24478,
"s": 24391,
"text": "Parameters: This method accepts only one parameter query which is the query to invoke."
},
{
"code": null,
"e": 24552,
"s": 24478,
"text": "Return value: This method returns the query result, null may be returned."
},
{
"code": null,
"e": 24604,
"s": 24552,
"text": "Exception: This method throws following Exceptions:"
},
{
"code": null,
"e": 24645,
"s": 24604,
"text": "DateTimeException – if unable to query ."
},
{
"code": null,
"e": 24695,
"s": 24645,
"text": "ArithmeticException – if numeric overflow occurs."
},
{
"code": null,
"e": 24741,
"s": 24695,
"text": "Below programs illustrate the query() method:"
},
{
"code": null,
"e": 24752,
"s": 24741,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Instant.query() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create Instant object Instant instant = Instant.parse(\"2018-12-31T10:15:30.00Z\"); // apply query method of Instant class String value = instant.query(TemporalQueries.precision()) .toString(); // print the result System.out.println(\"Precision value for Instant is \" + value); }}",
"e": 25321,
"s": 24752,
"text": null
},
{
"code": null,
"e": 25359,
"s": 25321,
"text": "Precision value for Instant is Nanos\n"
},
{
"code": null,
"e": 25443,
"s": 25359,
"text": "Program 2: Showing if query did not found the required object then it returns null."
},
{
"code": "// Java program to demonstrate// Instant.query() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create Instant object Instant instant = Instant.parse(\"2018-12-31T10:15:30.00Z\"); // apply query method of Instant class // print the result System.out.println(\"Zone value for Instant is \" + instant.query(TemporalQueries.offset())); }}",
"e": 25933,
"s": 25443,
"text": null
},
{
"code": null,
"e": 25965,
"s": 25933,
"text": "Zone value for Instant is null\n"
},
{
"code": null,
"e": 26081,
"s": 25965,
"text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#query(java.time.temporal.TemporalQuery)"
},
{
"code": null,
"e": 26096,
"s": 26081,
"text": "Java-Functions"
},
{
"code": null,
"e": 26109,
"s": 26096,
"text": "Java-Instant"
},
{
"code": null,
"e": 26127,
"s": 26109,
"text": "Java-time package"
},
{
"code": null,
"e": 26132,
"s": 26127,
"text": "Java"
},
{
"code": null,
"e": 26137,
"s": 26132,
"text": "Java"
},
{
"code": null,
"e": 26235,
"s": 26137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26244,
"s": 26235,
"text": "Comments"
},
{
"code": null,
"e": 26257,
"s": 26244,
"text": "Old Comments"
},
{
"code": null,
"e": 26308,
"s": 26257,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26338,
"s": 26308,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26369,
"s": 26338,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26388,
"s": 26369,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26420,
"s": 26388,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26438,
"s": 26420,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26458,
"s": 26438,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26490,
"s": 26458,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26514,
"s": 26490,
"text": "Singleton Class in Java"
}
] |
Plagiarism Detection in Online Exams using Machine Learning | by Christopher Gerling | Towards Data Science | During the Covid-19 pandemic, many educational institutions have been forced to provide home schooling. This includes alternative examination methods for schools and universities. A traditional exam is written in person under permanent surveillance of educational staff. However, online teaching and examinations can fail to ensure a proper surveillance of students. Different online proctoring methods are already used to make plagiarism or examination fraud more difficult. Typical examples are individual video surveillance via webcam or technical user monitoring via mouse and keyboard tracking.Although these techniques already provide a proper solution to make plagiarism in online exams more difficult, the act of surveillance infringes the personal privacy [1]. Furthermore, these surveillance tools do not completely prevent students from multilateral communication among each other.
A recent approach to prevent examination fraud is the analytical identification of similarities between exams. This article proposes a machine learning-based analytical pipeline in order to tackle the problem of collusion from a data-driven perspective. It can replace privacy-infringing surveillance methods during online exams and raises honesty awareness among students.
Related Works
Committing plagiarism can have different forms in exams. Therefore, take-home exams are often designed in a way that all lecture materials and the internet can be used. The act of copying knowledge from external sources is either already expected or irrelevant for answering the questions. However, students are still able to cheat during take-home exams: Collusion is the “active, intentional and obvious act of cheating done in co-operation with others” [2].
Different strategies are used for preventing students’ collusion during exams. One way is to generate student-individual assignments. For instance, in data analytics courses, each student can be given an individual sample drawn from an original data set [3]. However, the individualisation of exams is not possible in every field. Considering a huge number of participants in an exam, the individualisation of questions makes comparability almost impossible. Hence, other strategies are also discussed in literature.
The estimation of similarities between assignments or exams is widely examined: One central problem in detecting collusion is that “no algorithm can detect plagiarism among students who have provided the same correct response where only one correct response is possible” [4]. For that reason, the exact opposite is analysed. A numeric representation of exam is required to put more emphasis on incorrect or rare answers. A specific weirdness vector “highlights suspicious behavior by detecting pairs of exams that contain identical incorrect answers, yet it is also worthwhile to identify pairs of exams that have identical correct answers” [4].
The estimation of an exam vector is dependent on the underlying structure of the questions. Multiple-choice answers, written explanation texts, numeric answers or programming code is evaluated in different ways. Very often, exams include a variety of different question types. This renders automated plagiarism detection difficult using one single detection model. For instance, textual answers can be compared using NLP models (e.g. bag-of-words, tf-idf, n-grams, LSA) [4] [5].
Text mining methods are a presented by multiple authors.However, “no simple process of comparing documents character by character will detect a sophisticated plagiarism” [6]. Other features need to be taken into consideration as well, such as event mining for analysing and comparing the timing of submissions [7].
A powerful method of plagiarism detection are rubric-based tools [1]. This method is applicable on any kind of exam or assignment. The examiner defines rubric-specific items for evaluating a student’s solution. The individual response is described by these multiple items, which are analysed for similarities [1]. Another advantage of this strategy is objectivity and transparency in grading.
Methodology & Results
This article analysis a take-home exam for assessing students’ programming skills. The data set contains 88 written exams and each exam consists of the same 8 tasks with multiple subtasks. During grading, the exam responses are evaluated using rubric-specific items.
The complete process of collusion identification is depicted in figure 1. Initially, the students’ identities are anonymised using randomised chiffre encryption. This step is only necessary for presentation purposes of the results.
import randomimport stringimport numpy as npimport pandas as pdmapping = dict()for c in string.ascii_uppercase: mapping[c] = random.sample(string.ascii_uppercase,1)for c in string.ascii_lowercase: mapping[c] = random.sample(string.ascii_lowercase,1)mapping[" "] = " "df_exam.columns = ["".join([mapping[c][0] for c in x if c in mapping.keys()]) for x in df_exam.columns]
The chiffre data frame has 85 columns with student names and 33 descriptive items (rows).
After loading and anonymising the data, the exam vectors are created. Initially, each column contains 33 numeric items. Without any transformation, these could already be used as exam vectors with 33 dimensions. However, there exist many items which have the same value for the majority of students. Specifically, if (almost) all students were able to solve one task and present the same solution, then the information gain of this item is redundant. Items, which add not much information about the differences (variances) within the data set can hence be omitted.
The formulation of a set of items with much variety of different answers is done by a simple machine learning algorithm for dimensionality reduction. A principal component analysis defines a certain number of dimensions which can represent the variance in the data without redundancies.
# one row for each studentX = np.array(df_exam).transpose()# pcafrom sklearn.decomposition import PCApca = PCA(n_components=25)pca.fit(X)# get explained varianceround(sum(list(pca.explained_variance_ratio_))*100, 2)# apply PCAX_new = pca.fit_transform(X)
By setting the number of components (dimensions) to 25, the explained variance is marginally decreased to 98.76% of the original variance. That is, a reduction of 8 items has only marginal impact on modelling the individual differences between students. Moreover, this reduction of dimensionality helps to interpret the “distances” between exams properly. The result is a more compact vector for each exam.
The typical distance measure for vectors is the cosine distance (resp. cosine similarity):
For all 85 exams, the pairwise cosine distances are calculated and stored in a data frame matrix (Figure 3). The values range between -1 for unsimilar exams and +1 for identical exams.
# define cosine distance as similarity measuredef cosine(a, b): return np.dot(a, b)/(np.linalg.norm(a)*np.linalg.norm(b))# create similarity matrixsims = np.empty([len(X_new), len(X_new)])for stud in range(len(X_new)): for peer in range(len(X_new)): sims[stud][peer] = cosine(X_new[stud], X_new[peer])df_sims = pd.DataFrame(sims)df_sims.columns = list(df_exam.columns)df_sims.index = list(df_exam.columns)
The final step for identifying collusive behaviour is sorting the pairwise exam similarities decreasingly. Remember that this approach depends on errors. Specifically, the “weirdness” of two students committing the same errors. Exams without errors will be identical per definition. Therefore, the best exams are ignored in this ordering.
pairwise = df_sims.stack().sort_values(ascending=False).reset_index()pairwise = pairwise[pairwise["level_0"]!=pairwise["level_1"]]# add points to DataFramepoints = pd.DataFrame(df_exam.sum().sort_values(ascending=False))points["name"] = points.index# join informationresult = pd.merge(pairwise, points, left_on="level_0", right_on="name", how= "inner")result = pd.merge(result, points, left_on="level_1", right_on="name", how= "inner")result = result.rename(columns={"level_0":"student_1", "level_1":"student_2", "0_x":"similarity", "0_y":"score_1", 0:"score_2"})result = result[["student_1", "student_2", "similarity","score_1", "score_2"]].reset_index(drop=True)result = result.sort_values(by="similarity", ascending=False)# show only those with mistakesresult[(result["score_1"]<31) & (result["score_2"]<31) & (result["student_1"]<result["student_2"])][:40]
The most similar exams (only those with errors) have a similarity score of 1 (completely identical) or close to 1 (very similar). Figure 4 demonstrates, that this algorithm is able to identify a couple of student-pairs with very similar exam vectors. The student-pair in the first row has the same exam vector over 25 dimensions, which results in a cosine similarity of +1. Considering that both students achieved only average results, the model strongly indicates collusive behaviour.
The similarity score in the following rows remains significantly high, which can also be a hint for collusion. Using this model, the examiners are able to identify suspicious structures easily. A manual comparison of these pairs of exams is then recommended.
The pairwise similarities can be divided into three groups:
The best 20% of exams compared to the other 80% (top_20 vs. others)The best 20% of exams in comparison (top_20 vs. top_20)The lower 80% of exams in comparison (others vs. others)
The best 20% of exams compared to the other 80% (top_20 vs. others)
The best 20% of exams in comparison (top_20 vs. top_20)
The lower 80% of exams in comparison (others vs. others)
Starting with (1), the distribution of the similarity scores seems to be almost evenly distributed. A very good exam compared to a very bad exam results in a highly negative similarity score. Likewise, in comparison to a good exam, the similarity score tends to be high.
Focussing only on the best 20% of exams (2), the similarity scores are all quite high. This underlines the hypothesis that two very good exams share a similarity score close to one. Hence, the identification of collusion among these students is almost impossible per definition.
When excluding the best students and only analysing the “worst” 80% of exams (3), the plot seems to follow a normal distribution with an expected similarity score of 0 on average.
For identifying plagiarism, (1) and (3) are the two important groups. The case of two bad/average exams with a similarity score of almost +1 is considered highly suspicious. Figure 5 shows a couple of these cases. The comparison of bad and a good exams is also worth checking, since many pairwise similarities are close to 1.
Reducing the number of dimensions even further to only two dimensions allows to plot the exams in a coordinate system. This visualisation helps to further understand the distribution of exams based on the grade. The students were segmented into three groups using k-means clustering. These three groups represent “bad/worst grades”, “good/best grades” and “average grades”. Figure 6 shows the distribution of the exams using two latent variables. Here, the latent dimension 1 can be interpreted as the final score of a student. The latent dimension 2 is necessary to visualise the similarities/distances between exams.
Once more, this plot shows the high similarity between very good exams. A proper distinction for collusion identification seems impossible. However, the data points of those students with average or bad grades are much more scattered. The expected similarity between these exams should be around 0. Thus, two bad/average exams with a higher similarity score are worth a manual investigation by the examiner.
From an ethical perspective, the data-driven approach of plagiarism detection opens up new opportunities: It can prevent collusive behaviour without permanent and privacy-infringing surveillance during online-exams. The possibility of being caught cheating by an algorithm after the evaluation is a mild but effective threat. In this scenario, the students themselves are neither observed nor analysed during the exam. Only the given responses are digitally processed. However, as a matter of fairness, this approach fully relies on the students’ awareness that all results will be analysed for collusion. Making the process of plagiarism detection transparent will hence prevent students from cheating without drastic privacy infringement.
Christopher Gerling
Follow me on: www.linkedin.com/in/christopher-gerling/
www.mission-digital.comgithub.com/christopher3996
References
A. M. Edward F. Gehringer and G. Wang, “Tools for detecting plagiarism in online exams,” in 2021 ASEE Virtual Annual Conference Content Access. Virtual Conference: ASEE Conferences, 2021, https://peer.asee.org/37915.D. Dobrovska and A. Pokorny, “Avoiding plagiarism and collusion.”, 2007.J. Coakley and C. K. Tyran, “Can e-cheating be prevented?: An approach to detect plagiarism in computer skills courses,” 2001.E. F. Gehringer, X. Liu, A. D. Kariya, and G. Wang, “Comparing and combining tests for plagiarism detection in online exams,” in EDM, 2020.J. Lemantara, M. Dewiyani Sunarto, B. Hariadi, T. Sagirani, and T. Amelia, “Prototype of online examination on molearn applications using text similarity to detect plagiarism,” in 2018 5th International Conference on Information Technology, Computer, and Electrical Engineering (ICITACEE), 2018, pp. 131–136.J. Leskovec, A. Rajaraman, and J. D. Ullman, Mining of Massive Datasets, 2nd ed. Cambridge University Press, 2014. [Online]. Available: http://mmds.org.C. Cleophas, C. Honnige, F. Meisel, and P. Meyer, “Who’s cheating? ̈ mining patterns of collusion from text and events in online exams,” INFORMS Transactions on Education, 2021. [Online]. Available: https://doi.org/10.1287/ited.2021.0260.
A. M. Edward F. Gehringer and G. Wang, “Tools for detecting plagiarism in online exams,” in 2021 ASEE Virtual Annual Conference Content Access. Virtual Conference: ASEE Conferences, 2021, https://peer.asee.org/37915.
D. Dobrovska and A. Pokorny, “Avoiding plagiarism and collusion.”, 2007.
J. Coakley and C. K. Tyran, “Can e-cheating be prevented?: An approach to detect plagiarism in computer skills courses,” 2001.
E. F. Gehringer, X. Liu, A. D. Kariya, and G. Wang, “Comparing and combining tests for plagiarism detection in online exams,” in EDM, 2020.
J. Lemantara, M. Dewiyani Sunarto, B. Hariadi, T. Sagirani, and T. Amelia, “Prototype of online examination on molearn applications using text similarity to detect plagiarism,” in 2018 5th International Conference on Information Technology, Computer, and Electrical Engineering (ICITACEE), 2018, pp. 131–136.
J. Leskovec, A. Rajaraman, and J. D. Ullman, Mining of Massive Datasets, 2nd ed. Cambridge University Press, 2014. [Online]. Available: http://mmds.org.
C. Cleophas, C. Honnige, F. Meisel, and P. Meyer, “Who’s cheating? ̈ mining patterns of collusion from text and events in online exams,” INFORMS Transactions on Education, 2021. [Online]. Available: https://doi.org/10.1287/ited.2021.0260.
The code and the data were both created by the author and published on Github. | [
{
"code": null,
"e": 1058,
"s": 165,
"text": "During the Covid-19 pandemic, many educational institutions have been forced to provide home schooling. This includes alternative examination methods for schools and universities. A traditional exam is written in person under permanent surveillance of educational staff. However, online teaching and examinations can fail to ensure a proper surveillance of students. Different online proctoring methods are already used to make plagiarism or examination fraud more difficult. Typical examples are individual video surveillance via webcam or technical user monitoring via mouse and keyboard tracking.Although these techniques already provide a proper solution to make plagiarism in online exams more difficult, the act of surveillance infringes the personal privacy [1]. Furthermore, these surveillance tools do not completely prevent students from multilateral communication among each other."
},
{
"code": null,
"e": 1432,
"s": 1058,
"text": "A recent approach to prevent examination fraud is the analytical identification of similarities between exams. This article proposes a machine learning-based analytical pipeline in order to tackle the problem of collusion from a data-driven perspective. It can replace privacy-infringing surveillance methods during online exams and raises honesty awareness among students."
},
{
"code": null,
"e": 1446,
"s": 1432,
"text": "Related Works"
},
{
"code": null,
"e": 1907,
"s": 1446,
"text": "Committing plagiarism can have different forms in exams. Therefore, take-home exams are often designed in a way that all lecture materials and the internet can be used. The act of copying knowledge from external sources is either already expected or irrelevant for answering the questions. However, students are still able to cheat during take-home exams: Collusion is the “active, intentional and obvious act of cheating done in co-operation with others” [2]."
},
{
"code": null,
"e": 2424,
"s": 1907,
"text": "Different strategies are used for preventing students’ collusion during exams. One way is to generate student-individual assignments. For instance, in data analytics courses, each student can be given an individual sample drawn from an original data set [3]. However, the individualisation of exams is not possible in every field. Considering a huge number of participants in an exam, the individualisation of questions makes comparability almost impossible. Hence, other strategies are also discussed in literature."
},
{
"code": null,
"e": 3070,
"s": 2424,
"text": "The estimation of similarities between assignments or exams is widely examined: One central problem in detecting collusion is that “no algorithm can detect plagiarism among students who have provided the same correct response where only one correct response is possible” [4]. For that reason, the exact opposite is analysed. A numeric representation of exam is required to put more emphasis on incorrect or rare answers. A specific weirdness vector “highlights suspicious behavior by detecting pairs of exams that contain identical incorrect answers, yet it is also worthwhile to identify pairs of exams that have identical correct answers” [4]."
},
{
"code": null,
"e": 3549,
"s": 3070,
"text": "The estimation of an exam vector is dependent on the underlying structure of the questions. Multiple-choice answers, written explanation texts, numeric answers or programming code is evaluated in different ways. Very often, exams include a variety of different question types. This renders automated plagiarism detection difficult using one single detection model. For instance, textual answers can be compared using NLP models (e.g. bag-of-words, tf-idf, n-grams, LSA) [4] [5]."
},
{
"code": null,
"e": 3864,
"s": 3549,
"text": "Text mining methods are a presented by multiple authors.However, “no simple process of comparing documents character by character will detect a sophisticated plagiarism” [6]. Other features need to be taken into consideration as well, such as event mining for analysing and comparing the timing of submissions [7]."
},
{
"code": null,
"e": 4257,
"s": 3864,
"text": "A powerful method of plagiarism detection are rubric-based tools [1]. This method is applicable on any kind of exam or assignment. The examiner defines rubric-specific items for evaluating a student’s solution. The individual response is described by these multiple items, which are analysed for similarities [1]. Another advantage of this strategy is objectivity and transparency in grading."
},
{
"code": null,
"e": 4279,
"s": 4257,
"text": "Methodology & Results"
},
{
"code": null,
"e": 4546,
"s": 4279,
"text": "This article analysis a take-home exam for assessing students’ programming skills. The data set contains 88 written exams and each exam consists of the same 8 tasks with multiple subtasks. During grading, the exam responses are evaluated using rubric-specific items."
},
{
"code": null,
"e": 4778,
"s": 4546,
"text": "The complete process of collusion identification is depicted in figure 1. Initially, the students’ identities are anonymised using randomised chiffre encryption. This step is only necessary for presentation purposes of the results."
},
{
"code": null,
"e": 5155,
"s": 4778,
"text": "import randomimport stringimport numpy as npimport pandas as pdmapping = dict()for c in string.ascii_uppercase: mapping[c] = random.sample(string.ascii_uppercase,1)for c in string.ascii_lowercase: mapping[c] = random.sample(string.ascii_lowercase,1)mapping[\" \"] = \" \"df_exam.columns = [\"\".join([mapping[c][0] for c in x if c in mapping.keys()]) for x in df_exam.columns]"
},
{
"code": null,
"e": 5245,
"s": 5155,
"text": "The chiffre data frame has 85 columns with student names and 33 descriptive items (rows)."
},
{
"code": null,
"e": 5810,
"s": 5245,
"text": "After loading and anonymising the data, the exam vectors are created. Initially, each column contains 33 numeric items. Without any transformation, these could already be used as exam vectors with 33 dimensions. However, there exist many items which have the same value for the majority of students. Specifically, if (almost) all students were able to solve one task and present the same solution, then the information gain of this item is redundant. Items, which add not much information about the differences (variances) within the data set can hence be omitted."
},
{
"code": null,
"e": 6097,
"s": 5810,
"text": "The formulation of a set of items with much variety of different answers is done by a simple machine learning algorithm for dimensionality reduction. A principal component analysis defines a certain number of dimensions which can represent the variance in the data without redundancies."
},
{
"code": null,
"e": 6352,
"s": 6097,
"text": "# one row for each studentX = np.array(df_exam).transpose()# pcafrom sklearn.decomposition import PCApca = PCA(n_components=25)pca.fit(X)# get explained varianceround(sum(list(pca.explained_variance_ratio_))*100, 2)# apply PCAX_new = pca.fit_transform(X)"
},
{
"code": null,
"e": 6759,
"s": 6352,
"text": "By setting the number of components (dimensions) to 25, the explained variance is marginally decreased to 98.76% of the original variance. That is, a reduction of 8 items has only marginal impact on modelling the individual differences between students. Moreover, this reduction of dimensionality helps to interpret the “distances” between exams properly. The result is a more compact vector for each exam."
},
{
"code": null,
"e": 6850,
"s": 6759,
"text": "The typical distance measure for vectors is the cosine distance (resp. cosine similarity):"
},
{
"code": null,
"e": 7035,
"s": 6850,
"text": "For all 85 exams, the pairwise cosine distances are calculated and stored in a data frame matrix (Figure 3). The values range between -1 for unsimilar exams and +1 for identical exams."
},
{
"code": null,
"e": 7455,
"s": 7035,
"text": "# define cosine distance as similarity measuredef cosine(a, b): return np.dot(a, b)/(np.linalg.norm(a)*np.linalg.norm(b))# create similarity matrixsims = np.empty([len(X_new), len(X_new)])for stud in range(len(X_new)): for peer in range(len(X_new)): sims[stud][peer] = cosine(X_new[stud], X_new[peer])df_sims = pd.DataFrame(sims)df_sims.columns = list(df_exam.columns)df_sims.index = list(df_exam.columns)"
},
{
"code": null,
"e": 7794,
"s": 7455,
"text": "The final step for identifying collusive behaviour is sorting the pairwise exam similarities decreasingly. Remember that this approach depends on errors. Specifically, the “weirdness” of two students committing the same errors. Exams without errors will be identical per definition. Therefore, the best exams are ignored in this ordering."
},
{
"code": null,
"e": 8655,
"s": 7794,
"text": "pairwise = df_sims.stack().sort_values(ascending=False).reset_index()pairwise = pairwise[pairwise[\"level_0\"]!=pairwise[\"level_1\"]]# add points to DataFramepoints = pd.DataFrame(df_exam.sum().sort_values(ascending=False))points[\"name\"] = points.index# join informationresult = pd.merge(pairwise, points, left_on=\"level_0\", right_on=\"name\", how= \"inner\")result = pd.merge(result, points, left_on=\"level_1\", right_on=\"name\", how= \"inner\")result = result.rename(columns={\"level_0\":\"student_1\", \"level_1\":\"student_2\", \"0_x\":\"similarity\", \"0_y\":\"score_1\", 0:\"score_2\"})result = result[[\"student_1\", \"student_2\", \"similarity\",\"score_1\", \"score_2\"]].reset_index(drop=True)result = result.sort_values(by=\"similarity\", ascending=False)# show only those with mistakesresult[(result[\"score_1\"]<31) & (result[\"score_2\"]<31) & (result[\"student_1\"]<result[\"student_2\"])][:40]"
},
{
"code": null,
"e": 9141,
"s": 8655,
"text": "The most similar exams (only those with errors) have a similarity score of 1 (completely identical) or close to 1 (very similar). Figure 4 demonstrates, that this algorithm is able to identify a couple of student-pairs with very similar exam vectors. The student-pair in the first row has the same exam vector over 25 dimensions, which results in a cosine similarity of +1. Considering that both students achieved only average results, the model strongly indicates collusive behaviour."
},
{
"code": null,
"e": 9400,
"s": 9141,
"text": "The similarity score in the following rows remains significantly high, which can also be a hint for collusion. Using this model, the examiners are able to identify suspicious structures easily. A manual comparison of these pairs of exams is then recommended."
},
{
"code": null,
"e": 9460,
"s": 9400,
"text": "The pairwise similarities can be divided into three groups:"
},
{
"code": null,
"e": 9639,
"s": 9460,
"text": "The best 20% of exams compared to the other 80% (top_20 vs. others)The best 20% of exams in comparison (top_20 vs. top_20)The lower 80% of exams in comparison (others vs. others)"
},
{
"code": null,
"e": 9707,
"s": 9639,
"text": "The best 20% of exams compared to the other 80% (top_20 vs. others)"
},
{
"code": null,
"e": 9763,
"s": 9707,
"text": "The best 20% of exams in comparison (top_20 vs. top_20)"
},
{
"code": null,
"e": 9820,
"s": 9763,
"text": "The lower 80% of exams in comparison (others vs. others)"
},
{
"code": null,
"e": 10091,
"s": 9820,
"text": "Starting with (1), the distribution of the similarity scores seems to be almost evenly distributed. A very good exam compared to a very bad exam results in a highly negative similarity score. Likewise, in comparison to a good exam, the similarity score tends to be high."
},
{
"code": null,
"e": 10370,
"s": 10091,
"text": "Focussing only on the best 20% of exams (2), the similarity scores are all quite high. This underlines the hypothesis that two very good exams share a similarity score close to one. Hence, the identification of collusion among these students is almost impossible per definition."
},
{
"code": null,
"e": 10550,
"s": 10370,
"text": "When excluding the best students and only analysing the “worst” 80% of exams (3), the plot seems to follow a normal distribution with an expected similarity score of 0 on average."
},
{
"code": null,
"e": 10876,
"s": 10550,
"text": "For identifying plagiarism, (1) and (3) are the two important groups. The case of two bad/average exams with a similarity score of almost +1 is considered highly suspicious. Figure 5 shows a couple of these cases. The comparison of bad and a good exams is also worth checking, since many pairwise similarities are close to 1."
},
{
"code": null,
"e": 11495,
"s": 10876,
"text": "Reducing the number of dimensions even further to only two dimensions allows to plot the exams in a coordinate system. This visualisation helps to further understand the distribution of exams based on the grade. The students were segmented into three groups using k-means clustering. These three groups represent “bad/worst grades”, “good/best grades” and “average grades”. Figure 6 shows the distribution of the exams using two latent variables. Here, the latent dimension 1 can be interpreted as the final score of a student. The latent dimension 2 is necessary to visualise the similarities/distances between exams."
},
{
"code": null,
"e": 11903,
"s": 11495,
"text": "Once more, this plot shows the high similarity between very good exams. A proper distinction for collusion identification seems impossible. However, the data points of those students with average or bad grades are much more scattered. The expected similarity between these exams should be around 0. Thus, two bad/average exams with a higher similarity score are worth a manual investigation by the examiner."
},
{
"code": null,
"e": 12644,
"s": 11903,
"text": "From an ethical perspective, the data-driven approach of plagiarism detection opens up new opportunities: It can prevent collusive behaviour without permanent and privacy-infringing surveillance during online-exams. The possibility of being caught cheating by an algorithm after the evaluation is a mild but effective threat. In this scenario, the students themselves are neither observed nor analysed during the exam. Only the given responses are digitally processed. However, as a matter of fairness, this approach fully relies on the students’ awareness that all results will be analysed for collusion. Making the process of plagiarism detection transparent will hence prevent students from cheating without drastic privacy infringement."
},
{
"code": null,
"e": 12664,
"s": 12644,
"text": "Christopher Gerling"
},
{
"code": null,
"e": 12719,
"s": 12664,
"text": "Follow me on: www.linkedin.com/in/christopher-gerling/"
},
{
"code": null,
"e": 12769,
"s": 12719,
"text": "www.mission-digital.comgithub.com/christopher3996"
},
{
"code": null,
"e": 12780,
"s": 12769,
"text": "References"
},
{
"code": null,
"e": 14033,
"s": 12780,
"text": "A. M. Edward F. Gehringer and G. Wang, “Tools for detecting plagiarism in online exams,” in 2021 ASEE Virtual Annual Conference Content Access. Virtual Conference: ASEE Conferences, 2021, https://peer.asee.org/37915.D. Dobrovska and A. Pokorny, “Avoiding plagiarism and collusion.”, 2007.J. Coakley and C. K. Tyran, “Can e-cheating be prevented?: An approach to detect plagiarism in computer skills courses,” 2001.E. F. Gehringer, X. Liu, A. D. Kariya, and G. Wang, “Comparing and combining tests for plagiarism detection in online exams,” in EDM, 2020.J. Lemantara, M. Dewiyani Sunarto, B. Hariadi, T. Sagirani, and T. Amelia, “Prototype of online examination on molearn applications using text similarity to detect plagiarism,” in 2018 5th International Conference on Information Technology, Computer, and Electrical Engineering (ICITACEE), 2018, pp. 131–136.J. Leskovec, A. Rajaraman, and J. D. Ullman, Mining of Massive Datasets, 2nd ed. Cambridge University Press, 2014. [Online]. Available: http://mmds.org.C. Cleophas, C. Honnige, F. Meisel, and P. Meyer, “Who’s cheating? ̈ mining patterns of collusion from text and events in online exams,” INFORMS Transactions on Education, 2021. [Online]. Available: https://doi.org/10.1287/ited.2021.0260."
},
{
"code": null,
"e": 14250,
"s": 14033,
"text": "A. M. Edward F. Gehringer and G. Wang, “Tools for detecting plagiarism in online exams,” in 2021 ASEE Virtual Annual Conference Content Access. Virtual Conference: ASEE Conferences, 2021, https://peer.asee.org/37915."
},
{
"code": null,
"e": 14323,
"s": 14250,
"text": "D. Dobrovska and A. Pokorny, “Avoiding plagiarism and collusion.”, 2007."
},
{
"code": null,
"e": 14450,
"s": 14323,
"text": "J. Coakley and C. K. Tyran, “Can e-cheating be prevented?: An approach to detect plagiarism in computer skills courses,” 2001."
},
{
"code": null,
"e": 14590,
"s": 14450,
"text": "E. F. Gehringer, X. Liu, A. D. Kariya, and G. Wang, “Comparing and combining tests for plagiarism detection in online exams,” in EDM, 2020."
},
{
"code": null,
"e": 14899,
"s": 14590,
"text": "J. Lemantara, M. Dewiyani Sunarto, B. Hariadi, T. Sagirani, and T. Amelia, “Prototype of online examination on molearn applications using text similarity to detect plagiarism,” in 2018 5th International Conference on Information Technology, Computer, and Electrical Engineering (ICITACEE), 2018, pp. 131–136."
},
{
"code": null,
"e": 15052,
"s": 14899,
"text": "J. Leskovec, A. Rajaraman, and J. D. Ullman, Mining of Massive Datasets, 2nd ed. Cambridge University Press, 2014. [Online]. Available: http://mmds.org."
},
{
"code": null,
"e": 15292,
"s": 15052,
"text": "C. Cleophas, C. Honnige, F. Meisel, and P. Meyer, “Who’s cheating? ̈ mining patterns of collusion from text and events in online exams,” INFORMS Transactions on Education, 2021. [Online]. Available: https://doi.org/10.1287/ited.2021.0260."
}
] |
Construct a Decision Tree and How to Deal with Overfitting | by Jun M. | Towards Data Science | A decision tree is an algorithm for supervised learning. It uses a tree structure, in which there are two types of nodes: decision node and leaf node. A decision node splits the data into two branches by asking a boolean question on a feature. A leaf node represents a class. The training process is about finding the “best” split at a certain feature with a certain value. And the predicting process is to reach the leaf node from root by answering the question at each decision node along the path.
The term “best” split means that after split, the two branches are more “ordered” than any other possible split. How do we define more ordered? It depends on which metric we choose. In general, there are two types of metric: gini impurity and entropy. The smaller these metrics are, the more “ordered” the dataset is.
The difference between the two metrics is pretty subtle. To learn more, you may read this post. In most applications, both metric behave similarly. Below is the code to calculate each metric.
The training process is essentially building the tree. A key step is determining the “best” split. The procedure is as follows: we try to split the data at each unique value in each feature, and choose the best one that yields the least disorder. Now let’s translate this procedure into Python code.
Before we build the tree, let’s define decision node and leaf node. A decision node specifies the feature and value upon which it will split. It also points to its left and right children. A leaf node includes a dictionary similar to a Counter object showing how many training examples for each class. This is useful to calculate the accuracy for training (although it is not necessary since we could get the accuracy by predicting each example after the model is trained). In addition, it leads to the resulting prediction for each example that reaches this leaf.
Given its structure, it is most convenient to construct the tree by recursion. The exit of recursion is a leaf node. This happens when we cannot increase the purity of the data through splitting. If we could find a “best” split, this becomes a decision node. Next we do the same recursively to its left and right children.
Now we can predict an example by traversing the tree until a leaf node.
It turns out that the training accuracy is 100% and the decision boundary is weird looking! Clearly the model is overfitting the training data. Well, if you think about it, a decision tree will overfit the data if we keep splitting until the dataset couldn’t be more pure. In other words, the model will correctly classify each and every example if we don’t stop splitting! The training accuracy is 100% (except when there are examples with different classes for exactly same features) without surprise.
From previous section, we know the behind-scene reason why a decision tree overfits. To prevent overfitting, there are two ways: 1. we stop splitting the tree at some point; 2. we generate a complete tree first, and then get rid of some branches. I am going to use the 1st method as an example. In order to stop splitting earlier, we need to introduce two hyperparameters for training. They are: maximum depth of the tree and minimum size of a leaf. Let’s rewrite the tree building part.
Now we can retrain the data and plot the decision boundary.
Next, we will visualize a decision tree by print out its nodes. The indentation of a node is proportional to its depth.
|---feature_1 <= 1.87| |---feature_1 <= -0.74| | |---feature_1 <= -1.79| | | |---feature_1 <= -2.1| | | | |---Class: 2| | | |---feature_1 > -2.1| | | | |---Class: 2| | |---feature_1 > -1.79| | | |---feature_0 <= 1.62| | | | |---feature_0 <= -1.31| | | | | |---Class: 2| | | | |---feature_0 > -1.31| | | | | |---feature_1 <= -1.49| | | | | | |---Class: 1| | | | | |---feature_1 > -1.49| | | | | | |---Class: 1| | | |---feature_0 > 1.62| | | | |---Class: 2| |---feature_1 > -0.74| | |---feature_1 <= 0.76| | | |---feature_0 <= 0.89| | | | |---feature_0 <= -0.86| | | | | |---feature_0 <= -2.24| | | | | | |---Class: 2| | | | | |---feature_0 > -2.24| | | | | | |---Class: 1| | | | |---feature_0 > -0.86| | | | | |---Class: 0| | | |---feature_0 > 0.89| | | | |---feature_0 <= 2.13| | | | | |---Class: 1| | | | |---feature_0 > 2.13| | | | | |---Class: 2| | |---feature_1 > 0.76| | | |---feature_0 <= -1.6| | | | |---Class: 2| | | |---feature_0 > -1.6| | | | |---feature_0 <= 1.35| | | | | |---feature_1 <= 1.66| | | | | | |---Class: 1| | | | | |---feature_1 > 1.66| | | | | | |---Class: 1| | | | |---feature_0 > 1.35| | | | | |---Class: 2|---feature_1 > 1.87| |---Class: 2
The examples above clearly shows one characteristic of decision tree: the decision boundary is linear in the feature space. While the tree is able to classify dataset that is not linearly separable, it relies heavily on the quality of training data and its accuracy decreases around decision boundaries. One way to address this drawback is feature engineering. Similar to the examples in logistic regression, we could expand the features to include non-linear terms. Here is one example if we add terms like x1x2, x12 and x22.
Unlike other regression models, decision tree doesn’t use regularization to fight against overfitting. Instead, it employs tree pruning. Selecting the right hyperparameters (tree depth and leaf size) also requires experimentation, e.g. doing cross-validation with a hyperparameter matrix.
For a complete workflow, including data generation and plotting decision boundary, you may visit my github. | [
{
"code": null,
"e": 673,
"s": 172,
"text": "A decision tree is an algorithm for supervised learning. It uses a tree structure, in which there are two types of nodes: decision node and leaf node. A decision node splits the data into two branches by asking a boolean question on a feature. A leaf node represents a class. The training process is about finding the “best” split at a certain feature with a certain value. And the predicting process is to reach the leaf node from root by answering the question at each decision node along the path."
},
{
"code": null,
"e": 991,
"s": 673,
"text": "The term “best” split means that after split, the two branches are more “ordered” than any other possible split. How do we define more ordered? It depends on which metric we choose. In general, there are two types of metric: gini impurity and entropy. The smaller these metrics are, the more “ordered” the dataset is."
},
{
"code": null,
"e": 1183,
"s": 991,
"text": "The difference between the two metrics is pretty subtle. To learn more, you may read this post. In most applications, both metric behave similarly. Below is the code to calculate each metric."
},
{
"code": null,
"e": 1483,
"s": 1183,
"text": "The training process is essentially building the tree. A key step is determining the “best” split. The procedure is as follows: we try to split the data at each unique value in each feature, and choose the best one that yields the least disorder. Now let’s translate this procedure into Python code."
},
{
"code": null,
"e": 2048,
"s": 1483,
"text": "Before we build the tree, let’s define decision node and leaf node. A decision node specifies the feature and value upon which it will split. It also points to its left and right children. A leaf node includes a dictionary similar to a Counter object showing how many training examples for each class. This is useful to calculate the accuracy for training (although it is not necessary since we could get the accuracy by predicting each example after the model is trained). In addition, it leads to the resulting prediction for each example that reaches this leaf."
},
{
"code": null,
"e": 2371,
"s": 2048,
"text": "Given its structure, it is most convenient to construct the tree by recursion. The exit of recursion is a leaf node. This happens when we cannot increase the purity of the data through splitting. If we could find a “best” split, this becomes a decision node. Next we do the same recursively to its left and right children."
},
{
"code": null,
"e": 2443,
"s": 2371,
"text": "Now we can predict an example by traversing the tree until a leaf node."
},
{
"code": null,
"e": 2947,
"s": 2443,
"text": "It turns out that the training accuracy is 100% and the decision boundary is weird looking! Clearly the model is overfitting the training data. Well, if you think about it, a decision tree will overfit the data if we keep splitting until the dataset couldn’t be more pure. In other words, the model will correctly classify each and every example if we don’t stop splitting! The training accuracy is 100% (except when there are examples with different classes for exactly same features) without surprise."
},
{
"code": null,
"e": 3435,
"s": 2947,
"text": "From previous section, we know the behind-scene reason why a decision tree overfits. To prevent overfitting, there are two ways: 1. we stop splitting the tree at some point; 2. we generate a complete tree first, and then get rid of some branches. I am going to use the 1st method as an example. In order to stop splitting earlier, we need to introduce two hyperparameters for training. They are: maximum depth of the tree and minimum size of a leaf. Let’s rewrite the tree building part."
},
{
"code": null,
"e": 3495,
"s": 3435,
"text": "Now we can retrain the data and plot the decision boundary."
},
{
"code": null,
"e": 3615,
"s": 3495,
"text": "Next, we will visualize a decision tree by print out its nodes. The indentation of a node is proportional to its depth."
},
{
"code": null,
"e": 5131,
"s": 3615,
"text": "|---feature_1 <= 1.87| |---feature_1 <= -0.74| | |---feature_1 <= -1.79| | | |---feature_1 <= -2.1| | | | |---Class: 2| | | |---feature_1 > -2.1| | | | |---Class: 2| | |---feature_1 > -1.79| | | |---feature_0 <= 1.62| | | | |---feature_0 <= -1.31| | | | | |---Class: 2| | | | |---feature_0 > -1.31| | | | | |---feature_1 <= -1.49| | | | | | |---Class: 1| | | | | |---feature_1 > -1.49| | | | | | |---Class: 1| | | |---feature_0 > 1.62| | | | |---Class: 2| |---feature_1 > -0.74| | |---feature_1 <= 0.76| | | |---feature_0 <= 0.89| | | | |---feature_0 <= -0.86| | | | | |---feature_0 <= -2.24| | | | | | |---Class: 2| | | | | |---feature_0 > -2.24| | | | | | |---Class: 1| | | | |---feature_0 > -0.86| | | | | |---Class: 0| | | |---feature_0 > 0.89| | | | |---feature_0 <= 2.13| | | | | |---Class: 1| | | | |---feature_0 > 2.13| | | | | |---Class: 2| | |---feature_1 > 0.76| | | |---feature_0 <= -1.6| | | | |---Class: 2| | | |---feature_0 > -1.6| | | | |---feature_0 <= 1.35| | | | | |---feature_1 <= 1.66| | | | | | |---Class: 1| | | | | |---feature_1 > 1.66| | | | | | |---Class: 1| | | | |---feature_0 > 1.35| | | | | |---Class: 2|---feature_1 > 1.87| |---Class: 2"
},
{
"code": null,
"e": 5658,
"s": 5131,
"text": "The examples above clearly shows one characteristic of decision tree: the decision boundary is linear in the feature space. While the tree is able to classify dataset that is not linearly separable, it relies heavily on the quality of training data and its accuracy decreases around decision boundaries. One way to address this drawback is feature engineering. Similar to the examples in logistic regression, we could expand the features to include non-linear terms. Here is one example if we add terms like x1x2, x12 and x22."
},
{
"code": null,
"e": 5947,
"s": 5658,
"text": "Unlike other regression models, decision tree doesn’t use regularization to fight against overfitting. Instead, it employs tree pruning. Selecting the right hyperparameters (tree depth and leaf size) also requires experimentation, e.g. doing cross-validation with a hyperparameter matrix."
}
] |
SQLite - Subqueries | A Subquery or Inner query or Nested query is a query within another SQLite query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators such as =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery.
BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, let us check the following sub-query with SELECT statement.
sqlite> SELECT *
FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY
WHERE SALARY > 45000) ;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions.
Following is the basic syntax is as follows −
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. To copy the complete COMPANY table into COMPANY_BKP, following is the syntax −
sqlite> INSERT INTO COMPANY_BKP
SELECT * FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY) ;
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.
Following is the basic syntax is as follows −
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table.
Following example updates SALARY by 0.50 times in COMPANY table for all the customers, whose AGE is greater than or equal to 27.
sqlite> UPDATE COMPANY
SET SALARY = SALARY * 0.50
WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
WHERE AGE >= 27 );
This would impact two rows and finally COMPANY table would have the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 10000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 42500.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
Following is the basic syntax is as follows −
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table.
Following example deletes records from COMPANY table for all the customers whose AGE is greater than or equal to 27.
sqlite> DELETE FROM COMPANY
WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
WHERE AGE > 27 );
This will impact two rows and finally COMPANY table will have the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 42500.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2757,
"s": 2638,
"text": "A Subquery or Inner query or Nested query is a query within another SQLite query and embedded within the WHERE clause."
},
{
"code": null,
"e": 2888,
"s": 2757,
"text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved."
},
{
"code": null,
"e": 3034,
"s": 2888,
"text": "Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators such as =, <, >, >=, <=, IN, BETWEEN, etc."
},
{
"code": null,
"e": 3086,
"s": 3034,
"text": "There are a few rules that subqueries must follow −"
},
{
"code": null,
"e": 3134,
"s": 3086,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 3182,
"s": 3134,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 3336,
"s": 3182,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 3490,
"s": 3336,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 3662,
"s": 3490,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 3834,
"s": 3662,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 3948,
"s": 3834,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator."
},
{
"code": null,
"e": 4062,
"s": 3948,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator."
},
{
"code": null,
"e": 4161,
"s": 4062,
"text": "BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery."
},
{
"code": null,
"e": 4260,
"s": 4161,
"text": "BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery."
},
{
"code": null,
"e": 4356,
"s": 4260,
"text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −"
},
{
"code": null,
"e": 4529,
"s": 4356,
"text": "SELECT column_name [, column_name ]\nFROM table1 [, table2 ]\nWHERE column_name OPERATOR\n (SELECT column_name [, column_name ]\n FROM table1 [, table2 ]\n [WHERE])\n"
},
{
"code": null,
"e": 4580,
"s": 4529,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 5086,
"s": 4580,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 5151,
"s": 5086,
"text": "Now, let us check the following sub-query with SELECT statement."
},
{
"code": null,
"e": 5263,
"s": 5151,
"text": "sqlite> SELECT * \n FROM COMPANY \n WHERE ID IN (SELECT ID \n FROM COMPANY \n WHERE SALARY > 45000) ;"
},
{
"code": null,
"e": 5303,
"s": 5263,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5530,
"s": 5303,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 5778,
"s": 5530,
"text": "Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions."
},
{
"code": null,
"e": 5824,
"s": 5778,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 5965,
"s": 5824,
"text": "INSERT INTO table_name [ (column1 [, column2 ]) ]\n SELECT [ *|column1 [, column2 ]\n FROM table1 [, table2 ]\n [ WHERE VALUE OPERATOR ]\n"
},
{
"code": null,
"e": 6197,
"s": 5965,
"text": "Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. To copy the complete COMPANY table into COMPANY_BKP, following is the syntax −"
},
{
"code": null,
"e": 6305,
"s": 6197,
"text": "sqlite> INSERT INTO COMPANY_BKP\n SELECT * FROM COMPANY \n WHERE ID IN (SELECT ID \n FROM COMPANY) ;\n"
},
{
"code": null,
"e": 6481,
"s": 6305,
"text": "The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement."
},
{
"code": null,
"e": 6527,
"s": 6481,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 6656,
"s": 6527,
"text": "UPDATE table\nSET column_name = new_value\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n"
},
{
"code": null,
"e": 6738,
"s": 6656,
"text": "Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table."
},
{
"code": null,
"e": 6867,
"s": 6738,
"text": "Following example updates SALARY by 0.50 times in COMPANY table for all the customers, whose AGE is greater than or equal to 27."
},
{
"code": null,
"e": 6990,
"s": 6867,
"text": "sqlite> UPDATE COMPANY\n SET SALARY = SALARY * 0.50\n WHERE AGE IN (SELECT AGE FROM COMPANY_BKP\n WHERE AGE >= 27 );"
},
{
"code": null,
"e": 7078,
"s": 6990,
"text": "This would impact two rows and finally COMPANY table would have the following records −"
},
{
"code": null,
"e": 7585,
"s": 7078,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 10000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 42500.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 7695,
"s": 7585,
"text": "Subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above."
},
{
"code": null,
"e": 7741,
"s": 7695,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 7852,
"s": 7741,
"text": "DELETE FROM TABLE_NAME\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n"
},
{
"code": null,
"e": 7934,
"s": 7852,
"text": "Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table."
},
{
"code": null,
"e": 8051,
"s": 7934,
"text": "Following example deletes records from COMPANY table for all the customers whose AGE is greater than or equal to 27."
},
{
"code": null,
"e": 8145,
"s": 8051,
"text": "sqlite> DELETE FROM COMPANY\n WHERE AGE IN (SELECT AGE FROM COMPANY_BKP\n WHERE AGE > 27 );"
},
{
"code": null,
"e": 8231,
"s": 8145,
"text": "This will impact two rows and finally COMPANY table will have the following records −"
},
{
"code": null,
"e": 8682,
"s": 8231,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 42500.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 8717,
"s": 8682,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8738,
"s": 8717,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 8771,
"s": 8738,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8788,
"s": 8771,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 8819,
"s": 8788,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 8832,
"s": 8819,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 8839,
"s": 8832,
"text": " Print"
},
{
"code": null,
"e": 8850,
"s": 8839,
"text": " Add Notes"
}
] |
Access Modifiers in C++ - GeeksforGeeks | 22 Apr, 2021
Access modifiers are used to implement an important aspect of Object-Oriented Programming known as Data Hiding. Consider a real-life example: The Research and analysis wing (R&AW), having 10 core members has come in possession of sensitive confidential information regarding national security. Now we can correlate these core members to data members or member functions of a class which in turn can be correlated to the R&A wing. These 10 members can directly access confidential information from their wing (the class), but anyone apart from these 10 members can’t access this information directly i.e. outside functions other than those prevalent in the class itself can’t access information that is not entitled to them, without having either assigned privileges (such as those possessed by friend class and inherited class as will be seen in this article ahead) or access to one of these 10 members who is allowed direct access to the confidential information (similar to how private members of a class can be accessed in the outside world through public member functions of the class that have direct access to private members). This is what data hiding is in practice. Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class members. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions.There are 3 types of access modifiers available in C++:
PublicPrivateProtected
Public
Private
Protected
Note: If we do not specify any access modifiers for the members inside the class then by default the access modifier for the members will be Private.
Let us now look at each one these access modifiers in details: 1. Public: All the class members declared under the public specifier will be available to everyone. The data members and member functions declared as public can be accessed by other classes and functions too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.
Example:
CPP
// C++ program to demonstrate public// access modifier #include<iostream>using namespace std; // class definitionclass Circle{ public: double radius; double compute_area() { return 3.14*radius*radius; } }; // main functionint main(){ Circle obj; // accessing public datamember outside class obj.radius = 5.5; cout << "Radius is: " << obj.radius << "\n"; cout << "Area is: " << obj.compute_area(); return 0;}
Output:
Radius is: 5.5
Area is: 94.985
In the above program the data member radius is declared as public so it could be accessed outside the class and thus was allowed access from inside main(). 2. Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
Example:
CPP
// C++ program to demonstrate private// access modifier #include<iostream>using namespace std; class Circle{ // private data member private: double radius; // public member function public: double compute_area() { // member function can access private // data member radius return 3.14*radius*radius; } }; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.radius = 1.5; cout << "Area is:" << obj.compute_area(); return 0;}
Output:
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
^
The output of above program is a compile time error because we are not allowed to access the private data members of a class directly outside the class. Yet an access to obj.radius is attempted, radius being a private data member we obtain a compilation error.
However, we can access the private data members of a class indirectly using the public member functions of the class.
Example:
CPP
// C++ program to demonstrate private// access modifier #include<iostream>using namespace std; class Circle{ // private data member private: double radius; // public member function public: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14*radius*radius; cout << "Radius is: " << radius << endl; cout << "Area is: " << area; } }; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}
Output:
Radius is: 1.5
Area is: 7.065
3. Protected: Protected access modifier is similar to private access modifier in the sense that it can’t be accessed outside of it’s class unless with the help of friend class, the difference is that the class members declared as Protected can be accessed by any subclass(derived class) of that class as well.
Note: This access through inheritance can alter the access modifier of the elements of base class in derived class depending on the modes of Inheritance.
Example:
CPP
// C++ program to demonstrate// protected access modifier#include <bits/stdc++.h>using namespace std; // base classclass Parent{ // protected data members protected: int id_protected; }; // sub class or derived class from public base classclass Child : public Parent{ public: void setId(int id) { // Child class is able to access the inherited // protected data members of base class id_protected = id; } void displayId() { cout << "id_protected is: " << id_protected << endl; }}; // main functionint main() { Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}
Output:
id_protected is: 81
PriyankaSharma2
KoshaleshMeher
costheta_z
simmytarika5
cpp-class
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Map in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Operator Overloading in C++
Socket Programming in C/C++
Multidimensional Arrays in C / C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Operator Overloading in C++
Object Oriented Programming in C++ | [
{
"code": null,
"e": 24078,
"s": 24050,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25528,
"s": 24078,
"text": "Access modifiers are used to implement an important aspect of Object-Oriented Programming known as Data Hiding. Consider a real-life example: The Research and analysis wing (R&AW), having 10 core members has come in possession of sensitive confidential information regarding national security. Now we can correlate these core members to data members or member functions of a class which in turn can be correlated to the R&A wing. These 10 members can directly access confidential information from their wing (the class), but anyone apart from these 10 members can’t access this information directly i.e. outside functions other than those prevalent in the class itself can’t access information that is not entitled to them, without having either assigned privileges (such as those possessed by friend class and inherited class as will be seen in this article ahead) or access to one of these 10 members who is allowed direct access to the confidential information (similar to how private members of a class can be accessed in the outside world through public member functions of the class that have direct access to private members). This is what data hiding is in practice. Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class members. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions.There are 3 types of access modifiers available in C++: "
},
{
"code": null,
"e": 25551,
"s": 25528,
"text": "PublicPrivateProtected"
},
{
"code": null,
"e": 25558,
"s": 25551,
"text": "Public"
},
{
"code": null,
"e": 25566,
"s": 25558,
"text": "Private"
},
{
"code": null,
"e": 25576,
"s": 25566,
"text": "Protected"
},
{
"code": null,
"e": 25726,
"s": 25576,
"text": "Note: If we do not specify any access modifiers for the members inside the class then by default the access modifier for the members will be Private."
},
{
"code": null,
"e": 26149,
"s": 25726,
"text": "Let us now look at each one these access modifiers in details: 1. Public: All the class members declared under the public specifier will be available to everyone. The data members and member functions declared as public can be accessed by other classes and functions too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class. "
},
{
"code": null,
"e": 26159,
"s": 26149,
"text": "Example: "
},
{
"code": null,
"e": 26163,
"s": 26159,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate public// access modifier #include<iostream>using namespace std; // class definitionclass Circle{ public: double radius; double compute_area() { return 3.14*radius*radius; } }; // main functionint main(){ Circle obj; // accessing public datamember outside class obj.radius = 5.5; cout << \"Radius is: \" << obj.radius << \"\\n\"; cout << \"Area is: \" << obj.compute_area(); return 0;}",
"e": 26655,
"s": 26163,
"text": null
},
{
"code": null,
"e": 26664,
"s": 26655,
"text": "Output: "
},
{
"code": null,
"e": 26695,
"s": 26664,
"text": "Radius is: 5.5\nArea is: 94.985"
},
{
"code": null,
"e": 27165,
"s": 26695,
"text": "In the above program the data member radius is declared as public so it could be accessed outside the class and thus was allowed access from inside main(). 2. Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class. "
},
{
"code": null,
"e": 27175,
"s": 27165,
"text": "Example: "
},
{
"code": null,
"e": 27179,
"s": 27175,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate private// access modifier #include<iostream>using namespace std; class Circle{ // private data member private: double radius; // public member function public: double compute_area() { // member function can access private // data member radius return 3.14*radius*radius; } }; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.radius = 1.5; cout << \"Area is:\" << obj.compute_area(); return 0;}",
"e": 27814,
"s": 27179,
"text": null
},
{
"code": null,
"e": 27823,
"s": 27814,
"text": "Output: "
},
{
"code": null,
"e": 28008,
"s": 27823,
"text": " In function 'int main()':\n11:16: error: 'double Circle::radius' is private\n double radius;\n ^\n31:9: error: within this context\n obj.radius = 1.5;\n ^"
},
{
"code": null,
"e": 28270,
"s": 28008,
"text": "The output of above program is a compile time error because we are not allowed to access the private data members of a class directly outside the class. Yet an access to obj.radius is attempted, radius being a private data member we obtain a compilation error. "
},
{
"code": null,
"e": 28389,
"s": 28270,
"text": "However, we can access the private data members of a class indirectly using the public member functions of the class. "
},
{
"code": null,
"e": 28399,
"s": 28389,
"text": "Example: "
},
{
"code": null,
"e": 28403,
"s": 28399,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate private// access modifier #include<iostream>using namespace std; class Circle{ // private data member private: double radius; // public member function public: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14*radius*radius; cout << \"Radius is: \" << radius << endl; cout << \"Area is: \" << area; } }; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}",
"e": 29156,
"s": 28403,
"text": null
},
{
"code": null,
"e": 29165,
"s": 29156,
"text": "Output: "
},
{
"code": null,
"e": 29195,
"s": 29165,
"text": "Radius is: 1.5\nArea is: 7.065"
},
{
"code": null,
"e": 29506,
"s": 29195,
"text": "3. Protected: Protected access modifier is similar to private access modifier in the sense that it can’t be accessed outside of it’s class unless with the help of friend class, the difference is that the class members declared as Protected can be accessed by any subclass(derived class) of that class as well. "
},
{
"code": null,
"e": 29660,
"s": 29506,
"text": "Note: This access through inheritance can alter the access modifier of the elements of base class in derived class depending on the modes of Inheritance."
},
{
"code": null,
"e": 29670,
"s": 29660,
"text": "Example: "
},
{
"code": null,
"e": 29674,
"s": 29670,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// protected access modifier#include <bits/stdc++.h>using namespace std; // base classclass Parent{ // protected data members protected: int id_protected; }; // sub class or derived class from public base classclass Child : public Parent{ public: void setId(int id) { // Child class is able to access the inherited // protected data members of base class id_protected = id; } void displayId() { cout << \"id_protected is: \" << id_protected << endl; }}; // main functionint main() { Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}",
"e": 30468,
"s": 29674,
"text": null
},
{
"code": null,
"e": 30477,
"s": 30468,
"text": "Output: "
},
{
"code": null,
"e": 30497,
"s": 30477,
"text": "id_protected is: 81"
},
{
"code": null,
"e": 30513,
"s": 30497,
"text": "PriyankaSharma2"
},
{
"code": null,
"e": 30528,
"s": 30513,
"text": "KoshaleshMeher"
},
{
"code": null,
"e": 30539,
"s": 30528,
"text": "costheta_z"
},
{
"code": null,
"e": 30552,
"s": 30539,
"text": "simmytarika5"
},
{
"code": null,
"e": 30562,
"s": 30552,
"text": "cpp-class"
},
{
"code": null,
"e": 30566,
"s": 30562,
"text": "C++"
},
{
"code": null,
"e": 30585,
"s": 30566,
"text": "School Programming"
},
{
"code": null,
"e": 30589,
"s": 30585,
"text": "CPP"
},
{
"code": null,
"e": 30687,
"s": 30589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30730,
"s": 30687,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30757,
"s": 30730,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30785,
"s": 30757,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30813,
"s": 30785,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30848,
"s": 30813,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 30866,
"s": 30848,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30891,
"s": 30866,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30910,
"s": 30891,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30938,
"s": 30910,
"text": "Operator Overloading in C++"
}
] |
How do I declare and initialize an array in Java? | You can declare an array just like a variable −
int myArray[];
You can create an array just like an object using the new keyword −
myArray = new int[5];
You can initialize the array by assigning values to all the elements one by one using the index −
myArray [0] = 101;
myArray [1] = 102;
You can access the array element using the index values −
System.out.println("The first element of the array is: " + myArray [0]);
System.out.println("The first element of the array is: " + myArray [1]);
Alternatively, you can create and initialize an array using the flower braces ({ }):
Int [] myArray = {10, 20, 30, 40, 50} | [
{
"code": null,
"e": 1110,
"s": 1062,
"text": "You can declare an array just like a variable −"
},
{
"code": null,
"e": 1125,
"s": 1110,
"text": "int myArray[];"
},
{
"code": null,
"e": 1193,
"s": 1125,
"text": "You can create an array just like an object using the new keyword −"
},
{
"code": null,
"e": 1215,
"s": 1193,
"text": "myArray = new int[5];"
},
{
"code": null,
"e": 1313,
"s": 1215,
"text": "You can initialize the array by assigning values to all the elements one by one using the index −"
},
{
"code": null,
"e": 1351,
"s": 1313,
"text": "myArray [0] = 101;\nmyArray [1] = 102;"
},
{
"code": null,
"e": 1409,
"s": 1351,
"text": "You can access the array element using the index values −"
},
{
"code": null,
"e": 1678,
"s": 1409,
"text": "System.out.println(\"The first element of the array is: \" + myArray [0]);\nSystem.out.println(\"The first element of the array is: \" + myArray [1]);\nAlternatively, you can create and initialize an array using the flower braces ({ }):\nInt [] myArray = {10, 20, 30, 40, 50}"
}
] |
How to clear all elements from List in Python - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
The Python clear() method is used to clear all elements from the list.
the clear() method can be applied on a python list to remove all elements, it doesn’t take any values as parameters and doesn’t return (None) anything.
In the following example, I am going to create a list first and remove all elements at a once.
if __name__ == '__main__':
fruits = ['Apple','Banana','Gua','Pineapple','Mango']
# Before clearing the list
print(fruits)
fruits.clear()
# After clearing the list
print(fruits)
Output:
['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']
[]
del is a keyword in python, which is used to delete objects, lists or part of lists
if __name__ == '__main__':
fruits = ['Apple','Banana','Gua','Pineapple','Mango']
# Before clearing the list
print(fruits)
del fruits[:]
# After clearing the list
print(fruits)
Output:
['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']
[]
A python list can be empty by multiplying with 0 like below.
if __name__ == '__main__':
fruits = ['Apple','Banana','Gua','Pineapple','Mango']
# Before clearing the list
print(fruits)
# After clearing the list
fruits *=0
# After clearing the list
print(fruits)
Output:
['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']
[]
Python List in depth
Happy Learning 🙂
Python – How to remove key from dictionary ?
2 ways to Create ArrayList in Java
Python Set Data Structure in Depth
How to Remove Spaces from String in Python
How to Sort ArrayList in Java Descending Order
Python – How to remove duplicate elements from List
What is Python NumPy Library
How to Create or Delete Directories in Python ?
How to Rotate Elements in List
What are the List of Python Keywords
Python List Data Structure In Depth
Python List comprehension usage and advantages
How to remove empty lists from a Python List
How to Convert Python List Of Objects to CSV File
How to clear PuTTY Sessions on Windows
Python – How to remove key from dictionary ?
2 ways to Create ArrayList in Java
Python Set Data Structure in Depth
How to Remove Spaces from String in Python
How to Sort ArrayList in Java Descending Order
Python – How to remove duplicate elements from List
What is Python NumPy Library
How to Create or Delete Directories in Python ?
How to Rotate Elements in List
What are the List of Python Keywords
Python List Data Structure In Depth
Python List comprehension usage and advantages
How to remove empty lists from a Python List
How to Convert Python List Of Objects to CSV File
How to clear PuTTY Sessions on Windows
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 469,
"s": 398,
"text": "The Python clear() method is used to clear all elements from the list."
},
{
"code": null,
"e": 621,
"s": 469,
"text": "the clear() method can be applied on a python list to remove all elements, it doesn’t take any values as parameters and doesn’t return (None) anything."
},
{
"code": null,
"e": 716,
"s": 621,
"text": "In the following example, I am going to create a list first and remove all elements at a once."
},
{
"code": null,
"e": 917,
"s": 716,
"text": "if __name__ == '__main__':\n fruits = ['Apple','Banana','Gua','Pineapple','Mango']\n # Before clearing the list\n print(fruits)\n fruits.clear()\n # After clearing the list\n print(fruits)"
},
{
"code": null,
"e": 925,
"s": 917,
"text": "Output:"
},
{
"code": null,
"e": 977,
"s": 925,
"text": "['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']\n[]"
},
{
"code": null,
"e": 1061,
"s": 977,
"text": "del is a keyword in python, which is used to delete objects, lists or part of lists"
},
{
"code": null,
"e": 1261,
"s": 1061,
"text": "if __name__ == '__main__':\n fruits = ['Apple','Banana','Gua','Pineapple','Mango']\n # Before clearing the list\n print(fruits)\n del fruits[:]\n # After clearing the list\n print(fruits)"
},
{
"code": null,
"e": 1269,
"s": 1261,
"text": "Output:"
},
{
"code": null,
"e": 1321,
"s": 1269,
"text": "['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']\n[]"
},
{
"code": null,
"e": 1382,
"s": 1321,
"text": "A python list can be empty by multiplying with 0 like below."
},
{
"code": null,
"e": 1611,
"s": 1382,
"text": "if __name__ == '__main__':\n fruits = ['Apple','Banana','Gua','Pineapple','Mango']\n # Before clearing the list\n print(fruits)\n\n # After clearing the list\n\n fruits *=0\n # After clearing the list\n print(fruits)"
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Output:"
},
{
"code": null,
"e": 1671,
"s": 1619,
"text": "['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']\n[]"
},
{
"code": null,
"e": 1692,
"s": 1671,
"text": "Python List in depth"
},
{
"code": null,
"e": 1709,
"s": 1692,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2330,
"s": 1709,
"text": "\nPython – How to remove key from dictionary ?\n2 ways to Create ArrayList in Java\nPython Set Data Structure in Depth\nHow to Remove Spaces from String in Python\nHow to Sort ArrayList in Java Descending Order\nPython – How to remove duplicate elements from List\nWhat is Python NumPy Library\nHow to Create or Delete Directories in Python ?\nHow to Rotate Elements in List\nWhat are the List of Python Keywords\nPython List Data Structure In Depth\nPython List comprehension usage and advantages\nHow to remove empty lists from a Python List\nHow to Convert Python List Of Objects to CSV File\nHow to clear PuTTY Sessions on Windows\n"
},
{
"code": null,
"e": 2375,
"s": 2330,
"text": "Python – How to remove key from dictionary ?"
},
{
"code": null,
"e": 2410,
"s": 2375,
"text": "2 ways to Create ArrayList in Java"
},
{
"code": null,
"e": 2445,
"s": 2410,
"text": "Python Set Data Structure in Depth"
},
{
"code": null,
"e": 2488,
"s": 2445,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 2535,
"s": 2488,
"text": "How to Sort ArrayList in Java Descending Order"
},
{
"code": null,
"e": 2587,
"s": 2535,
"text": "Python – How to remove duplicate elements from List"
},
{
"code": null,
"e": 2616,
"s": 2587,
"text": "What is Python NumPy Library"
},
{
"code": null,
"e": 2664,
"s": 2616,
"text": "How to Create or Delete Directories in Python ?"
},
{
"code": null,
"e": 2695,
"s": 2664,
"text": "How to Rotate Elements in List"
},
{
"code": null,
"e": 2732,
"s": 2695,
"text": "What are the List of Python Keywords"
},
{
"code": null,
"e": 2768,
"s": 2732,
"text": "Python List Data Structure In Depth"
},
{
"code": null,
"e": 2815,
"s": 2768,
"text": "Python List comprehension usage and advantages"
},
{
"code": null,
"e": 2860,
"s": 2815,
"text": "How to remove empty lists from a Python List"
},
{
"code": null,
"e": 2910,
"s": 2860,
"text": "How to Convert Python List Of Objects to CSV File"
},
{
"code": null,
"e": 2949,
"s": 2910,
"text": "How to clear PuTTY Sessions on Windows"
},
{
"code": null,
"e": 2955,
"s": 2953,
"text": "Δ"
},
{
"code": null,
"e": 2978,
"s": 2955,
"text": " Python – Introduction"
},
{
"code": null,
"e": 2997,
"s": 2978,
"text": " Python – Features"
},
{
"code": null,
"e": 3026,
"s": 2997,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 3053,
"s": 3026,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 3077,
"s": 3053,
"text": " Python – Number System"
},
{
"code": null,
"e": 3099,
"s": 3077,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 3119,
"s": 3099,
"text": " Python – Operators"
},
{
"code": null,
"e": 3146,
"s": 3119,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 3179,
"s": 3146,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 3198,
"s": 3179,
"text": " Python – Keywords"
},
{
"code": null,
"e": 3219,
"s": 3198,
"text": " Python – Data Types"
},
{
"code": null,
"e": 3248,
"s": 3219,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 3278,
"s": 3248,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 3301,
"s": 3278,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 3325,
"s": 3301,
"text": " Python – String to Int"
},
{
"code": null,
"e": 3358,
"s": 3325,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 3381,
"s": 3358,
"text": " Python – if statement"
},
{
"code": null,
"e": 3410,
"s": 3381,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 3436,
"s": 3410,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 3471,
"s": 3436,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 3491,
"s": 3471,
"text": " Python – raw_input"
},
{
"code": null,
"e": 3515,
"s": 3491,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 3544,
"s": 3515,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 3567,
"s": 3544,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 3597,
"s": 3567,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 3622,
"s": 3597,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 3652,
"s": 3622,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 3682,
"s": 3652,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 3705,
"s": 3682,
"text": " Python – Constructors"
},
{
"code": null,
"e": 3736,
"s": 3705,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 3758,
"s": 3736,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 3779,
"s": 3758,
"text": " Python – Decorators"
},
{
"code": null,
"e": 3815,
"s": 3779,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 3845,
"s": 3815,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 3879,
"s": 3845,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 3905,
"s": 3879,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 3943,
"s": 3905,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 3971,
"s": 3943,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 3995,
"s": 3971,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 4021,
"s": 3995,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 4053,
"s": 4021,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 4079,
"s": 4053,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 4107,
"s": 4079,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 4138,
"s": 4107,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 4169,
"s": 4138,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 4202,
"s": 4169,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 4237,
"s": 4202,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 4274,
"s": 4237,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4312,
"s": 4274,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 4338,
"s": 4312,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 4363,
"s": 4338,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 4403,
"s": 4363,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 4438,
"s": 4403,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 4473,
"s": 4438,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 4502,
"s": 4473,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 4528,
"s": 4502,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 4554,
"s": 4528,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 4586,
"s": 4554,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 4614,
"s": 4586,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 4654,
"s": 4614,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 4688,
"s": 4654,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 4713,
"s": 4688,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 4734,
"s": 4713,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 4765,
"s": 4734,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 4802,
"s": 4765,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 4839,
"s": 4802,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 4861,
"s": 4839,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 4899,
"s": 4861,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 4922,
"s": 4899,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 4960,
"s": 4922,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 4991,
"s": 4960,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 5029,
"s": 4991,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 5069,
"s": 5029,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 5116,
"s": 5069,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 5148,
"s": 5116,
"text": " Howto – Sort dictionary by key"
}
] |
TypeScript - Array some() | some() method tests whether some element in the array passes the test implemented by the provided function.
array.some(callback[, thisObject]);
callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
If some element passes the test, then it returns true, otherwise false.
function isBigEnough(element, index, array) {
return (element >= 10);
}
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
console.log("Returned value is : " + retval );
var retval = [12, 5, 8, 1, 4].some(isBigEnough);
console.log("Returned value is : " + retval );
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Returned value is : false
Returned value is : true
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2156,
"s": 2048,
"text": "some() method tests whether some element in the array passes the test implemented by the provided function."
},
{
"code": null,
"e": 2193,
"s": 2156,
"text": "array.some(callback[, thisObject]);\n"
},
{
"code": null,
"e": 2239,
"s": 2193,
"text": "callback − Function to test for each element."
},
{
"code": null,
"e": 2285,
"s": 2239,
"text": "callback − Function to test for each element."
},
{
"code": null,
"e": 2345,
"s": 2285,
"text": "thisObject − Object to use as this when executing callback."
},
{
"code": null,
"e": 2405,
"s": 2345,
"text": "thisObject − Object to use as this when executing callback."
},
{
"code": null,
"e": 2477,
"s": 2405,
"text": "If some element passes the test, then it returns true, otherwise false."
},
{
"code": null,
"e": 2782,
"s": 2477,
"text": "function isBigEnough(element, index, array) { \n return (element >= 10); \n \n} \n \nvar retval = [2, 5, 8, 1, 4].some(isBigEnough);\nconsole.log(\"Returned value is : \" + retval ); \n \nvar retval = [12, 5, 8, 1, 4].some(isBigEnough); \nconsole.log(\"Returned value is : \" + retval );\n"
},
{
"code": null,
"e": 2842,
"s": 2782,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2869,
"s": 2842,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2922,
"s": 2869,
"text": "Returned value is : false \nReturned value is : true\n"
},
{
"code": null,
"e": 2955,
"s": 2922,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2969,
"s": 2955,
"text": " Antonio Papa"
},
{
"code": null,
"e": 3002,
"s": 2969,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3016,
"s": 3002,
"text": " Haider Malik"
},
{
"code": null,
"e": 3051,
"s": 3016,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3071,
"s": 3051,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3104,
"s": 3071,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3118,
"s": 3104,
"text": " Sean Bradley"
},
{
"code": null,
"e": 3153,
"s": 3118,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3169,
"s": 3153,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3202,
"s": 3169,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3202,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3229,
"s": 3222,
"text": " Print"
},
{
"code": null,
"e": 3240,
"s": 3229,
"text": " Add Notes"
}
] |
Keywords in Java | Keywords in Java are reserved words that represent predefined actions, internal processes etc. Because of this, keywords cannot be used as names of variables, functions, objects etc.
The main difference between keywords and identifiers is that keywords are reserved words that represent predefined actions while identifiers are the names of variables, functions, objects etc.
Some of the keywords in the Java are given as follows −
A program that demonstrates keywords is given as follows −
Live Demo
public class Example {
public static void main(String[] args) {
int i = 5;
char c = 'A';
System.out.println("i = " + i);
System.out.println("c = " + c);
}
}
i = 5
c = A
Now let us understand the above program.
The keywords in the above program are int and char that specify integer and character data types respectively. Also i and c are identifiers.
In the above program, the values of i and c are defined and then they are printed. The code snippet that demonstrates this is given as follows.
int i = 5;
char c = 'A';
System.out.println("i = " + i);
System.out.println("c = " + c); | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Keywords in Java are reserved words that represent predefined actions, internal processes etc. Because of this, keywords cannot be used as names of variables, functions, objects etc."
},
{
"code": null,
"e": 1438,
"s": 1245,
"text": "The main difference between keywords and identifiers is that keywords are reserved words that represent predefined actions while identifiers are the names of variables, functions, objects etc."
},
{
"code": null,
"e": 1494,
"s": 1438,
"text": "Some of the keywords in the Java are given as follows −"
},
{
"code": null,
"e": 1553,
"s": 1494,
"text": "A program that demonstrates keywords is given as follows −"
},
{
"code": null,
"e": 1564,
"s": 1553,
"text": " Live Demo"
},
{
"code": null,
"e": 1721,
"s": 1564,
"text": "public class Example {\npublic static void main(String[] args) {\nint i = 5;\nchar c = 'A';\nSystem.out.println(\"i = \" + i);\nSystem.out.println(\"c = \" + c);\n}\n}"
},
{
"code": null,
"e": 1733,
"s": 1721,
"text": "i = 5\nc = A"
},
{
"code": null,
"e": 1774,
"s": 1733,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1915,
"s": 1774,
"text": "The keywords in the above program are int and char that specify integer and character data types respectively. Also i and c are identifiers."
},
{
"code": null,
"e": 2059,
"s": 1915,
"text": "In the above program, the values of i and c are defined and then they are printed. The code snippet that demonstrates this is given as follows."
},
{
"code": null,
"e": 2148,
"s": 2059,
"text": "int i = 5;\nchar c = 'A';\nSystem.out.println(\"i = \" + i);\nSystem.out.println(\"c = \" + c);"
}
] |
time.Now() Function in Golang With Examples - GeeksforGeeks | 21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Now() function in Go language is used to find the current local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func Now() Time
Return Value: It returns the current local time.
Example 1:
// Golang program to illustrate the usage of// time.Now() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling Now() method tm := time.Now() // Prints current // local time in UTC fmt.Printf("%s", tm)}
Output:
2020-04-09 11:24:14.785868848 +0000 UTC m=+0.000187421
Here, current time is returned in UTC.
Example 2:
// Golang program to illustrate the usage of// time.Now() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling Now() method tm := time.Now() tm1 := time.Now() // Prints current local time in UTC fmt.Printf("%s\n", tm) // Sleep for 10 seconds time.Sleep(10 * time.Second) // Prints the current time after 10 // seconds of the sleep is over fmt.Printf("%s", tm1)}
Output:
2020-04-09 11:37:59.087484568 +0000 UTC m=+0.000106559
2020-04-09 11:37:59.087484779 +0000 UTC m=+0.000106736
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strings in Golang
Time Durations in Golang
How to Parse JSON in Golang?
Structures in Golang
Defer Keyword in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Class and Object in Golang
Rune in Golang
Function Arguments in Golang | [
{
"code": null,
"e": 25813,
"s": 25785,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 26117,
"s": 25813,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Now() function in Go language is used to find the current local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 26125,
"s": 26117,
"text": "Syntax:"
},
{
"code": null,
"e": 26142,
"s": 26125,
"text": "func Now() Time\n"
},
{
"code": null,
"e": 26191,
"s": 26142,
"text": "Return Value: It returns the current local time."
},
{
"code": null,
"e": 26202,
"s": 26191,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// time.Now() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling Now() method tm := time.Now() // Prints current // local time in UTC fmt.Printf(\"%s\", tm)}",
"e": 26512,
"s": 26202,
"text": null
},
{
"code": null,
"e": 26520,
"s": 26512,
"text": "Output:"
},
{
"code": null,
"e": 26576,
"s": 26520,
"text": "2020-04-09 11:24:14.785868848 +0000 UTC m=+0.000187421\n"
},
{
"code": null,
"e": 26615,
"s": 26576,
"text": "Here, current time is returned in UTC."
},
{
"code": null,
"e": 26626,
"s": 26615,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// time.Now() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling Now() method tm := time.Now() tm1 := time.Now() // Prints current local time in UTC fmt.Printf(\"%s\\n\", tm) // Sleep for 10 seconds time.Sleep(10 * time.Second) // Prints the current time after 10 // seconds of the sleep is over fmt.Printf(\"%s\", tm1)}",
"e": 27114,
"s": 26626,
"text": null
},
{
"code": null,
"e": 27122,
"s": 27114,
"text": "Output:"
},
{
"code": null,
"e": 27233,
"s": 27122,
"text": "2020-04-09 11:37:59.087484568 +0000 UTC m=+0.000106559\n2020-04-09 11:37:59.087484779 +0000 UTC m=+0.000106736\n"
},
{
"code": null,
"e": 27245,
"s": 27233,
"text": "GoLang-time"
},
{
"code": null,
"e": 27257,
"s": 27245,
"text": "Go Language"
},
{
"code": null,
"e": 27355,
"s": 27257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27373,
"s": 27355,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27398,
"s": 27373,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27427,
"s": 27398,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 27448,
"s": 27427,
"text": "Structures in Golang"
},
{
"code": null,
"e": 27472,
"s": 27448,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 27493,
"s": 27472,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 27548,
"s": 27493,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 27575,
"s": 27548,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 27590,
"s": 27575,
"text": "Rune in Golang"
}
] |
H2 Database - Commit | COMMIT is a command from the SQL grammar used to commit the transaction. We can either commit the specific transaction or we can commit the currently executed transaction.
There are two different syntaxes for COMMIT command.
Following is the generic syntax for the commit command to commit the current transaction.
COMMIT [ WORK ]
Following is the generic syntax for the commit command to commit the specific transaction.
COMMIT TRANSACTION transactionName
In this example, let us commit the current transaction using the following command.
COMMIT
The above command produces the following output.
Committed successfully
In this example, we will commit the transaction named tx_test using the following command.
COMMIT TRANSACTION tx_test;
The above command produces the following output.
Committed successfully
14 Lectures
1 hours
Mahesh Kumar
100 Lectures
9.5 hours
Hari Om Singh
108 Lectures
8 hours
Pavan Lalwani
10 Lectures
1 hours
Deepti Trivedi
20 Lectures
2 hours
Deepti Trivedi
14 Lectures
1 hours
Deepti Trivedi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2279,
"s": 2107,
"text": "COMMIT is a command from the SQL grammar used to commit the transaction. We can either commit the specific transaction or we can commit the currently executed transaction."
},
{
"code": null,
"e": 2332,
"s": 2279,
"text": "There are two different syntaxes for COMMIT command."
},
{
"code": null,
"e": 2422,
"s": 2332,
"text": "Following is the generic syntax for the commit command to commit the current transaction."
},
{
"code": null,
"e": 2440,
"s": 2422,
"text": "COMMIT [ WORK ] \n"
},
{
"code": null,
"e": 2531,
"s": 2440,
"text": "Following is the generic syntax for the commit command to commit the specific transaction."
},
{
"code": null,
"e": 2567,
"s": 2531,
"text": "COMMIT TRANSACTION transactionName\n"
},
{
"code": null,
"e": 2651,
"s": 2567,
"text": "In this example, let us commit the current transaction using the following command."
},
{
"code": null,
"e": 2659,
"s": 2651,
"text": "COMMIT\n"
},
{
"code": null,
"e": 2708,
"s": 2659,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2732,
"s": 2708,
"text": "Committed successfully\n"
},
{
"code": null,
"e": 2823,
"s": 2732,
"text": "In this example, we will commit the transaction named tx_test using the following command."
},
{
"code": null,
"e": 2852,
"s": 2823,
"text": "COMMIT TRANSACTION tx_test;\n"
},
{
"code": null,
"e": 2901,
"s": 2852,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2926,
"s": 2901,
"text": "Committed successfully \n"
},
{
"code": null,
"e": 2959,
"s": 2926,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2973,
"s": 2959,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 3009,
"s": 2973,
"text": "\n 100 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 3024,
"s": 3009,
"text": " Hari Om Singh"
},
{
"code": null,
"e": 3058,
"s": 3024,
"text": "\n 108 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3073,
"s": 3058,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3106,
"s": 3073,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3122,
"s": 3106,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3155,
"s": 3122,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3171,
"s": 3155,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3204,
"s": 3171,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3220,
"s": 3204,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3227,
"s": 3220,
"text": " Print"
},
{
"code": null,
"e": 3238,
"s": 3227,
"text": " Add Notes"
}
] |
Check if a number is perfect square without finding square root in C++ | Suppose a number is given, we have to check whether the number is a perfect square or not. We will not use the square root operation to check it. Suppose a number 1024 is there, this is a perfect square, but 1000 is not a perfect square. The logic is simple, we have to follow this algorithm to get the result.
isPerfectSquare(n) −
input − The number n
output − true, if the number is a perfect square, otherwise, false
begin
for i := 1, i2 ≤ n, increase i by 1:
if n is divisible by i, and n / i = i, then
return true
done
return false
end
Live Demo
#include <iostream>
using namespace std;
bool isPerfectSquare(int number) {
for (int i = 1; i * i <= number; i++) {
if ((number % i == 0) && (number / i == i)) {
return true;
}
}
return false;
}
int main() {
int n = 1024;
if(isPerfectSquare(n)){
cout << n << " is perfect square number";
} else {
cout << n << " is not a perfect square number";
}
}
1024 is perfect square number | [
{
"code": null,
"e": 1373,
"s": 1062,
"text": "Suppose a number is given, we have to check whether the number is a perfect square or not. We will not use the square root operation to check it. Suppose a number 1024 is there, this is a perfect square, but 1000 is not a perfect square. The logic is simple, we have to follow this algorithm to get the result."
},
{
"code": null,
"e": 1394,
"s": 1373,
"text": "isPerfectSquare(n) −"
},
{
"code": null,
"e": 1415,
"s": 1394,
"text": "input − The number n"
},
{
"code": null,
"e": 1482,
"s": 1415,
"text": "output − true, if the number is a perfect square, otherwise, false"
},
{
"code": null,
"e": 1627,
"s": 1482,
"text": "begin\n for i := 1, i2 ≤ n, increase i by 1:\n if n is divisible by i, and n / i = i, then\n return true\n done\n return false\nend"
},
{
"code": null,
"e": 1638,
"s": 1627,
"text": " Live Demo"
},
{
"code": null,
"e": 2041,
"s": 1638,
"text": "#include <iostream>\nusing namespace std;\nbool isPerfectSquare(int number) {\n for (int i = 1; i * i <= number; i++) {\n if ((number % i == 0) && (number / i == i)) {\n return true;\n }\n }\n return false;\n}\nint main() {\n int n = 1024;\n if(isPerfectSquare(n)){\n cout << n << \" is perfect square number\";\n } else {\n cout << n << \" is not a perfect square number\";\n }\n}"
},
{
"code": null,
"e": 2071,
"s": 2041,
"text": "1024 is perfect square number"
}
] |
From soup to nuts guide for setting up a conda environment | by Ebru Cucen | Towards Data Science | Hello! Conda is one of the most popular tools at data science community, and yet, it can be confusing to understand the steps and the cost of implementing that step, as there is hardly a single place explains, so I decided to write one up.
I will focus on three topics, the first one is about conda installer options, Anaconda, miniconda, and miniforge, what you will be missing by not using one. The second topic will be about setting up an environment, you can reliably use for multiple projects, and how to modify when you need more configuration. And the last part is about the relationship of channels with environments and packages, which is also an ignored topic, but very important to show good engineering skills if you want to productionize your work with minimum trouble.
PS: I am on macOS Catalina 10.15.7, and have the Conda version 4.9.0. If you have questions on specific versions, please leave a comment.
So, what am I promising you may get, by the end of this article would be understanding how to set up your conda environment through the lens of the opportunity cost by choosing between:
miniconda and miniforge installers
naming environments as unique and standard
adding channels globally and specific to your environment
installing packages from different channels
Hope you enjoy, and I’ll see you at the end!
conda is an open-source, cross-platform, package, dependency and environment management tool for -in theory- any language (but mostly supported on Data Science and Machine Learning specific languages, such as Python, R, Ruby, C/C++, FORTRAN, ...). Anaconda is the company who developed it first, then open-sourced under the BSD license. It has more functionality than both pip and virtual env together can offer. Pip is a package manager on top of Python for a limited number of libraries, i.e. it can’t install Python. Virtualenv is a simple environment manager, can’t install packages at all... I guess you are convinced to use conda at this point, so we can continue!
The top three installers for installing conda are Anaconda, miniconda and miniforge. The first two are developed by Anaconda, and available on their website, whereas miniforge is created by the community recently as miniconda does not have any not support foraarch64 architecture.
If you need specific requirements, like running your models on aarch64(arm64) or ppc64le (POWER8/9) architectures, you should use miniforge installation. It has also support for PyPy, a light version of Python. During the installation, it sets conda-forgeas the default -and the only- channel and does not have the defaults channel. We will talk about channels on the next part more in detail.
Another reason to use miniforge is the commercial use restriction(*) on Anaconda/miniconda is due to a recent change on Term Of Service of Anaconda, where it is declared as a violation to use the Repository for commercial activities, which includes usage of the packages installed from the defaults channel.
Also, there are a couple of open-source projects already moved from mini-conda to miniforge, this and this, which suggests there will be an increase at the community supporting this repo.
If you are happy with ToS and don’t need the architecture requirements, we are left with 2 options, Anaconda or miniconda. If you want the full version which provides a one-off installation, and if you have 5GB disk space, Anaconda will install Python + 250 packages for you. It may* be a good choice for new starters, as it has commonly used packages ready to use, as well as applications such as Anaconda Navigator, where you can launch your JupyterLab, pySpider IDE for your environments. Anaconda also has multiple editions, i.e. Individual edition is the free version, Enterprise edition is for your team if you want to extend and manage the customisation of packages and channels privately.
And our last option is the minimal installer miniconda will be a good choice, as it will set up defaults channel. *It is better than Anaconda installation because you learn more about which packages to download and you don’t have to free up 5 GB.
PS: If you think you are missing out Anaconda Navigator, Spyder you can install with conda, the first one is available in the default channel, and Spyder is available on both.
$ conda install anaconda-navigator$ conda install spyder
🛑 There are also different methods to run our installers:
Local: Depending on your environment both installers offer different releases: either as a package (i.e. exe for Windows platforms), as a script (for Linux platforms) or both (pkg** and sh for macOS platforms). ** miniconda only, miniforge does not support it (yet).
Cloud VM: Only miniconda has an offer of AMI images for AWS if you want to isolate your environment and run on the cloud.
Container: Docker installers are available for both: miniconda and miniforge
CI/CD Pipeline: Both miniconda and miniforge have Github actions for multiple packages it support and it can take the hard work off from your shoulders.
Conda environment is an abstract way of organising multiple packages and their dependency together. Any new environment we create has a directory where all the packages will be downloaded to, and any configuration, history related to this environment will be stored. If you have installed the Anaconda’s installer, it creates an environment called base on the anaconda's installation directory. You can check this out by running conda env list command: (*) refers to the default environment (when we are not using any environments actively).
$ conda env list# conda environments:#base * /Users/ebrucucen/opt/anaconda3
It’s all good, but we want our very own environment. There are 2 conventions on how to name your environments.
First one is you can give unique names to your environment. This implementation creates an environment for each version of Python (as it is the main language we are all interested, right?), such as conda-py37 or env-py3.8 for Python 3.7 and Python 3.8 versions respectively. This is great, if you are new to environments, possibly you won’t have many versions of Pythons, with multiple packages with complex dependency trees. You can access your environment from any project folder, and follow the conda documentation when executing the commands involving environments without any issues as the environment will be set up on the standard locations (/user/.../envs/)
To create an environment, we use conda create command, followed by the environment name, and a list of package=version pairs, where versions are optional, with the tradeoff installing the latest versions.
$ conda create --name env-py3.8 python=3.8 numpy=1.19.5
The second option is using common name to all of your environments, and create a new one for each project folder, such as conda-env. This means, for any project folder you are working on, you can reference the environment name the same way, and use in any on your automation scripts in a consistent manner. Please note, the subcommand --prefix is exclusively mutual with the--name pick your poison carefully!
$ conda create --prefix /<possibly a long path>/conda-env python=3.7# or if you are already on the same directory:$ conda create --prefix ./conda-env python=3.7
Whichever naming convention you have chosen, now you have an environment, (either env-py3.8 or conda-env or both(!)), and next thing we need to do is to activate, so we can start installing packages to these environments:
$ conda activate env-py3.8
which (by default) displays environment name on the command-line, ready to take next set of instructions....
(env-py3.8) $
or
$ conda activate ./conda-env
results in not so pretty display, and definitely not a great use of your space
(/<possibly a long path>/conda-env) $
To change this behaviour to display simply the environment name, you can modify .condarc file (which is by default on your home directory,~/.condarc, if you are not sure you can find out by conda config — show-sources) :
conda config --set env_prompt '({name})'
Now, if you have managed to follow me to this point, we should have an environment, activated waiting for us to install packages.
If you want to breathe and have a bit deep dive, check out the subdirectories of the env folders, where conda-meta folder contains history file to track each action on this environment, JSON files for each package with its build number, dependencies, and file locations listed... If you found/know anything interesting, please do leave a comment, it will help us to understand the environment mystery better. We need packages, and channels help us to get them with the right version and dependencies, let’s move next!
Channels are repositories for our packages. Each channel, maintained separately, may have a different version of the packages, different build for each version, and the same version of the packages may have different dependencies in each channel. Checkout the Stackoverflow question for more discussion on this.
A good example is for the most common two packages, NumPy and Tensorflow, where Anaconda’s defaults channel and conda-forge has different versions available.
numpy 1.19.5 py39he588a01_1 conda-forgenumpy 1.19.2 py39he57783f_0 pkgs/maintensorflow 2.0.0 mkl_py37hda344b4_0 pkgs/maintensorflow 1.14.0 hcba10bf_0 conda-forge
To avoid one confusion, this does not mean if we want to install tensorflow 2.0.0 version referencing conda-forge channel, but it means conda will try to reach out to default channel for the tensorflow 2.0 modules available and prioritised conda-forge for each dependency, which in return you will get:
_tflow_select pkgs/main/osx-64::_tflow_select-2.3.0-mkl absl-py conda-forge/osx-64::absl-py-0.11.0-py37hf985489_0 ... tensorboard pkgs/main/noarch::tensorboard-2.0.0-pyhb38c66f_1 tensorflow pkgs/main/osx-64::tensorflow-2.0.0-mkl_py37hda344b4_0 tensorflow-base pkgs/main/osx-64::tensorflow-base-2.0.0-mkl_py37h66b1bf0_0 tensorflow-estima~ pkgs/main/noarch::tensorflow-estimator-2.0.0-pyh2649769_0 termcolor conda-forge/noarch::termcolor-1.1.0-py_2 werkzeug conda-forge/noarch::werkzeug-1.0.1-pyh9f0ad1d_0
Add channels
As we mentioned above, the default channel for miniconda and Anaconda installations is defaults channel, whereas for miniforge, the default channel will be conda-forge channel. We can display our channels by looking at the configuration file (independent of the fact that whether you are in an activated environment or you are not):
$ conda config --show-sources
which results in something similar to this (yours will be slightly different):
==> /Users/ebrucucen/.condarc <==auto_update_conda: Falsessl_verify: Truechannels: - conda-forge - defaults
You can add channels globally, or local to your environment when you are in the activated environment. For global installation, you can call conda config add conda-canary to test the packages to be published to live within 24 hour
$ conda config --add channels conda-canary
We can also create a channel-specific to an environment. Let’s say we want to install genomics related packages to our env-py3.8 environment, then we can activate an environment, passing the--envargument to it, and add the bioconda channel to it:
$ conda activate env-py3.8(env-py3.8) $conda config --env --add channels bioconda
The result will be similar to this (you may/may not have defaults channels)
(env-py3.8) $conda config --show-sources==> /Users/ebrucucen/.condarc <==auto_update_conda: Falsessl_verify: Truechannels: - conda-canary - conda-forge - defaults==> /Users/ebrucucen/opt/anaconda3/envs/env-py3.8/.condarc <==channels: - bioconda - defaults
Append channel
One thing you may have noticed is that the add command modifies the config file with putting the latest additional channel to the top of the list. conda is opinionated about the order of the channels, as it is a priority list in essence. If our new channel should go to the bottom, rather than to the top, we can use the append argument (or modify the config file, I hear you)
(env-py3.8) $conda config --env --append channels test-channel
if we check out the configuration file, we will see our channel as the last item ( yes, you are right, there is no channel validation happens during the execution of add/append channel commands, but it will error when you want to search/install packages)
(env-py3.8) $conda config --show-sources==> /Users/ebrucucen/.condarc <==auto_update_conda: Falsessl_verify: Truechannels: - conda-canary - conda-forge - defaults==> /Users/ebrucucen/opt/anaconda3/envs/env-py3.8/.condarc <==channels: - bioconda - defaults - test-channel
Remove channels
If you want to remove a channel (either a mistake you have done or you don’t need it any more), is quite as simple as running the --remove argument, and with the same principle where you need to specify the --env tag to remove the channel from the activated environment, otherwise, conda will give an error to tell you it can’t find the channel.
(env-py3.8) $conda config --env --remove channels test-channel
And finally, we can install our packages now. To find out what you need, I recommend Anaconda search, which gives the versions and the downloads for each package, you have a better understanding of your options, plus you can find good jupyternotebooks for your packages.
Since each environment has a prioritised list of channels, any installation will checklist one by one whether the version (if specified) is available or not.
$ conda search spyder
Top 6 ways I use to install packages are: on a specific environment, of a specific version, of a specific build ( which can be gobbledygook), from a specific channel, and also with dependencies or without dependencies. For the first 3, we can use this format:
$ conda install -n <env-name> -c <channel> <package_name>=<version>=<build_string>$ conda install -n env-py3.9 -c conda-forge numpy=1.19.5=py39he588a01_1
conda install by default installs the dependant packages. We should explicitly tell we don’t want the dependencies (danger Williams, I assume we know what we are doing at this point).
$ conda install -c conda-forge numpy --no-deps
Thank you for your patience, and reading through my post. Now, you have a conda set up with an environment, and channels ready to install any package (as well as Pip, and other tools) you need as I promised with the reasoning behind each choice. Hope you enjoyed it. It is a simple process, and you can customise as much as you want, such as creating your own channels, packages, will all the support available. Happy condaing! | [
{
"code": null,
"e": 412,
"s": 172,
"text": "Hello! Conda is one of the most popular tools at data science community, and yet, it can be confusing to understand the steps and the cost of implementing that step, as there is hardly a single place explains, so I decided to write one up."
},
{
"code": null,
"e": 955,
"s": 412,
"text": "I will focus on three topics, the first one is about conda installer options, Anaconda, miniconda, and miniforge, what you will be missing by not using one. The second topic will be about setting up an environment, you can reliably use for multiple projects, and how to modify when you need more configuration. And the last part is about the relationship of channels with environments and packages, which is also an ignored topic, but very important to show good engineering skills if you want to productionize your work with minimum trouble."
},
{
"code": null,
"e": 1093,
"s": 955,
"text": "PS: I am on macOS Catalina 10.15.7, and have the Conda version 4.9.0. If you have questions on specific versions, please leave a comment."
},
{
"code": null,
"e": 1279,
"s": 1093,
"text": "So, what am I promising you may get, by the end of this article would be understanding how to set up your conda environment through the lens of the opportunity cost by choosing between:"
},
{
"code": null,
"e": 1314,
"s": 1279,
"text": "miniconda and miniforge installers"
},
{
"code": null,
"e": 1357,
"s": 1314,
"text": "naming environments as unique and standard"
},
{
"code": null,
"e": 1415,
"s": 1357,
"text": "adding channels globally and specific to your environment"
},
{
"code": null,
"e": 1459,
"s": 1415,
"text": "installing packages from different channels"
},
{
"code": null,
"e": 1504,
"s": 1459,
"text": "Hope you enjoy, and I’ll see you at the end!"
},
{
"code": null,
"e": 2175,
"s": 1504,
"text": "conda is an open-source, cross-platform, package, dependency and environment management tool for -in theory- any language (but mostly supported on Data Science and Machine Learning specific languages, such as Python, R, Ruby, C/C++, FORTRAN, ...). Anaconda is the company who developed it first, then open-sourced under the BSD license. It has more functionality than both pip and virtual env together can offer. Pip is a package manager on top of Python for a limited number of libraries, i.e. it can’t install Python. Virtualenv is a simple environment manager, can’t install packages at all... I guess you are convinced to use conda at this point, so we can continue!"
},
{
"code": null,
"e": 2456,
"s": 2175,
"text": "The top three installers for installing conda are Anaconda, miniconda and miniforge. The first two are developed by Anaconda, and available on their website, whereas miniforge is created by the community recently as miniconda does not have any not support foraarch64 architecture."
},
{
"code": null,
"e": 2850,
"s": 2456,
"text": "If you need specific requirements, like running your models on aarch64(arm64) or ppc64le (POWER8/9) architectures, you should use miniforge installation. It has also support for PyPy, a light version of Python. During the installation, it sets conda-forgeas the default -and the only- channel and does not have the defaults channel. We will talk about channels on the next part more in detail."
},
{
"code": null,
"e": 3158,
"s": 2850,
"text": "Another reason to use miniforge is the commercial use restriction(*) on Anaconda/miniconda is due to a recent change on Term Of Service of Anaconda, where it is declared as a violation to use the Repository for commercial activities, which includes usage of the packages installed from the defaults channel."
},
{
"code": null,
"e": 3346,
"s": 3158,
"text": "Also, there are a couple of open-source projects already moved from mini-conda to miniforge, this and this, which suggests there will be an increase at the community supporting this repo."
},
{
"code": null,
"e": 4043,
"s": 3346,
"text": "If you are happy with ToS and don’t need the architecture requirements, we are left with 2 options, Anaconda or miniconda. If you want the full version which provides a one-off installation, and if you have 5GB disk space, Anaconda will install Python + 250 packages for you. It may* be a good choice for new starters, as it has commonly used packages ready to use, as well as applications such as Anaconda Navigator, where you can launch your JupyterLab, pySpider IDE for your environments. Anaconda also has multiple editions, i.e. Individual edition is the free version, Enterprise edition is for your team if you want to extend and manage the customisation of packages and channels privately."
},
{
"code": null,
"e": 4290,
"s": 4043,
"text": "And our last option is the minimal installer miniconda will be a good choice, as it will set up defaults channel. *It is better than Anaconda installation because you learn more about which packages to download and you don’t have to free up 5 GB."
},
{
"code": null,
"e": 4466,
"s": 4290,
"text": "PS: If you think you are missing out Anaconda Navigator, Spyder you can install with conda, the first one is available in the default channel, and Spyder is available on both."
},
{
"code": null,
"e": 4523,
"s": 4466,
"text": "$ conda install anaconda-navigator$ conda install spyder"
},
{
"code": null,
"e": 4581,
"s": 4523,
"text": "🛑 There are also different methods to run our installers:"
},
{
"code": null,
"e": 4848,
"s": 4581,
"text": "Local: Depending on your environment both installers offer different releases: either as a package (i.e. exe for Windows platforms), as a script (for Linux platforms) or both (pkg** and sh for macOS platforms). ** miniconda only, miniforge does not support it (yet)."
},
{
"code": null,
"e": 4970,
"s": 4848,
"text": "Cloud VM: Only miniconda has an offer of AMI images for AWS if you want to isolate your environment and run on the cloud."
},
{
"code": null,
"e": 5047,
"s": 4970,
"text": "Container: Docker installers are available for both: miniconda and miniforge"
},
{
"code": null,
"e": 5200,
"s": 5047,
"text": "CI/CD Pipeline: Both miniconda and miniforge have Github actions for multiple packages it support and it can take the hard work off from your shoulders."
},
{
"code": null,
"e": 5742,
"s": 5200,
"text": "Conda environment is an abstract way of organising multiple packages and their dependency together. Any new environment we create has a directory where all the packages will be downloaded to, and any configuration, history related to this environment will be stored. If you have installed the Anaconda’s installer, it creates an environment called base on the anaconda's installation directory. You can check this out by running conda env list command: (*) refers to the default environment (when we are not using any environments actively)."
},
{
"code": null,
"e": 5826,
"s": 5742,
"text": "$ conda env list# conda environments:#base * /Users/ebrucucen/opt/anaconda3"
},
{
"code": null,
"e": 5937,
"s": 5826,
"text": "It’s all good, but we want our very own environment. There are 2 conventions on how to name your environments."
},
{
"code": null,
"e": 6603,
"s": 5937,
"text": "First one is you can give unique names to your environment. This implementation creates an environment for each version of Python (as it is the main language we are all interested, right?), such as conda-py37 or env-py3.8 for Python 3.7 and Python 3.8 versions respectively. This is great, if you are new to environments, possibly you won’t have many versions of Pythons, with multiple packages with complex dependency trees. You can access your environment from any project folder, and follow the conda documentation when executing the commands involving environments without any issues as the environment will be set up on the standard locations (/user/.../envs/)"
},
{
"code": null,
"e": 6808,
"s": 6603,
"text": "To create an environment, we use conda create command, followed by the environment name, and a list of package=version pairs, where versions are optional, with the tradeoff installing the latest versions."
},
{
"code": null,
"e": 6864,
"s": 6808,
"text": "$ conda create --name env-py3.8 python=3.8 numpy=1.19.5"
},
{
"code": null,
"e": 7273,
"s": 6864,
"text": "The second option is using common name to all of your environments, and create a new one for each project folder, such as conda-env. This means, for any project folder you are working on, you can reference the environment name the same way, and use in any on your automation scripts in a consistent manner. Please note, the subcommand --prefix is exclusively mutual with the--name pick your poison carefully!"
},
{
"code": null,
"e": 7436,
"s": 7273,
"text": "$ conda create --prefix /<possibly a long path>/conda-env python=3.7# or if you are already on the same directory:$ conda create --prefix ./conda-env python=3.7"
},
{
"code": null,
"e": 7658,
"s": 7436,
"text": "Whichever naming convention you have chosen, now you have an environment, (either env-py3.8 or conda-env or both(!)), and next thing we need to do is to activate, so we can start installing packages to these environments:"
},
{
"code": null,
"e": 7685,
"s": 7658,
"text": "$ conda activate env-py3.8"
},
{
"code": null,
"e": 7794,
"s": 7685,
"text": "which (by default) displays environment name on the command-line, ready to take next set of instructions...."
},
{
"code": null,
"e": 7808,
"s": 7794,
"text": "(env-py3.8) $"
},
{
"code": null,
"e": 7811,
"s": 7808,
"text": "or"
},
{
"code": null,
"e": 7840,
"s": 7811,
"text": "$ conda activate ./conda-env"
},
{
"code": null,
"e": 7919,
"s": 7840,
"text": "results in not so pretty display, and definitely not a great use of your space"
},
{
"code": null,
"e": 7957,
"s": 7919,
"text": "(/<possibly a long path>/conda-env) $"
},
{
"code": null,
"e": 8178,
"s": 7957,
"text": "To change this behaviour to display simply the environment name, you can modify .condarc file (which is by default on your home directory,~/.condarc, if you are not sure you can find out by conda config — show-sources) :"
},
{
"code": null,
"e": 8219,
"s": 8178,
"text": "conda config --set env_prompt '({name})'"
},
{
"code": null,
"e": 8349,
"s": 8219,
"text": "Now, if you have managed to follow me to this point, we should have an environment, activated waiting for us to install packages."
},
{
"code": null,
"e": 8867,
"s": 8349,
"text": "If you want to breathe and have a bit deep dive, check out the subdirectories of the env folders, where conda-meta folder contains history file to track each action on this environment, JSON files for each package with its build number, dependencies, and file locations listed... If you found/know anything interesting, please do leave a comment, it will help us to understand the environment mystery better. We need packages, and channels help us to get them with the right version and dependencies, let’s move next!"
},
{
"code": null,
"e": 9179,
"s": 8867,
"text": "Channels are repositories for our packages. Each channel, maintained separately, may have a different version of the packages, different build for each version, and the same version of the packages may have different dependencies in each channel. Checkout the Stackoverflow question for more discussion on this."
},
{
"code": null,
"e": 9337,
"s": 9179,
"text": "A good example is for the most common two packages, NumPy and Tensorflow, where Anaconda’s defaults channel and conda-forge has different versions available."
},
{
"code": null,
"e": 9596,
"s": 9337,
"text": "numpy 1.19.5 py39he588a01_1 conda-forgenumpy 1.19.2 py39he57783f_0 pkgs/maintensorflow 2.0.0 mkl_py37hda344b4_0 pkgs/maintensorflow 1.14.0 hcba10bf_0 conda-forge"
},
{
"code": null,
"e": 9899,
"s": 9596,
"text": "To avoid one confusion, this does not mean if we want to install tensorflow 2.0.0 version referencing conda-forge channel, but it means conda will try to reach out to default channel for the tensorflow 2.0 modules available and prioritised conda-forge for each dependency, which in return you will get:"
},
{
"code": null,
"e": 10463,
"s": 9899,
"text": "_tflow_select pkgs/main/osx-64::_tflow_select-2.3.0-mkl absl-py conda-forge/osx-64::absl-py-0.11.0-py37hf985489_0 ... tensorboard pkgs/main/noarch::tensorboard-2.0.0-pyhb38c66f_1 tensorflow pkgs/main/osx-64::tensorflow-2.0.0-mkl_py37hda344b4_0 tensorflow-base pkgs/main/osx-64::tensorflow-base-2.0.0-mkl_py37h66b1bf0_0 tensorflow-estima~ pkgs/main/noarch::tensorflow-estimator-2.0.0-pyh2649769_0 termcolor conda-forge/noarch::termcolor-1.1.0-py_2 werkzeug conda-forge/noarch::werkzeug-1.0.1-pyh9f0ad1d_0"
},
{
"code": null,
"e": 10476,
"s": 10463,
"text": "Add channels"
},
{
"code": null,
"e": 10809,
"s": 10476,
"text": "As we mentioned above, the default channel for miniconda and Anaconda installations is defaults channel, whereas for miniforge, the default channel will be conda-forge channel. We can display our channels by looking at the configuration file (independent of the fact that whether you are in an activated environment or you are not):"
},
{
"code": null,
"e": 10839,
"s": 10809,
"text": "$ conda config --show-sources"
},
{
"code": null,
"e": 10918,
"s": 10839,
"text": "which results in something similar to this (yours will be slightly different):"
},
{
"code": null,
"e": 11028,
"s": 10918,
"text": "==> /Users/ebrucucen/.condarc <==auto_update_conda: Falsessl_verify: Truechannels: - conda-forge - defaults"
},
{
"code": null,
"e": 11259,
"s": 11028,
"text": "You can add channels globally, or local to your environment when you are in the activated environment. For global installation, you can call conda config add conda-canary to test the packages to be published to live within 24 hour"
},
{
"code": null,
"e": 11302,
"s": 11259,
"text": "$ conda config --add channels conda-canary"
},
{
"code": null,
"e": 11549,
"s": 11302,
"text": "We can also create a channel-specific to an environment. Let’s say we want to install genomics related packages to our env-py3.8 environment, then we can activate an environment, passing the--envargument to it, and add the bioconda channel to it:"
},
{
"code": null,
"e": 11631,
"s": 11549,
"text": "$ conda activate env-py3.8(env-py3.8) $conda config --env --add channels bioconda"
},
{
"code": null,
"e": 11707,
"s": 11631,
"text": "The result will be similar to this (you may/may not have defaults channels)"
},
{
"code": null,
"e": 11968,
"s": 11707,
"text": "(env-py3.8) $conda config --show-sources==> /Users/ebrucucen/.condarc <==auto_update_conda: Falsessl_verify: Truechannels: - conda-canary - conda-forge - defaults==> /Users/ebrucucen/opt/anaconda3/envs/env-py3.8/.condarc <==channels: - bioconda - defaults"
},
{
"code": null,
"e": 11983,
"s": 11968,
"text": "Append channel"
},
{
"code": null,
"e": 12360,
"s": 11983,
"text": "One thing you may have noticed is that the add command modifies the config file with putting the latest additional channel to the top of the list. conda is opinionated about the order of the channels, as it is a priority list in essence. If our new channel should go to the bottom, rather than to the top, we can use the append argument (or modify the config file, I hear you)"
},
{
"code": null,
"e": 12423,
"s": 12360,
"text": "(env-py3.8) $conda config --env --append channels test-channel"
},
{
"code": null,
"e": 12678,
"s": 12423,
"text": "if we check out the configuration file, we will see our channel as the last item ( yes, you are right, there is no channel validation happens during the execution of add/append channel commands, but it will error when you want to search/install packages)"
},
{
"code": null,
"e": 12955,
"s": 12678,
"text": "(env-py3.8) $conda config --show-sources==> /Users/ebrucucen/.condarc <==auto_update_conda: Falsessl_verify: Truechannels: - conda-canary - conda-forge - defaults==> /Users/ebrucucen/opt/anaconda3/envs/env-py3.8/.condarc <==channels: - bioconda - defaults - test-channel"
},
{
"code": null,
"e": 12971,
"s": 12955,
"text": "Remove channels"
},
{
"code": null,
"e": 13317,
"s": 12971,
"text": "If you want to remove a channel (either a mistake you have done or you don’t need it any more), is quite as simple as running the --remove argument, and with the same principle where you need to specify the --env tag to remove the channel from the activated environment, otherwise, conda will give an error to tell you it can’t find the channel."
},
{
"code": null,
"e": 13380,
"s": 13317,
"text": "(env-py3.8) $conda config --env --remove channels test-channel"
},
{
"code": null,
"e": 13651,
"s": 13380,
"text": "And finally, we can install our packages now. To find out what you need, I recommend Anaconda search, which gives the versions and the downloads for each package, you have a better understanding of your options, plus you can find good jupyternotebooks for your packages."
},
{
"code": null,
"e": 13809,
"s": 13651,
"text": "Since each environment has a prioritised list of channels, any installation will checklist one by one whether the version (if specified) is available or not."
},
{
"code": null,
"e": 13831,
"s": 13809,
"text": "$ conda search spyder"
},
{
"code": null,
"e": 14091,
"s": 13831,
"text": "Top 6 ways I use to install packages are: on a specific environment, of a specific version, of a specific build ( which can be gobbledygook), from a specific channel, and also with dependencies or without dependencies. For the first 3, we can use this format:"
},
{
"code": null,
"e": 14245,
"s": 14091,
"text": "$ conda install -n <env-name> -c <channel> <package_name>=<version>=<build_string>$ conda install -n env-py3.9 -c conda-forge numpy=1.19.5=py39he588a01_1"
},
{
"code": null,
"e": 14429,
"s": 14245,
"text": "conda install by default installs the dependant packages. We should explicitly tell we don’t want the dependencies (danger Williams, I assume we know what we are doing at this point)."
},
{
"code": null,
"e": 14476,
"s": 14429,
"text": "$ conda install -c conda-forge numpy --no-deps"
}
] |
\qquad - Tex Command | \qquad - Used to create 2em space.
{ \qquad}
\qquad command creates 2em space.
|\qquad\hphantom{|}|
|||
|\qquad\hphantom{|}|
|||
|\qquad\hphantom{|}|
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8021,
"s": 7986,
"text": "\\qquad - Used to create 2em space."
},
{
"code": null,
"e": 8031,
"s": 8021,
"text": "{ \\qquad}"
},
{
"code": null,
"e": 8065,
"s": 8031,
"text": "\\qquad command creates 2em space."
},
{
"code": null,
"e": 8095,
"s": 8065,
"text": "\n|\\qquad\\hphantom{|}|\n\n|||\n\n\n"
},
{
"code": null,
"e": 8123,
"s": 8095,
"text": "|\\qquad\\hphantom{|}|\n\n|||\n\n"
},
{
"code": null,
"e": 8144,
"s": 8123,
"text": "|\\qquad\\hphantom{|}|"
},
{
"code": null,
"e": 8176,
"s": 8144,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8189,
"s": 8176,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8222,
"s": 8189,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8235,
"s": 8222,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8267,
"s": 8235,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8303,
"s": 8267,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8338,
"s": 8303,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8355,
"s": 8338,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8388,
"s": 8355,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8402,
"s": 8388,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8434,
"s": 8402,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8449,
"s": 8434,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8456,
"s": 8449,
"text": " Print"
},
{
"code": null,
"e": 8467,
"s": 8456,
"text": " Add Notes"
}
] |
Find a pair with given target in BST | Practice | GeeksforGeeks | Given a Binary Search Tree and a target sum. Check whether there's a pair of Nodes in the BST with value summing up to the target sum.
Example 1:
Input:
2
/ \
1 3
sum = 5
Output: 1
Explanation:
Nodes with value 2 and 3 sum up to 5.
Example 2:
Input:
6
/
5
/
3
/ \
1 4
sum = 2
Output: 0
Explanation:
There's no pair that sums up to 2.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isPairPresent() that takes a root node and a target value as a parameter and returns 1 if there's a pair of Nodes in the BST with values summing up to the target sum, else returns 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of Nodes ≤ 105
1 ≤ Sum ≤ 106
0
sagrikasoni2 days ago
class Solution
{
// root : the root Node of the given BST
// target : the target sum
public ArrayList<Integer>inorder (Node root, ArrayList<Integer> a){
if(root!=null){
if (root.left!=null)
inorder(root.left,a);
a.add(root.data);
if(root.right!=null)
inorder(root.right,a);
}
return a;
}
public int isPairPresent(Node root, int target)
{
ArrayList<Integer> ar = new ArrayList<Integer>();
inorder(root,ar);
HashSet<Integer> hs = new HashSet<Integer>();
for(int i =0;i<ar.size();i++){
if(hs.contains(target-ar.get(i)))
return 1;
hs.add(ar.get(i));
}
return 0;
}
}
0
adarshgupta4012 weeks ago
Easy JAva Code-
class Solution
{
public int isPairPresent(Node root, int k)
{
ArrayList<Integer> list = new ArrayList<>();
inorder(root, list);
int i=0, j=list.size() -1;
while(i< j){
int sum = list.get(i) + list.get(j);
if( sum == k ) return 1;
else if(sum > k ) j--;
else i++;
}
return 0;
}
public void inorder( Node root, ArrayList<Integer> list){
if(root == null) return ;
inorder(root.left, list);
list.add( root.data);
inorder(root.right, list);
}
}
0
amishasahu3282 weeks ago
class BSTIterator
{
stack<Node*> st;
bool reverse = true;
// reverse -> true [before]
// reverse -> false [next]
public:
BSTIterator(Node *root, bool isReversed){
reverse = isReversed;
pushAll(root);
}
int next()
{
Node *root = st.top();
st.pop();
if(!reverse) pushAll(root->right);
else pushAll(root->left);
return root->data;
}
void pushAll(Node *root)
{
while(root)
{
st.push(root);
if(!reverse) root = root->left;
else root = root->right;
}
}
};
class Solution{
public:
// root : the root Node of the given BST
// target : the target sum
int isPairPresent(struct Node *root, int target)
{
//add code here.
if(!root) return 0;
BSTIterator left(root, false);
BSTIterator right(root, true);
int i = left.next();
int j = right.next();
while(i < j)
{
if(i + j == target) return 1;
else if(i + j < target) i = left.next();
else j = right.next();
}
return 0;
}
};
0
dronzerdracel3 weeks ago
Inorder traversal|2 pointer
void solve(struct Node *root,vector<int>&v){
if(!root)
return;
solve(root->left,v);
v.push_back(root->data);
solve(root->right,v);
}
int isPairPresent(struct Node *root, int target)
{
//add code here.
vector<int>v;
solve(root,v);
int i=0,j=v.size()-1;
while(i<j){
int sum=v[i]+v[j];
if(sum==target)
return 1;
else if(sum>target)
j--;
else
i++;
}
return false;
}
0
parthbabbar0012 months ago
class Solution{
private:
void inOrder(struct Node *root,vector<int>& ans){
if(root==NULL){
return ;
}
inOrder(root->left,ans);
ans.push_back(root->data);
inOrder(root->right,ans);
}
public:
// root : the root Node of the given BST
// target : the target sum
int isPairPresent(struct Node *root, int target)
{
vector<int> ans;
inOrder(root,ans);
int i=0;
int j=ans.size()-1;
while(i<j){
int sum = ans[i] + ans[j];
if(sum==target){
return 1;
}
else if(sum>target){
j--;
}else{
i++;
}
}
return 0;
}
0
lindan1232 months ago
unordered_map<int,int> m;
vector<int> vec;
void traversel(struct Node* root)
{
if(!root)return ;
traversel(root->left);
m[root->data]++;
vec.push_back(root->data);
traversel(root->right);
}
int isPairPresent(struct Node *root, int tar)
{
traversel(root);
for(int i=0;i<vec.size();i++)
{
if(vec[i]<tar)
{
int num = tar - vec[i];
if(m.find(num)!=m.end())
{
return 1;
}
}
else
{
return 0;
}
}
return 0;
}
Time Taken : 1.5sec
Cpp
+1
charigardash2 months ago
class Solution
{
// root : the root Node of the given BST
// target : the target sum
Stack<Node> s1,s2;
void find1(Node a){
while(a!=null){
s1.push(a);
a=a.left;
}
}void find2(Node a){
while(a!=null){
s2.push(a);
a=a.right;
}
}
public int isPairPresent(Node root, int target)
{
// Write your code here
s1=new Stack<>();
s2=new Stack<>();
find1(root);
find2(root);
while(s1.size()>0&&s2.size()>0){
if(s1.peek().data+s2.peek().data==target)return 1;
else if(s1.peek().data+s2.peek().data>target){
Node n=s2.peek();
s2.pop();
find2(n.left);
}else{
Node n=s1.peek();
s1.pop();
find1(n.right);
}
}return 0;
}
}
0
pratyushpandey7302 months ago
class Solution{
public:
// root : the root Node of the given BST
// target : the target sum
void helper(struct Node *root, vector<int> &v){
if(root==NULL) return;
v.push_back(root->data);
helper(root->left,v);
helper(root->right,v);
}
int isPairPresent(struct Node *root, int target)
{
if(root==NULL) return 0;
vector<int> v;
helper(root,v);
sort(v.begin(),v.end());
int i = 0;
int j = v.size() - 1;
int flag = 0;
while(i<j){
if(v[i] + v[j] == target){
flag = 1;
break;
}else if(v[i] + v[j] > target){
j--;
}else{
i++;
}
}
if(flag) return 1;
else return 0;
}
};
+1
binnukaniki1232 months ago
class Solution{ // root : the root Node of the given BST // target : the target sum HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); int c=0;int ta; public int isPairPresent(Node root, int target) { // Write your code here ta=target; inorder(root); return c; } public void inorder(Node root){ if(root==null || c==1)return; if(root.data<ta){ int p=ta-root.data; if(hm.containsKey(p)){ c=1;return; } hm.put(root.data,1); } inorder(root.left); inorder(root.right); }}
+2
sainikcodefreak2 months ago
class Solution{ public: // root : the root Node of the given BST // target : the target sum unordered_set<int>s; int isPairPresent(struct Node *root, int target) { //add code here. if(root==NULL) { return 0; } if(s.count(target-root->data)) { return 1; } else { s.insert(root->data); } return isPairPresent(root->left,target)|| isPairPresent(root->right,target); }};
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": 374,
"s": 238,
"text": "Given a Binary Search Tree and a target sum. Check whether there's a pair of Nodes in the BST with value summing up to the target sum. "
},
{
"code": null,
"e": 385,
"s": 374,
"text": "Example 1:"
},
{
"code": null,
"e": 499,
"s": 385,
"text": "Input:\n 2\n / \\\n 1 3\nsum = 5\nOutput: 1 \nExplanation: \nNodes with value 2 and 3 sum up to 5.\n"
},
{
"code": null,
"e": 510,
"s": 499,
"text": "Example 2:"
},
{
"code": null,
"e": 672,
"s": 510,
"text": "Input:\n 6\n / \n 5 \n /\n 3 \n / \\\n 1 4\nsum = 2\nOutput: 0 \nExplanation: \nThere's no pair that sums up to 2.\n"
},
{
"code": null,
"e": 953,
"s": 672,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isPairPresent() that takes a root node and a target value as a parameter and returns 1 if there's a pair of Nodes in the BST with values summing up to the target sum, else returns 0. "
},
{
"code": null,
"e": 1033,
"s": 953,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the BST)."
},
{
"code": null,
"e": 1086,
"s": 1033,
"text": "Constraints:\n1 ≤ Number of Nodes ≤ 105\n1 ≤ Sum ≤ 106"
},
{
"code": null,
"e": 1088,
"s": 1086,
"text": "0"
},
{
"code": null,
"e": 1110,
"s": 1088,
"text": "sagrikasoni2 days ago"
},
{
"code": null,
"e": 1882,
"s": 1110,
"text": "class Solution\n{\n // root : the root Node of the given BST\n // target : the target sum\n public ArrayList<Integer>inorder (Node root, ArrayList<Integer> a){\n if(root!=null){\n if (root.left!=null)\n inorder(root.left,a);\n a.add(root.data);\n if(root.right!=null)\n inorder(root.right,a);\n }\n return a;\n }\n public int isPairPresent(Node root, int target)\n {\n ArrayList<Integer> ar = new ArrayList<Integer>();\n inorder(root,ar);\n HashSet<Integer> hs = new HashSet<Integer>();\n for(int i =0;i<ar.size();i++){\n if(hs.contains(target-ar.get(i)))\n return 1;\n hs.add(ar.get(i));\n }\n \n return 0;\n \n \n }\n}"
},
{
"code": null,
"e": 1884,
"s": 1882,
"text": "0"
},
{
"code": null,
"e": 1910,
"s": 1884,
"text": "adarshgupta4012 weeks ago"
},
{
"code": null,
"e": 1926,
"s": 1910,
"text": "Easy JAva Code-"
},
{
"code": null,
"e": 2523,
"s": 1926,
"text": "class Solution\n{\n public int isPairPresent(Node root, int k)\n {\n ArrayList<Integer> list = new ArrayList<>();\n inorder(root, list);\n int i=0, j=list.size() -1;\n while(i< j){\n int sum = list.get(i) + list.get(j);\n if( sum == k ) return 1;\n else if(sum > k ) j--;\n else i++;\n }\n \n return 0;\n }\n public void inorder( Node root, ArrayList<Integer> list){ \n if(root == null) return ;\n inorder(root.left, list);\n list.add( root.data);\n inorder(root.right, list);\n }\n}"
},
{
"code": null,
"e": 2525,
"s": 2523,
"text": "0"
},
{
"code": null,
"e": 2550,
"s": 2525,
"text": "amishasahu3282 weeks ago"
},
{
"code": null,
"e": 3739,
"s": 2550,
"text": "class BSTIterator\n{\n stack<Node*> st;\n bool reverse = true;\n // reverse -> true [before]\n // reverse -> false [next]\n public:\n BSTIterator(Node *root, bool isReversed){\n reverse = isReversed;\n pushAll(root);\n }\n int next()\n {\n Node *root = st.top();\n st.pop();\n if(!reverse) pushAll(root->right);\n else pushAll(root->left);\n return root->data;\n }\n void pushAll(Node *root)\n {\n while(root)\n {\n st.push(root);\n if(!reverse) root = root->left;\n else root = root->right;\n }\n }\n \n};\nclass Solution{\n public:\n // root : the root Node of the given BST\n // target : the target sum\n int isPairPresent(struct Node *root, int target)\n {\n //add code here.\n if(!root) return 0;\n BSTIterator left(root, false);\n BSTIterator right(root, true);\n \n int i = left.next();\n int j = right.next();\n while(i < j)\n {\n if(i + j == target) return 1;\n else if(i + j < target) i = left.next();\n else j = right.next();\n }\n return 0;\n }\n};"
},
{
"code": null,
"e": 3741,
"s": 3739,
"text": "0"
},
{
"code": null,
"e": 3766,
"s": 3741,
"text": "dronzerdracel3 weeks ago"
},
{
"code": null,
"e": 3794,
"s": 3766,
"text": "Inorder traversal|2 pointer"
},
{
"code": null,
"e": 4300,
"s": 3794,
"text": "void solve(struct Node *root,vector<int>&v){\n if(!root)\n return;\n solve(root->left,v);\n v.push_back(root->data);\n solve(root->right,v);\n }\n int isPairPresent(struct Node *root, int target)\n {\n //add code here.\n vector<int>v;\n solve(root,v);\n int i=0,j=v.size()-1;\n while(i<j){\n int sum=v[i]+v[j];\n if(sum==target)\n return 1;\n else if(sum>target)\n j--;\n else\n i++;\n }\n return false;\n }"
},
{
"code": null,
"e": 4302,
"s": 4300,
"text": "0"
},
{
"code": null,
"e": 4329,
"s": 4302,
"text": "parthbabbar0012 months ago"
},
{
"code": null,
"e": 5093,
"s": 4329,
"text": "class Solution{\n private:\n void inOrder(struct Node *root,vector<int>& ans){\n if(root==NULL){\n return ;\n }\n \n inOrder(root->left,ans);\n ans.push_back(root->data);\n inOrder(root->right,ans);\n \n }\n\n public:\n // root : the root Node of the given BST\n // target : the target sum\n int isPairPresent(struct Node *root, int target)\n {\n vector<int> ans;\n inOrder(root,ans);\n int i=0;\n int j=ans.size()-1;\n while(i<j){\n int sum = ans[i] + ans[j];\n if(sum==target){\n return 1;\n }\n else if(sum>target){\n j--;\n }else{\n i++;\n }\n }\n \n return 0;\n }"
},
{
"code": null,
"e": 5095,
"s": 5093,
"text": "0"
},
{
"code": null,
"e": 5117,
"s": 5095,
"text": "lindan1232 months ago"
},
{
"code": null,
"e": 5818,
"s": 5117,
"text": " unordered_map<int,int> m;\n vector<int> vec;\n void traversel(struct Node* root)\n {\n if(!root)return ;\n \n traversel(root->left);\n m[root->data]++;\n vec.push_back(root->data);\n traversel(root->right);\n }\n int isPairPresent(struct Node *root, int tar)\n {\n traversel(root);\n \n for(int i=0;i<vec.size();i++)\n {\n if(vec[i]<tar)\n {\n int num = tar - vec[i];\n if(m.find(num)!=m.end())\n {\n return 1;\n }\n }\n else\n {\n return 0;\n }\n }\n return 0;\n }"
},
{
"code": null,
"e": 5838,
"s": 5818,
"text": "Time Taken : 1.5sec"
},
{
"code": null,
"e": 5842,
"s": 5838,
"text": "Cpp"
},
{
"code": null,
"e": 5845,
"s": 5842,
"text": "+1"
},
{
"code": null,
"e": 5870,
"s": 5845,
"text": "charigardash2 months ago"
},
{
"code": null,
"e": 6792,
"s": 5870,
"text": "class Solution\n{\n // root : the root Node of the given BST\n // target : the target sum\n Stack<Node> s1,s2;\n void find1(Node a){\n while(a!=null){\n s1.push(a);\n a=a.left;\n }\n }void find2(Node a){\n while(a!=null){\n s2.push(a);\n a=a.right;\n }\n }\n public int isPairPresent(Node root, int target)\n {\n // Write your code here\n s1=new Stack<>();\n s2=new Stack<>();\n find1(root);\n find2(root);\n while(s1.size()>0&&s2.size()>0){\n if(s1.peek().data+s2.peek().data==target)return 1;\n else if(s1.peek().data+s2.peek().data>target){\n Node n=s2.peek();\n s2.pop();\n find2(n.left);\n }else{\n Node n=s1.peek();\n s1.pop();\n find1(n.right);\n }\n }return 0;\n }\n}"
},
{
"code": null,
"e": 6794,
"s": 6792,
"text": "0"
},
{
"code": null,
"e": 6824,
"s": 6794,
"text": "pratyushpandey7302 months ago"
},
{
"code": null,
"e": 7716,
"s": 6824,
"text": "class Solution{\n public:\n // root : the root Node of the given BST\n // target : the target sum\n \n void helper(struct Node *root, vector<int> &v){\n \n if(root==NULL) return;\n \n v.push_back(root->data);\n helper(root->left,v);\n helper(root->right,v);\n }\n \n int isPairPresent(struct Node *root, int target)\n {\n if(root==NULL) return 0;\n vector<int> v;\n helper(root,v);\n \n sort(v.begin(),v.end());\n int i = 0;\n int j = v.size() - 1;\n \n int flag = 0;\n while(i<j){\n \n if(v[i] + v[j] == target){\n flag = 1;\n break;\n }else if(v[i] + v[j] > target){\n j--;\n }else{\n i++;\n }\n }\n \n if(flag) return 1;\n else return 0;\n }\n};"
},
{
"code": null,
"e": 7719,
"s": 7716,
"text": "+1"
},
{
"code": null,
"e": 7746,
"s": 7719,
"text": "binnukaniki1232 months ago"
},
{
"code": null,
"e": 8389,
"s": 7746,
"text": "class Solution{ // root : the root Node of the given BST // target : the target sum HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); int c=0;int ta; public int isPairPresent(Node root, int target) { // Write your code here ta=target; inorder(root); return c; } public void inorder(Node root){ if(root==null || c==1)return; if(root.data<ta){ int p=ta-root.data; if(hm.containsKey(p)){ c=1;return; } hm.put(root.data,1); } inorder(root.left); inorder(root.right); }}"
},
{
"code": null,
"e": 8392,
"s": 8389,
"text": "+2"
},
{
"code": null,
"e": 8420,
"s": 8392,
"text": "sainikcodefreak2 months ago"
},
{
"code": null,
"e": 8857,
"s": 8420,
"text": "class Solution{ public: // root : the root Node of the given BST // target : the target sum unordered_set<int>s; int isPairPresent(struct Node *root, int target) { //add code here. if(root==NULL) { return 0; } if(s.count(target-root->data)) { return 1; } else { s.insert(root->data); } return isPairPresent(root->left,target)|| isPairPresent(root->right,target); }};"
},
{
"code": null,
"e": 9003,
"s": 8857,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 9039,
"s": 9003,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9049,
"s": 9039,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9059,
"s": 9049,
"text": "\nContest\n"
},
{
"code": null,
"e": 9122,
"s": 9059,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9270,
"s": 9122,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9478,
"s": 9270,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 9584,
"s": 9478,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Solidity - Interfaces | Interfaces are similar to abstract contracts and are created using interface keyword. Following are the key characteristics of an interface.
Interface can not have any function with implementation.
Interface can not have any function with implementation.
Functions of an interface can be only of type external.
Functions of an interface can be only of type external.
Interface can not have constructor.
Interface can not have constructor.
Interface can not have state variables.
Interface can not have state variables.
Interface can have enum, structs which can be accessed using interface name dot notation.
Interface can have enum, structs which can be accessed using interface name dot notation.
Try the following code to understand how the interface works in Solidity.
pragma solidity ^0.5.0;
interface Calculator {
function getResult() external view returns(uint);
}
contract Test is Calculator {
constructor() public {}
function getResult() external view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 3
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2696,
"s": 2555,
"text": "Interfaces are similar to abstract contracts and are created using interface keyword. Following are the key characteristics of an interface."
},
{
"code": null,
"e": 2753,
"s": 2696,
"text": "Interface can not have any function with implementation."
},
{
"code": null,
"e": 2810,
"s": 2753,
"text": "Interface can not have any function with implementation."
},
{
"code": null,
"e": 2866,
"s": 2810,
"text": "Functions of an interface can be only of type external."
},
{
"code": null,
"e": 2922,
"s": 2866,
"text": "Functions of an interface can be only of type external."
},
{
"code": null,
"e": 2958,
"s": 2922,
"text": "Interface can not have constructor."
},
{
"code": null,
"e": 2994,
"s": 2958,
"text": "Interface can not have constructor."
},
{
"code": null,
"e": 3034,
"s": 2994,
"text": "Interface can not have state variables."
},
{
"code": null,
"e": 3074,
"s": 3034,
"text": "Interface can not have state variables."
},
{
"code": null,
"e": 3164,
"s": 3074,
"text": "Interface can have enum, structs which can be accessed using interface name dot notation."
},
{
"code": null,
"e": 3254,
"s": 3164,
"text": "Interface can have enum, structs which can be accessed using interface name dot notation."
},
{
"code": null,
"e": 3328,
"s": 3254,
"text": "Try the following code to understand how the interface works in Solidity."
},
{
"code": null,
"e": 3633,
"s": 3328,
"text": "pragma solidity ^0.5.0;\n\ninterface Calculator {\n function getResult() external view returns(uint);\n}\ncontract Test is Calculator {\n constructor() public {}\n function getResult() external view returns(uint){\n uint a = 1; \n uint b = 2;\n uint result = a + b;\n return result;\n }\n}"
},
{
"code": null,
"e": 3715,
"s": 3633,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 3783,
"s": 3715,
"text": "Note − Select Test from dropdown before clicking the deploy button."
},
{
"code": null,
"e": 3798,
"s": 3783,
"text": "0: uint256: 3\n"
},
{
"code": null,
"e": 3833,
"s": 3798,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3833,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3885,
"s": 3850,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3902,
"s": 3885,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3937,
"s": 3902,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3951,
"s": 3937,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 3958,
"s": 3951,
"text": " Print"
},
{
"code": null,
"e": 3969,
"s": 3958,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.