title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
Hamming Distance in Python | Consider we have two integers. We have to find the Hamming distance of them. The hamming distance is the number of bit different bit count between two numbers. So if the numbers are 7 and 15, they are 0111 and 1111 in binary, here the MSb is different, so the Hamming distance is 1.
To solve this, we will follow these steps −
For i = 31 down to 0b1 = right shift of x (i AND 1 time)b2 = right shift of y (i AND 1 time)if b1 = b2, then answer := answer + 0, otherwise answer := answer + 1
b1 = right shift of x (i AND 1 time)
b2 = right shift of y (i AND 1 time)
if b1 = b2, then answer := answer + 0, otherwise answer := answer + 1
return answer
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
ans = 0
for i in range(31,-1,-1):
b1= x>>i&1
b2 = y>>i&1
ans+= not(b1==b2)
#if not(b1==b2):
# print(b1,b2,i)
return ans
ob1 = Solution()
print(ob1.hammingDistance(7, 15))
7
15
1 | [
{
"code": null,
"e": 1345,
"s": 1062,
"text": "Consider we have two integers. We have to find the Hamming distance of them. The hamming distance is the number of bit different bit count between two numbers. So if the numbers are 7 and 15, they are 0111 and 1111 in binary, here the MSb is different, ... |
Python - Ways to Copy Dictionary | A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. They copy() method returns a shallow copy of the dictionary.
Live Demo
#creating a dictionary
original = {1:'vishesh', 2:'python'}
# copying using copy() function
new = original.copy()
# removing all elements from the list Only new list becomes empty as #copy() does shallow copy.
new.clear()
print('new: ', new)
print('original: ', original)
# between = and copy()
original = {1:'Vishesh', 2:'python'}
# copying using copy() function
new = original.copy()
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
original = {1:'one', 2:'two'}
# copying using =
new = original
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
('new: ', {})
('original: ', {1: 'vishesh', 2: 'python'})
('new: ', {})
('original: ', {1: 'Vishesh', 2: 'python'})
('new: ', {})
('original: ', {}) | [
{
"code": null,
"e": 1283,
"s": 1062,
"text": "A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. They copy() method returns a shallow copy of the dictionary."
},
{
"code": null,
... |
MIME Media Types | MIME (Multipurpose Internet Mail Extension) media types were originally devised so that e-mails could include information other than plain text. MIME media types indicate the following things −
How different parts of a message, such as text and attachments, are combined into the message.
How different parts of a message, such as text and attachments, are combined into the message.
The way in which each part of the message is specified.
The way in which each part of the message is specified.
The way different items are encoded for transmission so that even software that was designed to work only with ASCII text can process the message.
The way different items are encoded for transmission so that even software that was designed to work only with ASCII text can process the message.
Now MIME types are not just for use with e-mail; they have been adopted by Web servers as a way to tell Web browsers what type of material was being sent to them so that they can cope with that kind of messages correctly.
MIME content types consist of two parts −
A main type
A sub-type
The main type is separated from the subtype by a forward slash character. For example, text/html for HTML.
This chapter is organized for the main types −
text
image
multipart
audio
video
message
model
application
For example, the text main type contains types of plain text files, such as −
text/plain for plain text files
text/html for HTML files
text/rtf for text files using rich text formatting
MIME types are officially supposed to be assigned and listed by the Internet Assigned Numbers Authority (IANA).
Many of the popular MIME types in this list (all those begin with "x-") are not assigned by the IANA and do not have official status. You can see the list of official MIME types at http://www.iana.org/assignments/media-types/. Those preceded with .vnd are vendorspecific.
When specifying the MIME type of a content-type field you can also indicate the character set for the text being used. If you do not specify a character set, the default is US-ASCII. For example −
content-type:text/plain; charset=iso-8859-1
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2568,
"s": 2374,
"text": "MIME (Multipurpose Internet Mail Extension) media types were originally devised so that e-mails could include information other than plain text. MIME media types indicate the following things −"
},
{
"code": null,
"e": 2663,
"s": 2568,
... |
Histograms Equalization in OpenCV - GeeksforGeeks | 22 Feb, 2018
Prerequisite : Analyze-image-using-histogram
Histogram equalization is a method in image processing of contrast adjustment using the image’s histogram.
This method usually increases the global contrast of many images, especially when the usable data of the image is represented by close contrast values. Through this adjustment, the intensities can be better distributed on the histogram. This allows for areas of lower local contrast to gain a higher contrast. Histogram equalization accomplishes this by effectively spreading out the most frequent intensity values. The method is useful in images with backgrounds and foregrounds that are both bright or both dark.
OpenCV has a function to do this, cv2.equalizeHist(). Its input is just grayscale image and output is our histogram equalized image.
Input Image :
Below is Python3 code implementing Histogram Equalization :
# import Opencvimport cv2 # import Numpyimport numpy as np # read a image using imreadimg = cv2.imread(\'F:\\do_nawab.png\', 0) # creating a Histograms Equalization# of a image using cv2.equalizeHist()equ = cv2.equalizeHist(img) # stacking images side-by-sideres = np.hstack((img, equ)) # show image input vs outputcv2.imshow(\'image\', res) cv2.waitKey(0)cv2.destroyAllWindows()
Output :
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python | [
{
"code": null,
"e": 24107,
"s": 24079,
"text": "\n22 Feb, 2018"
},
{
"code": null,
"e": 24152,
"s": 24107,
"text": "Prerequisite : Analyze-image-using-histogram"
},
{
"code": null,
"e": 24259,
"s": 24152,
"text": "Histogram equalization is a method in image p... |
CSS cue Property - GeeksforGeeks | 20 Nov, 2020
It is a shorthand version for both cue-before and cue-after property. It specifies that an auditory icon played before or after the element to distinguish and set the element.
Syntax:
cue: <cue-before> <cue-after>?
Property Values:
CSS cue-before: It is used to define an auditory icon played before the element to distinguish and set the element.Syntax:cue-before: url|none;Example:<!DOCTYPE html> <html> <head> <style> .gfg { cue-before: url("bell.wav"); } </style> </head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p class="gfg">CSS cue-before Property</p> <audio controls> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio> </body> </html> Output:
Syntax:
cue-before: url|none;
Example:
<!DOCTYPE html> <html> <head> <style> .gfg { cue-before: url("bell.wav"); } </style> </head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p class="gfg">CSS cue-before Property</p> <audio controls> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio> </body> </html>
Output:
CSS cue-after: It is used to define an auditory icon played after the element to distinguish and set the element.Syntax:cue-after: url | none ;Example:<!DOCTYPE html> <html> <head> <style> .gfg { cue-after: url("bell.wav"); } </style> </head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p class="gfg">CSS cue-after Property</p> <audio controls> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio> </body> </html> Output:
Syntax:
cue-after: url | none ;
Example:
<!DOCTYPE html> <html> <head> <style> .gfg { cue-after: url("bell.wav"); } </style> </head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p class="gfg">CSS cue-after Property</p> <audio controls> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio> </body> </html>
Output:
CSS-Properties
Picked
CSS
Web Technologies
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 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n20 Nov, 2020"
},
{
"code": null,
"e": 25553,
"s": 25376,
"text": "It is a shorthand version for both cue-before and cue-after property. It specifies that an auditory icon played before or after the element to distinguish and set ... |
Automate getting Tableau Server Users with REST API and Python | by Cristian Saavedra Desmoineaux | Towards Data Science | How many times someone asked you, can you check if these people have Tableau access? And, when you open the list, it has more than 50 emails.
As a Tableau Site Administrator, one of the most tedious tasks is to return a list to the business owners of the unlicensed people or don’t exist in Tableau server so they can request budget and licenses.
To validate and create the final list is a manual process. It is easy to make mistakes, and it will take many hours if you have a long input list.
I am going to explain how to automate this task using Tableau REST API, Tableau Server Client (TSC) and Python Pandas connecting with a local Tableau Server admin user and using Personal Access Token (PAT)
The main functions look like the following, in this case, It is using PAT to login to Tableau Server.
You need to login to the Server, go to Users, click the filter button, search one by one email or name, and take notes in another tool. You cannot use the web browser search because the pages load in batches, and if you don’t move the scrollbar, it isn’t going to show the name that you are looking for.
In case you haven’t an administrator user to do the test, you can get your own Tableau Online Site by joining as Developer and requesting a free site at https://www.tableau.com/developer/get-site
Before you use REST API, you can test the connection using remote Tab Command. If you don’t have it, you can download and install only the Tab command going to the current Tableau Server release page, and you will find the files at the end of the page.
I am going to use Windows Subsystem Linux (WSL2) with Ubuntu. You need to install java, get the file, install the deb package, refresh your profile opening a new terminal (or with source command) and accept the EULA.
sudo apt updatesudo apt install default-jrewget https://downloads.tableau.com/esdalt/2020.3.0/tableau-tabcmd-2020-3-0_all.debchmod +x tableau-tabcmd-2020-3-0_all.debsudo apt install ./tableau-tabcmd-2020-3-0_all.debtabcmd --accepteula
Use the Tab Command to test the login without check the SSL certification:
tabcmd login --no-certcheck -s https://yourserver.online.tableau.com -u your_user -p your_password -t your_site
We are going to install the Tableau Server Client (TSC) using pip as recommends the documentation at https://tableau.github.io/server-client-python/docs/#install-tsc
pip install tableauserverclientpip install tableauserverclient --upgrade
I am going to use the Tableau Server Client and Python Pandas using Miniconda in WSL2 with Ubuntu. If you need more information about the installation, I left a guide in this previous post
There are two ways to connect to the Tableau Server:
With a local admin user created directly in Tableau Server
Or using Personal Access Token (PAT)
As the documentation said, REST API and TabCmd cannot use SAML for Single Sign-On (SSO), for example, using Office 365 Azure Active Directory. If It is your case, you must use PAT that is available from Tableau Server 2019.4
In both cases, you need to provide the full URL address and the Site plus the login identification.
If you have many sites, to connect to the default, let the site empty like this:
site = ''
With the next Python code, you will be available to connect to Tableau Server.
First, you need to create a PAT in the User Settings you will need the Token Secret and Token Name.
With the following code, you will connect using PAT to Tableau Server.
Using PAT, I created two functions one for validating the email with a regular expression and others to get the list of Tableau Server users adding some cleansing for the text:
Using Python Pandas and Jupyter Lab, the next section will show you how to compare and export to an Excel file. The result should be Anir doesn’t exist, and Elliot is Unlicensed.
My Tableau Server list Users look like this.
And I will use a comma-separated values (CSV) file with the list of emails to find.
The next step is creating a Pandas DataFrame with the list of users from the Tableau Server with the previous functions.
And I check if any user has an invalid email in the username.
Next, I loaded the CSV file into a second DataFrame
And I validate if any user from the CSV has an invalid email to be fixed.
Then I do left join with both DataFrames to keep all emails from the CSV file.
I created outputs to split who have licenses, are Unlicensed, or do not exist.
And save the results into an Excel file using openpyxl
To install openpyxl use the following commands:
conda install openpyxlconda update openpyxl
help.tableau.com
tableau.github.io
github.com
To finish, I am grateful to Evan Slotnick, Anir Agarwal, and Elliott Stam because they showed me the path to beginning with Tableau REST API. | [
{
"code": null,
"e": 314,
"s": 172,
"text": "How many times someone asked you, can you check if these people have Tableau access? And, when you open the list, it has more than 50 emails."
},
{
"code": null,
"e": 519,
"s": 314,
"text": "As a Tableau Site Administrator, one of the ... |
Ruby - Date & Time | The Time class represents dates and times in Ruby. It is a thin layer over the system date and time functionality provided by the operating system. This class may be unable on your system to represent dates before 1970 or after 2038.
This chapter makes you familiar with all the most wanted concepts of date and time.
Following is the simple example to get current date and time −
#!/usr/bin/ruby -w
time1 = Time.new
puts "Current Time : " + time1.inspect
# Time.now is a synonym:
time2 = Time.now
puts "Current Time : " + time2.inspect
This will produce the following result −
Current Time : Mon Jun 02 12:02:39 -0700 2008
Current Time : Mon Jun 02 12:02:39 -0700 2008
We can use Time object to get various components of date and time. Following is the example showing the same −
#!/usr/bin/ruby -w
time = Time.new
# Components of a Time
puts "Current Time : " + time.inspect
puts time.year # => Year of the date
puts time.month # => Month of the date (1 to 12)
puts time.day # => Day of the date (1 to 31 )
puts time.wday # => 0: Day of week: 0 is Sunday
puts time.yday # => 365: Day of year
puts time.hour # => 23: 24-hour clock
puts time.min # => 59
puts time.sec # => 59
puts time.usec # => 999999: microseconds
puts time.zone # => "UTC": timezone name
This will produce the following result −
Current Time : Mon Jun 02 12:03:08 -0700 2008
2008
6
2
1
154
12
3
8
247476
UTC
These two functions can be used to format date in a standard format as follows −
# July 8, 2008
Time.local(2008, 7, 8)
# July 8, 2008, 09:10am, local time
Time.local(2008, 7, 8, 9, 10)
# July 8, 2008, 09:10 UTC
Time.utc(2008, 7, 8, 9, 10)
# July 8, 2008, 09:10:11 GMT (same as UTC)
Time.gm(2008, 7, 8, 9, 10, 11)
Following is the example to get all the components in an array in the following format −
[sec,min,hour,day,month,year,wday,yday,isdst,zone]
Try the following −
#!/usr/bin/ruby -w
time = Time.new
values = time.to_a
p values
This will generate the following result −
[26, 10, 12, 2, 6, 2008, 1, 154, false, "MST"]
This array could be passed to Time.utc or Time.local functions to get different format of dates as follows −
#!/usr/bin/ruby -w
time = Time.new
values = time.to_a
puts Time.utc(*values)
This will generate the following result −
Mon Jun 02 12:15:36 UTC 2008
Following is the way to get time represented internally as seconds since the (platform-dependent) epoch −
# Returns number of seconds since epoch
time = Time.now.to_i
# Convert number of seconds into Time object.
Time.at(time)
# Returns second since epoch which includes microseconds
time = Time.now.to_f
You can use a Time object to get all the information related to Timezones and daylight savings as follows −
time = Time.new
# Here is the interpretation
time.zone # => "UTC": return the timezone
time.utc_offset # => 0: UTC is 0 seconds offset from UTC
time.zone # => "PST" (or whatever your timezone is)
time.isdst # => false: If UTC does not have DST.
time.utc? # => true: if t is in UTC time zone
time.localtime # Convert to local timezone.
time.gmtime # Convert back to UTC.
time.getlocal # Return a new Time object in local zone
time.getutc # Return a new Time object in UTC
There are various ways to format date and time. Here is one example showing a few −
#!/usr/bin/ruby -w
time = Time.new
puts time.to_s
puts time.ctime
puts time.localtime
puts time.strftime("%Y-%m-%d %H:%M:%S")
This will produce the following result −
Mon Jun 02 12:35:19 -0700 2008
Mon Jun 2 12:35:19 2008
Mon Jun 02 12:35:19 -0700 2008
2008-06-02 12:35:19
These directives in the following table are used with the method Time.strftime.
%a
The abbreviated weekday name (Sun).
%A
The full weekday name (Sunday).
%b
The abbreviated month name (Jan).
%B
The full month name (January).
%c
The preferred local date and time representation.
%d
Day of the month (01 to 31).
%H
Hour of the day, 24-hour clock (00 to 23).
%I
Hour of the day, 12-hour clock (01 to 12).
%j
Day of the year (001 to 366).
%m
Month of the year (01 to 12).
%M
Minute of the hour (00 to 59).
%p
Meridian indicator (AM or PM).
%S
Second of the minute (00 to 60).
%U
Week number of the current year, starting with the first Sunday as the first day of the first week (00 to 53).
%W
Week number of the current year, starting with the first Monday as the first day of the first week (00 to 53).
%w
Day of the week (Sunday is 0, 0 to 6).
%x
Preferred representation for the date alone, no time.
%X
Preferred representation for the time alone, no date.
%y
Year without a century (00 to 99).
%Y
Year with century.
%Z
Time zone name.
%%
Literal % character.
You can perform simple arithmetic with time as follows −
now = Time.now # Current time
puts now
past = now - 10 # 10 seconds ago. Time - number => Time
puts past
future = now + 10 # 10 seconds from now Time + number => Time
puts future
diff = future - past # => 10 Time - Time => number of seconds
puts diff
This will produce the following result −
Thu Aug 01 20:57:05 -0700 2013
Thu Aug 01 20:56:55 -0700 2013
Thu Aug 01 20:57:15 -0700 2013
20.0
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2528,
"s": 2294,
"text": "The Time class represents dates and times in Ruby. It is a thin layer over the system date and time functionality provided by the operating system. This class may be unable on your system to represent dates before 1970 or after 2038."
},
{
"code... |
Permutations in Python | Suppose we have a collection of distinct integers; we have to find all possible permutations. So if the array is like [2,1,3], then the result will be [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
To solve this, we will follow these steps −
We will use the recursive approach, this will make the list, start, curr and res
if start > length of list – 1, then add curr into the res, and return
for i in range start to length of given list – 1swap the elements of list present at index start and (start + (i – start))permutation(list, start + 1, curr + [list[start]], res)swap the elements of list present at index start and (start + (i – start))initially call the permutation(arr, 0, [], res)
swap the elements of list present at index start and (start + (i – start))
permutation(list, start + 1, curr + [list[start]], res)
swap the elements of list present at index start and (start + (i – start))
initially call the permutation(arr, 0, [], res)
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def permute(self, nums):
result = []
self.permute_util(nums,0,[],result)
return result
def permute_util(self,given_list,start,curr,result):
if start > len(given_list)-1:
#print(curr)
result.append(curr)
return
for i in range(start,len(given_list)):
self.swap(given_list,start,start+(i-start)) self.permute_util(given_list,start+1,curr+[given_list[start]],result)
#print(given_list)
self.swap(given_list, start, start + (i - start))
def swap(self,nums,index1,index2):
temp = nums[index1]
nums[index1] = nums[index2]
nums[index2] = temp
ob1 = Solution()
print(ob1.permute([1,2,3,4]))
[1,2,3,4]
[[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,3,2],[1,4,2,3],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,3,1],[2,4,1,3],[3,2,1,4],[3,2,4,1],[3,1,2,4],[3,1,4,2],[3,4,1,2],[3,4,2,1],[4,2,3,1],[4,2,1,3],[4,3,2,1],[4,3,1,2],[4,1,3,2],[4,1,2,3]] | [
{
"code": null,
"e": 1268,
"s": 1062,
"text": "Suppose we have a collection of distinct integers; we have to find all possible permutations. So if the array is like [2,1,3], then the result will be [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]"
},
{
"code": null,
"e": 1312,
... |
Generate array of random unique numbers in PHP? | For random unique numbers array, use range() along with shuffle().
The PHP code is as follows
Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$limit_random_array_values = range(10, 20);
shuffle($limit_random_array_values);
$all_five_random_array_value = array_slice($limit_random_array_values ,0,5);
print_r($all_five_random_array_value);
?>
</body>
</html>
This will produce the following output
Array ( [0] => 11 [1] => 14 [2] => 15 [3] => 12 [4] => 18 ) | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "For random unique numbers array, use range() along with shuffle()."
},
{
"code": null,
"e": 1156,
"s": 1129,
"text": "The PHP code is as follows"
},
{
"code": null,
"e": 1167,
"s": 1156,
"text": " Live Demo"
},
... |
How to select the second index in Java JList? | To select the second index, use the setSelectedIndex() method −
JList new JList(sports);
list.setSelectedIndex(2);
The following is an example to select the second index in Java JList −
package my;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class SwingDemo extends JFrame {
static JFrame frame;
static JList list;
public static void main(String[] args) {
frame = new JFrame("JList Demo");
SwingDemo s = new SwingDemo();
JPanel panel = new JPanel();
String sports[]= { "Cricket","Football","Hockey","Rugby"};
list = new JList(sports);
list.setSelectedIndex(2);
panel.add(list);
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To select the second index, use the setSelectedIndex() method −"
},
{
"code": null,
"e": 1177,
"s": 1126,
"text": "JList new JList(sports);\nlist.setSelectedIndex(2);"
},
{
"code": null,
"e": 1248,
"s": 1177,
"tex... |
What is Interface segregation principle and how to implement it in C#? | Clients should not be forced to depend upon interfaces that they don't use.
The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use.
Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one submodule
public interface IProduct {
int ID { get; set; }
double Weight { get; set; }
int Stock { get; set; }
int Inseam { get; set; }
int WaistSize { get; set; }
}
public class Jeans : IProduct {
public int ID { get; set; }
public double Weight { get; set; }
public int Stock { get; set; }
public int Inseam { get; set; }
public int WaistSize { get; set; }
}
public class BaseballCap : IProduct {
public int ID { get; set; }
public double Weight { get; set; }
public int Stock { get; set; }
public int Inseam { get; set; }
public int WaistSize { get; set; }
public int HatSize { get; set; }
}
public interface IProduct {
int ID { get; set; }
double Weight { get; set; }
int Stock { get; set; }
}
public interface IPants {
int Inseam { get; set; }
int WaistSize { get; set; }
}
public interface IHat {
int HatSize { get; set; }
}
public class Jeans : IProduct, IPants {
public int ID { get; set; }
public double Weight { get; set; }
public int Stock { get; set; }
public int Inseam { get; set; }
public int WaistSize { get; set; }
}
public class BaseballCap : IProduct, IHat {
public int ID { get; set; }
public double Weight { get; set; }
public int Stock { get; set; }
public int HatSize { get; set; }
} | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Clients should not be forced to depend upon interfaces that they don't use."
},
{
"code": null,
"e": 1255,
"s": 1138,
"text": "The Interface Segregation Principle states that clients should not be forced to implement interfaces they ... |
Ansible - Introduction | Ansible is simple open source IT engine which automates application deployment, intra service orchestration, cloud provisioning and many other IT tools.
Ansible is easy to deploy because it does not use any agents or custom security infrastructure.
Ansible uses playbook to describe automation jobs, and playbook uses very simple language i.e. YAML (It’s a human-readable data serialization language & is commonly used for configuration files, but could be used in many applications where data is being stored)which is very easy for humans to understand, read and write. Hence the advantage is that even the IT infrastructure support guys can read and understand the playbook and debug if needed (YAML – It is in human readable form).
Ansible is designed for multi-tier deployment. Ansible does not manage one system at time, it models IT infrastructure by describing all of your systems are interrelated. Ansible is completely agentless which means Ansible works by connecting your nodes through ssh(by default). But if you want other method for connection like Kerberos, Ansible gives that option to you.
After connecting to your nodes, Ansible pushes small programs called as “Ansible Modules”. Ansible runs that modules on your nodes and removes them when finished. Ansible manages your inventory in simple text files (These are the hosts file). Ansible uses the hosts file where one can group the hosts and can control the actions on a specific group in the playbooks.
This is the content of hosts file −
#File name: hosts
#Description: Inventory file for your application. Defines machine type abc
node to deploy specific artifacts
# Defines machine type def node to upload
metadata.
[abc-node]
#server1 ansible_host = <target machine for DU deployment> ansible_user = <Ansible
user> ansible_connection = ssh
server1 ansible_host = <your host name> ansible_user = <your unix user>
ansible_connection = ssh
[def-node]
#server2 ansible_host = <target machine for artifact upload>
ansible_user = <Ansible user> ansible_connection = ssh
server2 ansible_host = <host> ansible_user = <user> ansible_connection = ssh
Configuration management in terms of Ansible means that it maintains configuration of the product performance by keeping a record and updating detailed information which describes an enterprise’s hardware and software.
Such information typically includes the exact versions and updates that have been applied to installed software packages and the locations and network addresses of hardware devices. For e.g. If you want to install the new version of WebLogic/WebSphere server on all of the machines present in your enterprise, it is not feasible for you to manually go and update each and every machine.
You can install WebLogic/WebSphere in one go on all of your machines with Ansible playbooks and inventory written in the most simple way. All you have to do is list out the IP addresses of your nodes in the inventory and write a playbook to install WebLogic/WebSphere. Run the playbook from your control machine & it will be installed on all your nodes.
The picture given below shows the working of Ansible.
Ansible works by connecting to your nodes and pushing out small programs, called "Ansible modules" to them. Ansible then executes these modules (over SSH by default), and removes them when finished. Your library of modules can reside on any machine, and there are no servers, daemons, or databases required.
The management node in the above picture is the controlling node (managing node) which controls the entire execution of the playbook. It’s the node from which you are running the installation. The inventory file provides the list of hosts where the Ansible modules needs to be run and the management node does a SSH connection and executes the small modules on the hosts machine and installs the product/software.
Beauty of Ansible is that it removes the modules once those are installed so effectively it connects to host machine , executes the instructions and if it’s successfully installed removes the code which was copied on the host machine which was executed.
41 Lectures
5 hours
AR Shankar
11 Lectures
58 mins
Musab Zayadneh
59 Lectures
15.5 hours
Narendra P
11 Lectures
1 hours
Sagar Mehta
39 Lectures
4 hours
Vikas Yadav
4 Lectures
3.5 hours
GreyCampus Inc.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1944,
"s": 1791,
"text": "Ansible is simple open source IT engine which automates application deployment, intra service orchestration, cloud provisioning and many other IT tools."
},
{
"code": null,
"e": 2040,
"s": 1944,
"text": "Ansible is easy to deploy bec... |
Why you should be using PHATE for dimensionality reduction | by Jamshaid Shahir | Towards Data Science | As data scientists, we often work with high-dimensional data with more than 3 features, or dimensions, of interest. In supervised machine learning, we may use this data for training and classification for example and may reduce the dimensions to speed up the training. In unsupervised learning, we use this type of data for visualization and clustering. In single-cell RNA sequencing (scRNA-seq), for example, we accumulate measurements of tens of thousands of genes per cell for upwards of a million cells. That’s a lot of data that provides a window into the cell’s identity, state, and other properties. More importantly, these properties put it in relation with the myriad of other cells in the dataset. Nevertheless, this creates a massive matrix of 1,000,000 cells and 10,000 genes, with each gene representing a dimension or axis. How do we interpret such data? As humans in a 3-D world, we cannot see anything beyond the three physical dimensions and need a way to capture the essence of the datasets like these while not losing anything of value.
How can we compress this dataset to 2 or 3 dimensions such that the essential information is retained? Your first instinct may be to use PCA or tSNE to project the dataset into a 2-D embedding. However, there are key tradeoffs with each of these methods that may lead to erroneous conclusions about the dataset in question during downstream analysis. With PCA, you lose local relationships between data-points (or cells in our case) at the cost of capturing a global representation. Furthermore, PCA is a linear method, which does not accurately capture complex datasets such as single-cell RNA sequencing data, where we can have a myriad of cell types defined by distinct gene expression portfolios while also undergoing various processes such as cell division, differentiation (specialization of stem cells into more mature cell types like neurons), metabolism, and so forth. tSNE, on the other hand, is a non-linear method that does a better job preserving local relationships but at the cost of shattering the global picture. For example, in stem cell differentiation, stem cells do not automatically turn into, say, a neuron, at the flick of switch (or set of genes in this case), but rather go through a continuum of changes defined by gradual changes in its transcriptomic profile. We often describe this continuum as a trajectory. The problem with tSNE is that it shatters these trajectories, resulting in disjointed clusters of cells, with little information on how one cell type is related to another.
So now that I’ve illustrated the downstream issues with this tradeoff, how can we resolve it? That is where PHATE enters the picture. PHATE — which stands for Potential of Heat diffusion for Affinity-based Transition Embedding — is a newcomer onto the world of dimensionality reduction. Like tSNE, it is a non-linear, unsupervised technique. However, unlike tSNE, which preserves local structure of higher-dimensional data often at the cost of the global structure, PHATE captures the best of both worlds of PCA and tSNE, preserving both local and global relationships between data-points to accurately reflect the high-dimensional dataset in question.
We will continue to use scRNA-seq data as an example. With this dataset, we essentially have an m-by-n matrix of m cells (rows) and n genes (columns), which represent discrete counts of messenger RNA molecules. We first compute a square matrix of the Euclidean distance between each of these cells, which is simply the length of the line segment between two points based on the Cartesian coordinates. In the context of scRNA-seq, these Cartesian coordinates are the gene expression measurements, so intuitively, we would expect cells a short distance apart to be very similar in gene expression, and hence similar cell types, whereas cells further apart to have very different gene expression patterns, and hence reflect starkly different cell types (e.g., a neuron and a red blood cell). However, this metric doesn’t always lend well to that interpretation. This is because of the Curse of Dimensionality, where too many dimensions can cause the data-points in your dataset to appear equidistant from all the others, makes it hard to draw conclusions of trends in your data, derive meaningful clusters and local neighborhoods, and determine other types of patterns. To address this problem, we convert our distances to affinities, which quantify local similarities between observations in our data. (This is where the “A” in PHATE for “Affinity-based” comes from!) These affinities are inversely proportional to the distances such that the further apart two observations are in Euclidean space, the smaller their affinity; likewise, the closer they are, the greater their affinity. Affinities are commonly calculated by using a kernel function to transform your Euclidean distances. In very simple terms, this is your probability mass or density function minus the factors/coefficients that normalize it to ensure that probabilities are between 0 and 1. They are used often in other Machine Learning problems such as support vector machines. One popular kernel you can guess is the Gaussian kernel:
Where x and y are coordinates in a high-dimensional space X, and ε is a bandwidth metric that measures the “spread” or radius of neighborhoods captured by this kernel. The authors of the PHATE paper use a slightly more advanced kernel function that does a better job of quantifying similarities, whose details I will spare for brevity. While this is a handy trick to preserve the local structure of our dataset, just embedding these alone will fracture the global structure as in the case of tSNE. Hence, in addition to retaining the local structure, PHATE’s other objective it to maintain the global relationships across the data. To achieve this, PHATE uses the affinities to “diffuse” through the data via a Markov random-walk. When we say diffuse, we mean the net spread from a region of high concentration to that of low concentration. In the context of affinities, this can be thought of as going from high affinities (i.e., a cluster of cells in our high-dimensional dataset) to lower affinities (i.e., more spread-out cells). More intuitively, we can think of this is the spread of heat in a room going from a warm source (e.g., a fireplace) to a less warm area (e.g., you on your couch), which can be modeled mathematically as the heat equation and whose solution is the heat kernel. This is where the “H” in PHATE, Heat diffusion, comes from. As for a random walk, this represents a trail of successive random steps through our high-dimensional space (i.e., transitioning from cell to cell), where each possible step or transition has a defined probability of going down said route. You can think of this as the heat in room random spreading in the direction of one corner of the room initially then switching directions. This is known more broadly as a stochastic or random process. In our context, we have the probability of cell i going to cell j depends on the last cell we visited. Now with all that terminology out of the way, let’s see how this works in action!
We first calculate initial probabilities of our random walk by normalizing our previously calculated affinities. This produces the following:
where
This gives us an N-by-N transition probability matrix of moving from cell x to cell y within a single time step.
A simpler term for this matrix, used in the PHATE paper, is the diffusion operator. Mathematically, to attain effective diffusion, we raise the diffusion operator to an optimal number of steps t to learn the global structure of our data. This gives us the probability of transitioning from cell x to cell y in t time steps. With larger t, we can cover more distance in the high-dimensional space and learn more about the global structure without getting bogged down by the locality from our single-time step affinity-based probabilities. You can think of this as scouting a hiking trail to build a map of the surroundings: every few steps, you lay down a marker to note your previous position, generally at notable areas (e.g., a large tree, a river bank, etc.), rather than setting markers with every step. This lets you build a general map of the area without getting bogged down by every single twig and branch. For sake of brevity, I’ll spare the technical details of how to calculate this optimal step t, which is described in the PHATE paper, using von Neumann entropy, but this all feeds into the “T” of our algorithm for “Transition”.
Alright, we’ve got our affinities to capture local relationships between nearby cells in one hand and a powered diffusion operator to learn our global space in another. Now what? Embed this powered diffusion operator? Not so fast. One limitation is that the resulting probability-based distances between cells via this operator (or diffusion distances, as the authors define them) are not very sensitive to distances between far away points and can suffer stability issues when we consider boundary points of our high-dimensional space (the paper goes into more detail on these shortcomings). This can be resolved however via the first letter of our acronym, “P”, which stands for Potential. The authors define this clever metric called potential distance, inspired by information theory and stochastic dynamics, where we measure the distance between log-transformed probabilities from the powered diffusion operator. This increases the sensitivity of our resulting distances, and it enables PHATE to preserve and local and global architecture for visualization purposes. Mathematically this is defined as follows:
where
pxt refers to row x of our diffusion operator, which you’ll recall is our transition probability matrix raised to the t’th power.
When we say that this distance metric is more sensitive, suppose the transition probability from cell a to cell b is 0.04, while for cell a to c it’s 0.05. Under these diffusion distances, they are not very sensitive to fold-changes. The distance, 0.01, may suffer sensitivity issues in trying to encapsulate this relationship in a lower dimension projection. However, if we log transform these probabilities and take their distance, we obtain a larger distance of 0.223, which is the same as if these probabilities had been 0.4 and 0.5 respectively (recall that log a - log b = log (a/b)). Pretty neat!
Alright, we’re ready for the “E” part of PHATE, “embedding”! Typically, with these diffusion metrics, we commonly perform an eigen-decomposition (i.e., break it up by eigenvectors of the matrix in question, in this case our powered diffusion operator) to derive a diffusion map of the data, which were a popular approach for studying differentiation trajectories in scRNA-seq data. The problem with this approach, however, is that it shatters trajectories into a myriad of eigenvectors reflecting the diffusion components. This high intrinsic dimensionality consequently renders them unamenable for visualization. To bypass this limitation, the authors embed the potential distance matrix using metric Multidimensional Scaling (metric MDS). This is an embedding method tailored for distance matrices as input by minimizing what’s known as a “stress” function:
While this equation may look intimidating, what it’s essentially doing is measuring the goodness of fit, in this case, how well the embedded coordinates fit the higher-dimensional data we seek to visualize. The smaller the stress, the greater fit. Thus, if the stress of these embedded points is zero, then the data has been successfully captured in this MDS embedding. Small, non-zero values may occur as a result of noise or a small number of MDS dimensions (i.e., m = 2 or 3). However, this level of distortion is generally tolerable so long as trajectories and other key features are preserved.
Everything I’ve discussed up until this point can be visually summarized in this figure from the authors of the PHATE paper:
If you’ve stuck around this long, congratulations! We’re now ready to learn how to implement PHATE in Python and see it in action! For simplicity, we’ll use the smaller version of the popular MNIST dataset where we have 8-by-8 images of hand-drawn digits (you can find an example from the authors of the paper applying PHATE to real scRNA-seq data here).
Install the PHATE library using pip or pip3:
pip install phate
Create a new Python file in your favorite editor or a notebook in Jupyter notebooks and run the following:
Let’s run this program to see the results
python3 mnist_phate.py
Looking at the PHATE embedding, you can see that we have generally clear separation of the digits, while the clusters themselves have unique shapes and distributions. Let’s see how the this compares to PCA and tSNE
PCA (left) overcrowds the data, making it difficult to draw concrete conclusions. tSNE (center) on the other hand does a nice job of separating them out into balled-up clusters, at the cost of a clear global structure of how the digits relate to another, as well as suppressing the unique spread of data within clusters. PHATE (right) reconciles these issues where you can clearly make out the clusters and get a sense of how they relate to one another (e.g., 3 and 9 having a lot of similarity). For the case of digits, this isn’t such a big deal, but for single-cell biology when we’re studying continuous processes such as turning stem cells into neurons, having that added detail of how cells transition from one cell type to another is very useful.
In this article, we learned about the PHATE algorithm, how it works, and how to implement it in Python. As you can see, it does a good job of preserving the local and global aspects of data. For more information on the math behind the PHATE algorithm, as well as more examples and comparisons to other methods like tSNE and UMAP, I encourage you to check out the original publication as well as some tutorials on PHATE and single-cell data analysis from the authors.
I hope you enjoyed this article. Thanks for reading and happy coding!
References:
[1] K. Moon, D. van Dijk, Z. Wang, S. Gigante, D. Burkhart, W. Chen, K. Yim, A. van den Elzen, M.J. Hirn, R.R. Coifman, N.B. Ivanova, G. Wolf, and S. Krishnaswamy, Visualizing structure and transitions in high-dimensional biological data (2019), Nature Biotechnology | [
{
"code": null,
"e": 1228,
"s": 172,
"text": "As data scientists, we often work with high-dimensional data with more than 3 features, or dimensions, of interest. In supervised machine learning, we may use this data for training and classification for example and may reduce the dimensions to speed up... |
Add the slug field inside Django Model - GeeksforGeeks | 05 Mar, 2021
It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. Let’s assume our blog have a post with the title ‘The Django book by Geeksforgeeks’ with primary key id= 2. We might refer to this post with
www.geeksforgeeks.org/posts/2.
Or, we can reference the title like
www.geeksforgeeks.org/posts/The Django book by Geeksforgeeks.
But the problem is spaces are not valid in URLs, they need to be replaced by %20 which is ugly, making it the following
www.geeksforgeeks.org/posts/The%20Django%20book%20by%20geeksforgeeks
But it is not solving meaningful URL. Another option can be
www.geeksforgeeks.org/posts/the-django-book-by-geeksforgeeks
So, the slug is now the-django-book-by-geeksforgeeks. All letters are down cased and spaces are replaced by hyphens -.
Assume that our Blog Post models look similar to this.
Python3
STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'),) class Post(models.Model): title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, null = True, blank = True) text = models.TextField() published_at = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft') class Meta: ordering = ('-published_at', ) def __str__(self): return self.title
Now we need to find a way to convert the title into a slug automatically. We want this script to be triggered every time a new instance of Post model is created. For this purpose, we will use signals.
Note: Add new file util.py in the same directory where settings.py file is saved.
Python3
import string, randomfrom django.db.models.signals import pre_savefrom django.dispatch import receiverfrom django.utils.text import slugify def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug = None): if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ max_length = Klass._meta.get_field('slug').max_length slug = slug[:max_length] qs_exists = Klass.objects.filter(slug = slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug = slug[:max_length-5], randstr = random_string_generator(size = 4)) return unique_slug_generator(instance, new_slug = new_slug) return slug
In many cases when there is a modification in a model’s instance we need to execute some action. Django provides us with an elegant way to handle these situations. The signals are utilities that allow associating events with actions. We can develop a function that will run when a signal calls it. In models.py file of posts app where Post Model was defined, add this in the same file:
Python3
@receiver(pre_save, sender=Post)def pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance)
The pre_save_receiver function should be placed separately outside the Post model.
Note: In urls.py edit detail path with path(‘posts/’, detail). In views.py edit the detail function with
Python3
def detail(request, slug): q = Post.objects.filter(slug__iexact = slug) if q.exists(): q = q.first() else: return HttpResponse('<h1>Post Not Found</h1>') context = { 'post': q } return render(request, 'posts/details.html', context)
The last step is to add the link in HTML file <a href=”/posts/{{ a.slug }}” class=”btn btn-primary”>View</a>. Now we are ready to go to 127.0.0.1:8000/posts/title-you-have-added and it will show you the page details.html.
richarda20
Python Django
Python
Web Technologies
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
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24196,
"s": 24168,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 24479,
"s": 24196,
"text": "It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. Let’s assume our blog ... |
Image Augmentation Examples in Python | by Connor Shorten | Towards Data Science | I am currently working on a study reviewing the depth and effectiveness of image data augmentations. The goal of this research is to learn how to increase our dataset size to train robust Convolutional Network models with limited or small amounts of data.
This study requires listing all the image augmentations we can think of and enumerating all of these combinations to try and improve the performance of an image classification model. Some of the most simple augmentations that come to mind are flipping, translations, rotation, scaling, isolating individual r,g,b color channels, and adding noise. More exciting augmentations are centered around using the Generative Adversarial Network model, sometimes swapping the Generator network with a Genetic Algorithm. Some creative methods have been proposed as well such as applying Instagram-style lighting filters to the images, applying random regional sharpening filters, and adding mean-images based on clustering techniques. This article will show you how to make augmentations on images using NumPy.
Below is a list and illustration of some of these Augmentation techniques, please leave a comment if you can think of any other ways to augment images that may improve the quality of an image classifier.
All Augmentations are done using Numpy without the OpenCV library
# Image Loading Code used for these examplesfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as pltimg = Image.open('./NIKE.png')img = np.array(img)plt.imshow(img)plt.show()
Flipping images is one of the most popular methods of image data augmentation. This is primarily due to the simplicity of the flipping code and how intuitive it is for most problems that flipped images would add value to the model. The model below could be thought of as seeing a left shoe rather than a right shoe, thus with this data augmentation, the model becomes more robust to the potential variations with seeing shoes.
# Flipping images with Numpyflipped_img = np.fliplr(img)plt.imshow(flipped_img)plt.show()
It is easy to imagine the value of translational augmentation with classifiers whose purpose is detection. As if this classification model was trying to detect when the shoe is in the image vs. when it is not. These translations will help it pick up on the shoe without seeing the entire shoe in the frame.
# Shifting Leftfor i in range(HEIGHT, 1, -1): for j in range(WIDTH): if (i < HEIGHT-20): img[j][i] = img[j][i-20] elif (i < HEIGHT-1): img[j][i] = 0plt.imshow(img)plt.show()
# Shifting Rightfor j in range(WIDTH): for i in range(HEIGHT): if (i < HEIGHT-20): img[j][i] = img[j][i+20]plt.imshow(img)plt.show()
# Shifting Upfor j in range(WIDTH): for i in range(HEIGHT): if (j < WIDTH - 20 and j > 20): img[j][i] = img[j+20][i] else: img[j][i] = 0plt.imshow(img)plt.show()
#Shifting Downfor j in range(WIDTH, 1, -1): for i in range(278): if (j < 144 and j > 20): img[j][i] = img[j-20][i]plt.imshow(img)plt.show()
Noise is an interesting augmentation technique that I am starting to become more familar with. I have seen a lot of interesting papers on Adversarial training where you can throw some batch of noise into an image and the model will not be able to classify it correctly as a result. I am still looking at ways to generate better noise than the illustration below. Adding noise may help with lighting distortions and make the model more robust in general.
# ADDING NOISEnoise = np.random.randint(5, size = (164, 278, 4), dtype = 'uint8')for i in range(WIDTH): for j in range(HEIGHT): for k in range(DEPTH): if (img[i][j][k] != 255): img[i][j][k] += noise[i][j][k]plt.imshow(img)plt.show()
I have received a lot of interest with researching the use of Generative Adversarial Networks for data augmentation, below are some of the images I have been able to produce using the MNIST dataset.
As we can tell from the images above, they certainly do look like 3’s, 7’s, and 9’s. I am currently having some trouble extending the architecture of the network to support the 300x300x3 size output of the sneakers compared to the 28x28x1 MNIST digits. However, I am very excited about this research and am looking forward to continuing it!
Thanks for reading this article, hopefully, you now know how to implement basic data augmentations to improve your classification models! | [
{
"code": null,
"e": 428,
"s": 172,
"text": "I am currently working on a study reviewing the depth and effectiveness of image data augmentations. The goal of this research is to learn how to increase our dataset size to train robust Convolutional Network models with limited or small amounts of data.... |
What are class instances in C#? | Class instances are objects. Like any other object-oriented language, C# also has object and classes. Objest are real-world entities and instance of a class. Access the members of the class using an object.
To access the class members, you use the dot (.) operator after the object name. The dot operator links the name of an object with the name of a member for example,
Box Box1 = new Box();
Above you can see Box1 is our object. We will use it to access the members −
Box1.height = 7.0;
You can also use it to call member functions −
Box1.getVolume();
The following is an example showing how objects and class work in C# −
Live Demo
using System;
namespace BoxApplication {
class Box {
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len ) {
length = len;
}
public void setBreadth( double bre ) {
breadth = bre;
}
public void setHeight( double hei ) {
height = hei;
}
public double getVolume() {
return length * breadth * height;
}
}
class Boxtester {
static void Main(string[] args) {
// Creating two objects
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// using objects to call the member functions
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
Volume of Box1 : 210
Volume of Box2 : 1560 | [
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Class instances are objects. Like any other object-oriented language, C# also has object and classes. Objest are real-world entities and instance of a class. Access the members of the class using an object."
},
{
"code": null,
"e": 1434,
... |
Python MySQL - Select Data | You can retrieve/fetch data from a table in MySQL using the SELECT query. This query/statement returns contents of the specified table in tabular form and it is called as result-set.
Following is the syntax of the SELECT query −
SELECT column1, column2, columnN FROM table_name;
Assume we have created a table in MySQL with name cricketers_data as −
CREATE TABLE cricketers_data(
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
And if we have inserted 5 records in to it using INSERT statements as −
insert into cricketers_data values('Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into cricketers_data values('Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into cricketers_data values('Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into cricketers_data values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into cricketers_data values('Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
Following query retrieves the FIRST_NAME and Country values from the table.
mysql> select FIRST_NAME, Country from cricketers_data;
+------------+-------------+
| FIRST_NAME | Country |
+------------+-------------+
| Shikhar | India |
| Jonathan | SouthAfrica |
| Kumara | Srilanka |
| Virat | India |
| Rohit | India |
+------------+-------------+
5 rows in set (0.00 sec)
You can also retrieve all the values of each record using * instated of the name of the columns as −
mysql> SELECT * from cricketers_data;
+------------+------------+---------------+----------------+-------------+
| First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country |
+------------+------------+---------------+----------------+-------------+
| Shikhar | Dhawan | 1981-12-05 | Delhi | India |
| Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica |
| Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka |
| Virat | Kohli | 1988-11-05 | Delhi | India |
| Rohit | Sharma | 1987-04-30 | Nagpur | India |
+------------+------------+---------------+----------------+-------------+
5 rows in set (0.00 sec)
READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python.
The cursor.MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where,
The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones).
The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones).
The fetchone() method fetches the next row in the result of a query and returns it as a tuple.
The fetchone() method fetches the next row in the result of a query and returns it as a tuple.
The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row.
The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row.
Note − A result set is an object that is returned when a cursor object is used to query a table.
rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method.
Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method.
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving single row
sql = '''SELECT * from EMPLOYEE'''
#Executing the query
cursor.execute(sql)
#Fetching 1st row from the table
result = cursor.fetchone();
print(result)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
#Closing the connection
conn.close()
('Krishna', 'Sharma', 19, 'M', 2000.0)
[('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 25, 'M', 5000.0)]
Following example retrieves first two rows of the EMPLOYEE table using the fetchmany() method.
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving single row
sql = '''SELECT * from EMPLOYEE'''
#Executing the query
cursor.execute(sql)
#Fetching 1st row from the table
result = cursor.fetchmany(size =2);
print(result)
#Closing the connection
conn.close()
[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.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": 2402,
"s": 2219,
"text": "You can retrieve/fetch data from a table in MySQL using the SELECT query. This query/statement returns contents of the specified table in tabular form and it is called as result-set."
},
{
"code": null,
"e": 2448,
"s": 2402,
"text": ... |
jQuery Set Content and Attributes | We will use the same three methods from the previous page to set content:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
The following example demonstrates how to set content with the jQuery text(), html(),
and val() methods:
All of the three jQuery methods above: text(), html(),
and val(), also come with a callback function. The callback function has two
parameters: the index of the current element in the list of elements selected
and the original (old) value. You then return the string you wish to use as the
new value from the function.
The following example demonstrates text() and html() with a callback
function:
The jQuery attr() method is also used to set/change attribute values.
The following example demonstrates how to change (set) the value of the href attribute
in a link:
The attr() method also allows you to set multiple attributes at the same
time.
The following example demonstrates how to set both the href and title attributes
at the same time:
The jQuery method attr(), also comes with a callback function. The callback function has two
parameters: the index of the current element in the list of elements selected
and the original (old) attribute value. You then return the string you wish to use as the
new attribute value from the function.
The following example demonstrates attr() with a callback
function:
Use a jQuery method to change the text of a <div> element to "Hello World".
$("div").("");
Start the Exercise
For a complete overview of all jQuery HTML methods, please go to our
jQuery HTML/CSS Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 74,
"s": 0,
"text": "We will use the same three methods from the previous page to set content:"
},
{
"code": null,
"e": 137,
"s": 74,
"text": "text() - Sets or returns the text content of selected elements"
},
{
"code": null,
"e": 219,
"s": 13... |
IMS DB - Secondary Indexing | Secondary Indexing is used when we want to access a database without using the complete concatenated key or when we do not want to use the sequence primary fields.
DL/I stores the pointer to segments of the indexed database in a separate database. Index pointer segment is the only type of secondary index. It consists of two parts −
Prefix Element
Data Element
The prefix part of the index pointer segment contains a pointer to the Index Target Segment. Index target segment is the segment that is accessible using the secondary index.
The data element contains the key value from the segment in the indexed database over which the index is built. This is also known as the index source segment.
Here are the key points to note about Secondary Indexing −
The index source segment and the target source segment need not be the same.
The index source segment and the target source segment need not be the same.
When we set up a secondary index, it is automatically maintained by the DL/I.
When we set up a secondary index, it is automatically maintained by the DL/I.
The DBA defines many secondary indexes as per the multiple access paths. These secondary indexes are stored in a separate index database.
The DBA defines many secondary indexes as per the multiple access paths. These secondary indexes are stored in a separate index database.
We should not create more secondary indexes, as they impose additional processing overhead on the DL/I.
We should not create more secondary indexes, as they impose additional processing overhead on the DL/I.
Points to note −
The field in the index source segment over which the secondary index is built is called as the secondary key.
The field in the index source segment over which the secondary index is built is called as the secondary key.
Any field can be used as a secondary key. It need not be the segments sequence field.
Any field can be used as a secondary key. It need not be the segments sequence field.
Secondary keys can be any combination of single fields within the index source segment.
Secondary keys can be any combination of single fields within the index source segment.
Secondary key values do not have to be unique.
Secondary key values do not have to be unique.
Points to note −
When we build a secondary index, the apparent hierarchical structure of the database is also changed.
When we build a secondary index, the apparent hierarchical structure of the database is also changed.
The index target segment becomes the apparent root segment. As shown in the following image, the Engineering segment becomes the root segment, even if it is not a root segment.
The index target segment becomes the apparent root segment. As shown in the following image, the Engineering segment becomes the root segment, even if it is not a root segment.
The rearrangement of the database structure caused by the secondary index is known as the secondary data structure.
The rearrangement of the database structure caused by the secondary index is known as the secondary data structure.
Secondary data structures do not make any changes to the main physical database structure present on the disk. It is just a way to alter the database structure in front of the application program.
Secondary data structures do not make any changes to the main physical database structure present on the disk. It is just a way to alter the database structure in front of the application program.
Points to note −
When an AND (* or &) operator is used with secondary indexes, it is known as a dependent AND operator.
When an AND (* or &) operator is used with secondary indexes, it is known as a dependent AND operator.
An independent AND (#) allows us to specify qualifications that would be impossible with a dependent AND.
An independent AND (#) allows us to specify qualifications that would be impossible with a dependent AND.
This operator can be used only for secondary indexes where the index source segment is dependent on the index target segment.
This operator can be used only for secondary indexes where the index source segment is dependent on the index target segment.
We can code an SSA with an independent AND to specify that an occurrence of the target segment be processed based on the fields in two or more dependent source segments.
We can code an SSA with an independent AND to specify that an occurrence of the target segment be processed based on the fields in two or more dependent source segments.
01 ITEM-SELECTION-SSA.
05 FILLER PIC X(8).
05 FILLER PIC X(1) VALUE '('.
05 FILLER PIC X(10).
05 SSA-KEY-1 PIC X(8).
05 FILLER PIC X VALUE '#'.
05 FILLER PIC X(10).
05 SSA-KEY-2 PIC X(8).
05 FILLER PIC X VALUE ')'.
Points to note −
Sparse sequencing is also known as Sparse Indexing. We can remove some of the index source segments from the index using sparse sequencing with secondary index database.
Sparse sequencing is also known as Sparse Indexing. We can remove some of the index source segments from the index using sparse sequencing with secondary index database.
Sparse sequencing is used to improve the performance. When some occurrences of the index source segment are not used, we can remove that.
Sparse sequencing is used to improve the performance. When some occurrences of the index source segment are not used, we can remove that.
DL/I uses a suppression value or a suppression routine or both to determine whether a segment should be indexed.
DL/I uses a suppression value or a suppression routine or both to determine whether a segment should be indexed.
If the value of a sequence field in the index source segment matches a suppression value, then no index relationship is established.
If the value of a sequence field in the index source segment matches a suppression value, then no index relationship is established.
The suppression routine is a user-written program that evaluates the segment and determines whether or not it should be indexed.
The suppression routine is a user-written program that evaluates the segment and determines whether or not it should be indexed.
When sparse indexing is used, its functions are handled by the DL/I. We do not need to make special provisions for it in the application program.
When sparse indexing is used, its functions are handled by the DL/I. We do not need to make special provisions for it in the application program.
As discussed in earlier modules, DBDGEN is used to create a DBD. When we create secondary indexes, two databases are involved. A DBA needs to create two DBDs using two DBDGENs for creating a relationship between an indexed database and a secondary indexed database.
After creating the secondary index for a database, the DBA needs to create the PSBs. PSBGEN for the program specifies the proper processing sequence for the database on the PROCSEQ parameter of the PSB macro. For the PROCSEQ parameter, the DBA codes the DBD name for the secondary index database.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2110,
"s": 1946,
"text": "Secondary Indexing is used when we want to access a database without using the complete concatenated key or when we do not want to use the sequence primary fields."
},
{
"code": null,
"e": 2280,
"s": 2110,
"text": "DL/I stores the po... |
GATE | GATE CS 2012 | Question 33 - GeeksforGeeks | 28 Jun, 2021
Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are(A) Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT(B) Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR(C) Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT(D) Full: (FRONT+1) mod n == REAR, empty: REAR == FRONTAnswer: (A)Explanation:Implementation of Circular Queue :
Head – It always points to the location from where next deletion takes place from the queue.Tail – It always points to the next empty location in which next insertion will take place in the queue.
We will be using wrap around feature since it is a circular queue which is when the tail or head is at the index n-1, next operation will bring them to index 0. In Spite of having capacity of n inside array, we will reserve one empty spot in order to detect the overflow(Queue Full) and underflow(Queue Empty) conditions. The elements in the queue reside in locations Q.head, Q.head + 1, . . . , Q.tail + 1, where we “wrap around” in the sense that location 0 immediately follows location n-1 in a circular order.
Algorithm :
ENQUEUE(Q, x)
{
if Q.head == Q.tail + 1
error "Queue overflow"
Q[Q.tail] = x
if Q.tail == Q.length - 1
Q.tail = 0
else
Q.tail = Q.tail + 1
}
DEQUEUE(Q)
{
if Q.head == Q.tail
error "Queue underflow"
x = Q[Q.head]
if Q.head == Q.length - 1
Q.head = 0
else
Q.head = Q.head + 1
return x
}
See http://en.wikipedia.org/wiki/Circular_buffer#Always_Keep_One_Slot_Open
This solution is contributed by Pranjul AhujaQuiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3 | [
{
"code": null,
"e": 24123,
"s": 24095,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24719,
"s": 24123,
"text": "Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out ... |
Whitespace in C++ | Whitespace is a term that refers to characters that are used for formatting purposes. In C++, this refers primarily to spaces, tabs, and (sometimes) newlines. The C++ compiler generally ignores whitespace, with a few minor exceptions. For example, all the 4 lines below mean the same thing −
cout<<"Hello";
cout << "Hello";
cout << "Hello" ;
cout
<<
"Hello";
The exceptions where C++ compiler takes whitespace in consideration is inside quotes and for operator detection. So whenever you put in a string, c++ takes note of the whitespace. For example,
"Hello world!"
"Hello world!"
Both of these are different strings. Also when you use compound operators or any multi-character operator, you cannot put in space between. For example,
<< and < < are different. Similarly, += and + = are different, with the latter not being a valid expression. | [
{
"code": null,
"e": 1354,
"s": 1062,
"text": "Whitespace is a term that refers to characters that are used for formatting purposes. In C++, this refers primarily to spaces, tabs, and (sometimes) newlines. The C++ compiler generally ignores whitespace, with a few minor exceptions. For example, all t... |
Check the number is Armstrong or not using C | How to check whether the given number is an Armstrong number or not using C Programming language?
Armstrong number is the number that is equal to the sum of cubes of its digits.
pqrs.........=pow(p,n)+pow(q,n)+pow(r,n)+..........
For example, 153,371,1634, etc., are Armstrong numbers.
153=1*1*1 + 5*5*5 + 3*3*3
=1+125+27
=153 (Armstrong number)
Live Demo
#include<stdio.h>
int main(){
int number,remainder,total=0,temp;
printf("enter the number=");
scanf("%d",&number);
temp=number;
while(number>0){
remainder=number%10;
total=total+(remainder*remainder*remainder);
number=number/10;
}
if(temp==total)
printf("This number is Armstrong number");
else
printf("This number is not Armstrong number");
return 0;
}
enter the number=371
This number is Armstrong number
Check: 371=3*3*3 +7*7*7 + 1*1*1
=27 + 343 +1
=371
enter the number=53
This number is not Armstrong number
53 = 5*5*5 + 3*3*3
=125 +27
= 152 != 53 | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "How to check whether the given number is an Armstrong number or not using C Programming language?"
},
{
"code": null,
"e": 1240,
"s": 1160,
"text": "Armstrong number is the number that is equal to the sum of cubes of its digits."
}... |
C++ Program for Sieve of Eratosthenes - GeeksforGeeks | 27 Feb, 2018
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.
// C++ program to print all primes smaller than or equal to// n using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std; void SieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n+1]; memset(prime, true, sizeof(prime)); for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Print all prime numbers for (int p=2; p<=n; p++) if (prime[p]) cout << p << " ";} // Driver Program to test above functionint main(){ int n = 30; cout << "Following are the prime numbers smaller " << " than or equal to " << n << endl; SieveOfEratosthenes(n); return 0;}
Output:
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29
Please refer complete article on Sieve of Eratosthenes for more details!
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Why it is important to write "using namespace std" in C++ program?
Different ways to print elements of vector
Setting up Sublime Text for C++ Competitive Programming Environment
Program to count Number of connected components in an undirected graph | [
{
"code": null,
"e": 24552,
"s": 24524,
"text": "\n27 Feb, 2018"
},
{
"code": null,
"e": 24780,
"s": 24552,
"text": "Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.For example, if n is 10, the output should be “2, 3, 5, 7”... |
Python - Cast datatype of only a single column in a Pandas DataFrame | To cast only a single column, use the astype() method. Let us first create a DataFrame with 2 columns. One of them is a “float64” type and another “int64” −
dataFrame = pd.DataFrame(
{
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
}
)
Check the types −
dataFrame.dtypes
Let’s say we need to cast only a single column “Units” from int64 to int32. For that, use astype() −
dataFrame.astype({'Units': 'int32'}).dtypes
Following is the code −
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
}
)
print"DataFrame ...\n",dataFrame
print"\nDataFrame Types ...\n",dataFrame.dtypes
print"\nCast only a single column to int32..."
print"\nUpdated DataFrame Types ...\n",dataFrame.astype({'Units': 'int32'}).dtypes
This will produce the following output −
DataFrame ...
Reg_Price Units
0 7000.50570 90
1 1500.00000 120
2 5000.00000 100
3 8000.00000 150
4 9000.75768 200
5 6000.00000 130
DataFrame Types ...
Reg_Price float64
Units int64
dtype: object
Cast only a single column to int32...
Updated DataFrame Types ...
Reg_Price float64
Units int32
dtype: object | [
{
"code": null,
"e": 1219,
"s": 1062,
"text": "To cast only a single column, use the astype() method. Let us first create a DataFrame with 2 columns. One of them is a “float64” type and another “int64” −"
},
{
"code": null,
"e": 1370,
"s": 1219,
"text": "dataFrame = pd.DataFrame(... |
What is the difference between setTimeout() and setInterval() in JavaScript? | setTimeout( function, duration) − This function calls function after duration milliseconds from now. This goes for one execution. Let’s see an example −
It waits for 2000 milliseconds, and then runs the callback function alert(‘Hello’) −
setTimeout(function() { alert('Hello');}, 2000);
setInterval(function, duration) − This function calls function after every duration milliseconds. This goes for unlimited times. Let’s see an example −
It triggers the alert(‘Hello’) after every 2000 milliseconds, not only once.
setInterval(function() { alert('Hello');}, 2000); | [
{
"code": null,
"e": 1215,
"s": 1062,
"text": "setTimeout( function, duration) − This function calls function after duration milliseconds from now. This goes for one execution. Let’s see an example −"
},
{
"code": null,
"e": 1300,
"s": 1215,
"text": "It waits for 2000 millisecond... |
Apply Propensity Score Methods in Causal Inference — Part 1: Stratification | by Shuangyuan (Sharon) Wei | Towards Data Science | This article introduces and implements the framework of propensity score method from Dehejia and Wahba (1999) “Causal Effects in Non-Experimental Studies: Reevaluating the Evaluation of Training Programs,” Journal of the American Statistical Association, Vol. 94, No448 (December 1999), pp. 1053–1062. I will briefly go over the theories and then walk through how I implemented the stratification matching step by step. The full Python code is provided at the end of the article.
The intuition of propensity score method is: instead of conditioning on the full vector of covariates Xi, which can get difficult when there are many pre-treatment variables and when the treatment and comparison groups are very different, we try to condition on the propensity score estimated with Xi.
If you need a recap of covariates matching, my previous article introduces the exact matching on the covariates with the Conditional Independence Assumption (CIA):
towardsdatascience.com
Define propensity score p(Xi) as
We have the following: Suppose the CIA holds such that
Then this holds:
Propensity score matching works in the same way as covariate matching except that we match on the score instead of the covariates directly. By the propensity score theorem:
In practice, the estimation is usually done in two steps. First, we estimate the propensity score. Second, we estimate the effects of treatment by using one of the matching methods.
The data used by Dehejia and Wahba (1999) are from the National Supported Work (NSW) project designed as a transitional, subsidized work experience program for people with long- standing “employment problems”. Eligible applicants were randomly assigned either to receive training (the treatment group) or to receive no training (the control group). The goal of the evaluation is to estimate the effect of trainings on earnings.
The analysis illustrated in the steps below is organized as follows: First, since the project was conducted as an RCT, the original data (NSW) are experimental data, which are used to estimate the treatment effect as a benchmark. Next, we use additional government survey data (CPS and PSID) to mimic the observational data. Then, we estimate and apply propensity score and stratification method to estimate the effect of the offer of training on earnings using the observation data .
If the randomization is done properly, we expect there should be no systematic differences in pretreatment characteristics between the control and treatment groups. Otherwise we may suspect that they differ also in their unobserved characteristics which may lead to biased estimator of the causal effect of the treatment.
It is therefore always a good idea to check that pretreatment variables are indeed balanced across the two groups. To test the covariate balance of the pre-treatment variables (re78 is the realized outcome variable and all the other variables are predetermined before the assignment to the treatment or control groups), I ran 8 separate simple linear regressions and report the results in the Table 1. It shows that the sample averages are not different across control and treatment groups.
Also, I estimate the average treatment effect (ATE) using the experimental data as the causal effect of being offered on-the-job training on the earnings (re87) post the training . Controlling the covariates, I obtained an effect of $1,676. I will keep this in mind as the benchmark.
Dehejia and Wahba (1999) used two survey data samples (CPS and PSID surveys) as comparison groups with the NSW treatment group to construct the observation database (CPS stands for Current Population Survey and PSID stands for Panel Study of Income Dynamics).
Similarly, I compared the sample means across the NSW (experimental data) and the added comparison samples (CPS and PSID). In the Table 3, it is obvious that The NSW-Treated differ quite a lot from CPS/PSID in the demographic characteristics as well as the pre-treatment earnings (re74 and re75). The NSW treatment groups are younger, less educated, more likely to be nonwhite, and have much lower earnings before the program. It makes no sense to directly compare the NSW-Treated with the comparison groups.
From this step onwards, I use PSID as the comparison group to construct the observation database with the NSW-Treated.
I used logistic regression model to estimate the propensity score. In particular, I explored two specifications regressing on two different sets of covariates (in the second set, I added the squared age and education years):
X1 = [‘age’, ‘ed’, ‘black’, ‘hisp’, ‘married’, ‘nodeg’, ‘re74’,’re75']X2 = [‘age’, ‘ed’, ‘black’, ‘hisp’, ‘married’, ‘nodeg’, ‘re74’,’re75',’age2',’ed2']
Next, I used cross validation to tune the parameter C which is the strength of the regularization. Higher values of C means less regularization.
best = 0.0for strength in [0.00001,0.0001,0.001,0.01,0.1, 1, 10, 100, 1000, 10000, 100000, 1000000] : model = LogisticRegression(C=strength, max_iter=10000) curScore = cross_val_score(model,df_combine[X1], df_combine[T],scoring=’f1').mean() if curScore > best : best = curScore print(strength) print (curScore)
Next, I ran the logistic regression model with the best C value and added the estimated propensity score back to the observation set. Below I plotted the estimated p-score across comparison and treatment groups below. Not shockingly, there is not much overlap between the two groups. The mean p-score of treatment group (n=185) is 0.62 while the mean p-score of comparison group is 0.03 (n=2490). In fact, as Dehejia and Wahba (1999) pointed out, one of the strengths of the propensity score method is that it dramatically highlights the fact that most of the comparison units are very different from the treated units.
The drastic differences between the treatment and comparison groups naturally lead to the steps of trimming and matching, which in my Python code are done in the same function stratification_function. The purpose of trimming is to find the common support so that no p-score from either treatment or control group falls outside it. After the trimming, we discarded roughly 1,300 observations from the PSID comparison group that are outside the range of common support, most of which have estimated propensity scores less than the minimum estimated propensity scores for the treated units. The reason for trimming is to prevent situation in which we end up with treated units without matching control units, and vice versa, when we enter the stratification/matching stage.
The basic idea of stratification is to define strata based on estimated propensity score and then group treated and comparison units into each strata. Within each stratum, we take a difference in means of the outcomes between the treatment and comparison groups, then we calculated the weighted mean across strata by the number of treated units within each stratum. The final weighted mean difference across treatment and control groups (ATT) is calculated as:
In my code, it is done in the function stratification_function. I also tested two ways of defining strata:
blocks1 = np.array_split(df_ps.query(“treat==1”)[“pscore”].sort_values(), nostrata)blocks2 = np.linspace(0,1,11)
Suppose we want 10 strata. The first way divides the estimated propensity score of treated units into 10 number of equal sized blocks and then match comparison units with estimated propensity score within the range of each block. The second way simply divides 1 into 10 equally spaced intervals.
Remember in the Step 3 Propensity Score Estimation, I tested two logistic regression models. Combining the two logistic regression models with the two definitions of strata, I have four models at the output which I name as: M11 (reg1, strata1), M12(reg1, strata2), M21(reg2, strata1), and M22(reg2, strata2). The results are presented in the Table 4 :
Out of these four options, the final model should be chosen based on the how well the covariates within each stratum are balanced across treated and comparison units. Therefore, I think Model21 is the best. Model21 estimates the effect = $1,632 (with std. error=1,514), which is pretty close to our experimental benchmark effect = $1,676.
Lastly, as promised, below is my full Python code for Step 1 to 5 which also output the summary tables 1–4 :
I downloaded all the data from NYU’s website | [
{
"code": null,
"e": 527,
"s": 47,
"text": "This article introduces and implements the framework of propensity score method from Dehejia and Wahba (1999) “Causal Effects in Non-Experimental Studies: Reevaluating the Evaluation of Training Programs,” Journal of the American Statistical Association, V... |
Unrestricted Grammar | Theory of Computation
In automaton, Unrestricted Grammar or Phrase Structure Grammar is the most general in the Chomsky Hierarchy of classification. This is type0 grammar, generally used to generate Recursively Enumerable languages. It is called unrestricted because no other restriction is made on this except each of their left hand sides being non-empty. The left hand sides of the rules can contain terminal and non-terminal, but the condition is at least one of them must be non-terminal.
A Turning Machine can simulate Unrestricted Grammar and Unrestricted Grammar can simulate Turning Machine configurations. It can always be found for the language recognized or generated by any Turning Machine.
The unrestricted grammar is 4 tuple -
G = (N,Σ,P,S)
N - A finite set of non-terminal symbols or variables,
Σ - It is a set of terminal symbols or the alphabet of the language being described, where N ∩ Σ = φ,
P - It is a finite set of "productions" or "rules",
S - It is a start variable or non-terminal symbol.
If, α and β are two strings over the alphabet N ∪ Σ.
Then, the rules or productions are of the form α → β. The start variable S appears on the left side of the rule.
L={anbncn | n≥0}
S→aBSc {Equal Number of a's, B's, c's}
S→ ε {Eliminate S}
Ba→aB {Move a's to Right of B's}
Bc→bc {Reduce B before first c to b}
Bb→bb {Reduce all remaining B's to b} | [
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 584,
"s": 112,
"text": "In automaton, Unrestricted Grammar or Phrase Structure Grammar is the most general in the Chomsky Hierarchy of classification. This is type0 grammar, generally used ... |
Cisco Switch Configuration basic commands - GeeksforGeeks | 03 Jul, 2020
Prerequisite – Switch Functions
A switch is a layer 2 device used to forward packet from one device to another within the network. It forwards the packet through one of its ports on the basis of destination MAC address and the entry in the MAC table.
Following basic commands are used to configure a new switch :
1. Changing the hostname of a switch to GfgSwitch :
It is used to set the name of the device.
switch(config)#hostname GfgSwitch
GfgSwitch(config)#
2. To add a banner message :
It provides a short message to the user who wants to access the switch.
GfgSwitch(config)#banner motd &
Enter Text message. End with character '&'
$ This is GeeksforGeeks floor Switch &
3. To set IP address in Switch :
IP address is the address of device in network.
GfgSwitch(config)#interface vlan1
GfgSwitch(config-if)#ip address 172.16.10.1 255.255.255.0
GfgSwitch(config-if)#exit
GfgSwitch(config)#ip default-gateway 172.16.10.0
4. To set the current clock time :
This is set the current time stored in the switch.
GfgSwitch#clock set 3:03:14 June 25 2020
5. Apply password protection (enable password, secret password, console password and vty password) :
Enable password :The enable password is used for securing privilege mode.GfgSwitch(config)#enable password GFGGFG
The enable password is used for securing privilege mode.
GfgSwitch(config)#enable password GFGGFG
Enable secret password :This is also used for securing privilege mode but the difference is that it will be displayed as ciphertext(***) on the configuration file.GfgSwitch(config)#enable secret GFGGFG
This is also used for securing privilege mode but the difference is that it will be displayed as ciphertext(***) on the configuration file.
GfgSwitch(config)#enable secret GFGGFG
Line console password :When a person will take access through console port then this password will be asked.GfgSwitch(config)#line console 0
GfgSwitch(config-line)#password GFG
GfgSwitch(config-line)#login
When a person will take access through console port then this password will be asked.
GfgSwitch(config)#line console 0
GfgSwitch(config-line)#password GFG
GfgSwitch(config-line)#login
Line VTY password :When a person want to access a router through VTY lines (telnet or ssh) then this password will be asked.GfgSwitch(config)#line VTY 0 2
GfgSwitch(config-line)#password GFGGFG
GfgSwitch(config-line)#exit
When a person want to access a router through VTY lines (telnet or ssh) then this password will be asked.
GfgSwitch(config)#line VTY 0 2
GfgSwitch(config-line)#password GFGGFG
GfgSwitch(config-line)#exit
6. Copy to startup-configuration file from running-configuration file :
GfgSwitch#copy running-config startup-config
7. To watch startup-configuration file and running-configuration file :
GfgSwitch#show startup-config
GfgSwitch#show running-config
8. Clear mac address table :
Switch stores MAC addresses in MAC address table
GfgSwitch#clear mac address-table
master_abhig
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Multiple Access Protocols in Computer Network
Intrusion Detection System (IDS)
GSM in Wireless Communication
Cryptography and its Types
Introduction and IPv4 Datagram Header
Routing Information Protocol (RIP)
Secure Socket Layer (SSL)
Stop and Wait ARQ
TCP Congestion Control | [
{
"code": null,
"e": 24536,
"s": 24508,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 24568,
"s": 24536,
"text": "Prerequisite – Switch Functions"
},
{
"code": null,
"e": 24787,
"s": 24568,
"text": "A switch is a layer 2 device used to forward packet from o... |
Symfony - Routing | Routing maps request URI to a specific controller's method. In general, any URI has the following three parts −
Hostname segment
Path segment
Query segment
For example, in URI / URL, http://www.tutorialspoint.com/index?q=data, www.tutorialspoint.com is the host name segment, index is the path segment and q=data is the query segment. Generally, routing checks the page segment against a set of constraints. If any constraint matches, then it returns a set of values. One of the main value is the controller.
Annotation plays an important role in the configuration of Symfony application. Annotation simplifies the configuration by declaring the configuration in the coding itself. Annotation is nothing but providing meta information about class, methods, and properties. Routing uses annotation extensively. Even though routing can be done without annotation, annotation simplifies routing to a large extent.
Following is a sample annotation.
/**
* @Route(“/student/home”)
*/
public function homeAction() {
// ...
}
Consider the StudentController class created in “student” project.
// src/AppBundle/Controller/StudentController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/home”)
*/
public function homeAction() {
// ...
}
/**
* @Route(“/student/about”)
*/
public function aboutAction() {
}
}
Here, the routing performs two steps. If you go to /student/home, the first route is matched then homeAction() is executed. Otherwise, If you go to /student/about, the second route is matched and then aboutAction() is executed.
Consider, you have a paginated list of student records with URLs like /student/2 and /student/3 for page 2 and 3 correspondingly. Then, if you want to change the route's path, you can use wildcard formats.
// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/{page}", name = “student_about”, requirements = {"page": "\d+"})
*/
public function aboutAction($page) {
// ...
}
}
Here, the \d+ is a regular expression that matches a digit of any length.
You can assign a placeholder value in routing. It is defined as follows.
// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/{page}", name = “student_about”, requirements = {"page": "\d+"})
*/
public function aboutAction($page = 1) {
// ...
}
}
Here, if you go to /student, the student_about route will match and $page will default to a value of 1.
If you want to redirect the user to another page, use the redirectToRoute() and redirect() methods.
public function homeAction() {
// redirect to the "homepage" route
return $this->redirectToRoute('homepage');
// redirect externally
\return $this->redirect('http://example.com/doc');
}
To generate a URL, consider a route name, student_name and wildcard name, student-names used in the path for that route. The complete listing for generating a URL is defined as follows.
class StudentController extends Controller {
public function aboutAction($name) {
// ...
// /student/student-names
$url = $this->generateUrl(
‘student_name’,
array(‘name’ =>
’student-names’)
);
}
}
Consider a simple example for routing in StudentController class as follows.
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class StudentController {
/**
* @Route("/student/home")
*/
public function homeAction() {
$name = 'Student details application';
return new Response(
'<html><body>Project: '.$name.'</body></html>'
);
}
}
Now, request the url,”http://localhost:8000/student/home” and it produces the following result.
Similarly, you can create another route for aboutAction() as well.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2315,
"s": 2203,
"text": "Routing maps request URI to a specific controller's method. In general, any URI has the following three parts −"
},
{
"code": null,
"e": 2332,
"s": 2315,
"text": "Hostname segment"
},
{
"code": null,
"e": 2345,
"s": 2... |
CSS3 - 2d Transforms | 2D transforms are used to re-change the element structure as translate, rotate, scale, and skew.
The following table has contained common values which are used in 2D transforms −
matrix(n,n,n,n,n,n)
Used to defines matrix transforms with six values
translate(x,y)
Used to transforms the element along with x-axis and y-axis
translateX(n)
Used to transforms the element along with x-axis
translateY(n)
Used to transforms the element along with y-axis
scale(x,y)
Used to change the width and height of element
scaleX(n)
Used to change the width of element
scaleY(n)
Used to change the height of element
rotate(angle)
Used to rotate the element based on an angle
skewX(angle)
Used to defines skew transforms along with x axis
skewY(angle)
Used to defines skew transforms along with y axis
The following examples are shown the sample of all above properties.
Box rotation with 20 degrees angle as shown below −
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: pink;
border: 1px solid black;
}
div#myDiv {
/* IE 9 */
-ms-transform: rotate(20deg);
/* Safari */
-webkit-transform: rotate(20deg);
/* Standard syntax */
transform: rotate(20deg);
}
</style>
</head>
<body>
<div>
Tutorials point.com.
</div>
<div id = "myDiv">
Tutorials point.com
</div>
</body>
</html>
It will produce the following result −
Box rotation with -20 degrees angle as shown below −
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: pink;
border: 1px solid black;
}
div#myDiv {
/* IE 9 */
-ms-transform: rotate(-20deg);
/* Safari */
-webkit-transform: rotate(-20deg);
/* Standard syntax */
transform: rotate(-20deg);
}
</style>
</head>
<body>
<div>
Tutorials point.com.
</div>
<div id = "myDiv">
Tutorials point.com
</div>
</body>
</html>
It will produce the following result −
Box rotation with skew x-axis as shown below −
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: pink;
border: 1px solid black;
}
div#skewDiv {
/* IE 9 */
-ms-transform: skewX(20deg);
/* Safari */
-webkit-transform: skewX(20deg);
/* Standard syntax */
transform: skewX(20deg);
}
</style>
</head>
<body>
<div>
Tutorials point.com.
</div>
<div id = "skewDiv">
Tutorials point.com
</div>
</body>
</html>
It will produce the following result −
Box rotation with skew y-axis as shown below −
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: pink;
border: 1px solid black;
}
div#skewDiv {
/* IE 9 */
-ms-transform: skewY(20deg);
/* Safari */
-webkit-transform: skewY(20deg);
/* Standard syntax */
transform: skewY(20deg);
}
</style>
</head>
<body>
<div>
Tutorials point.com.
</div>
<div id = "skewDiv">
Tutorials point.com
</div>
</body>
</html>
It will produce the following result −
Box rotation with Matrix transforms as shown below −
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: pink;
border: 1px solid black;
}
div#myDiv1 {
/* IE 9 */
-ms-transform: matrix(1, -0.3, 0, 1, 0, 0);
/* Safari */
-webkit-transform: matrix(1, -0.3, 0, 1, 0, 0);
/* Standard syntax */
transform: matrix(1, -0.3, 0, 1, 0, 0);
}
</style>
</head>
<body>
<div>
Tutorials point.com.
</div>
<div id = "myDiv1">
Tutorials point.com
</div>
</body>
</html>
It will produce the following result −
Matrix transforms with another direction.
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: pink;
border: 1px solid black;
}
div#myDiv2 {
/* IE 9 */
-ms-transform: matrix(1, 0, 0.5, 1, 150, 0);
/* Safari */
-webkit-transform: matrix(1, 0, 0.5, 1, 150, 0);
/* Standard syntax */
transform: matrix(1, 0, 0.5, 1, 150, 0);
}
</style>
</head>
<body>
<div>
Tutorials point.com.
</div>
<div id = "myDiv2">
Tutorials point.com
</div>
</body>
</html>
It will produce the following result −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2723,
"s": 2626,
"text": "2D transforms are used to re-change the element structure as translate, rotate, scale, and skew."
},
{
"code": null,
"e": 2805,
"s": 2723,
"text": "The following table has contained common values which are used in 2D transforms −"
... |
C - Floating Point Data Types - 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 this tutorial, we are going to learn about C floating point data types such as float, double.
In C, float data type occupies 4 bytes (32 bits) of memory to store real numbers that have at least one digit after the decimal point. A float data type can hold any value between 3.4E-38 to 3.4E+38.
The floating-point variable has a precision of 6 digits i.e., it uses 6 digits after the decimal point. Consider the following example that uses a float data type:
#include <stdio.h>
void main() {
float a = 2.135;
float b = 7.217;
float sum;
sum = a + b;
printf("Sum of two numbers = %f\n", sum);
}
Here, 4 bytes of memory is allocated to each variable a, b and they are initialized with floating-point constants 2.135000 and 7.217000 respectively.
A floating-point variable can represent a wider range of numbers than a fixed-point variable of the same bit width at the cost of precision. A signed 32-bit integer variable has a maximum value of 231 − 1 = 2,147,483,647, whereas an IEEE 754 32-bit base-2 floating-point variable has a maximum value of (2 − 2−23) × 2127 ≈ 3.4028235 × 1038.
All integers with 7 or fewer decimal digits, and any 2n for a whole number −149 ≤ n ≤ 127, can be converted exactly into an IEEE 754 single-precision floating-point value.
There’s no hardware support for unsigned floating-point operations. So, C doesn’t offer it.
In C, a double data type is used to increase the accuracy of the real number wherever a float is not sufficient.
A double data type occupies 8 bytes (64 bits) of memory to store real numbers, which have at least one digit after the decimal point. A double data type can hold any value between 1.7E-308 to 1.7E+308.
double data type values have a precision of 14 digits i.e., they can have 14 digits after the decimal point. Consider the following example using a double data type.
#include <stdio.h>
void main() {
double num1 = 26.7368;
double num2 = 1.42924;
double sum;
sum = num1 + num2;
printf("Sum of the numbers = %f\n", sum);
}
Here, 8 bytes of memory is allocated to each variable num1, num2 and they are initialized with real number constants 26.7368 and 1.42924 respectively.
To further extend the precision of a double data type, the user can use a long double data type. The long double type is guaranteed to have more bits than a double, while the exact number may vary from one hardware platform to another.
A long double data type allocates 10 bytes (80 bits) of memory to store the given values. A long double data type can hold any value between 3.4E-4932 to 1.1E+4932.
In a 32 – bit forth implementation,doubke data type has a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (signed) or 0 to 18,446,744,073,709,551,615 (unsigned)
Wiki – float data type
C Data types
Happy Learning 🙂
C – Integer Data Types – int, short int, long int and char
What are different Python Data Types
What are the Data types in C?
PHP Data types Example Tutorials
Python TypeCasting for Different Types
Underscores in Numeric Literals Java 7
C Program – Print the sum of digits of given number
C – Arithmetic Operators
Java program to find sum of digits
Variables & Keywords in C Language
C Number System – Decimal, Binary, Octal and Hex
C Program – Sum of digits of given number till single digit
Organization of data In Data Structures
Binary To Decimal Conversion Java Program
Python How to read input from keyboard
C – Integer Data Types – int, short int, long int and char
What are different Python Data Types
What are the Data types in C?
PHP Data types Example Tutorials
Python TypeCasting for Different Types
Underscores in Numeric Literals Java 7
C Program – Print the sum of digits of given number
C – Arithmetic Operators
Java program to find sum of digits
Variables & Keywords in C Language
C Number System – Decimal, Binary, Octal and Hex
C Program – Sum of digits of given number till single digit
Organization of data In Data Structures
Binary To Decimal Conversion Java Program
Python How to read input from keyboard
Δ
C – Introduction
C – Features
C – Variables & Keywords
C – Program Structure
C – Comment Lines & Tokens
C – Number System
C – Local and Global Variables
C – Scope & Lifetime of Variables
C – Data Types
C – Integer Data Types
C – Floating Data Types
C – Derived, Defined Data Types
C – Type Conversions
C – Arithmetic Operators
C – Bitwise Operators
C – Logical Operators
C – Comma and sizeof Operators
C – Operator Precedence and Associativity
C – Relational Operators
C Flow Control – if, if-else, nested if-else, if-else-if
C – Switch Case
C Iterative – for, while, dowhile loops
C Unconditional – break, continue, goto statements
C – Expressions and Statements
C – Header Files & Preprocessor Directives
C – One Dimensional Arrays
C – Multi Dimensional Arrays
C – Pointers Basics
C – Pointers with Arrays
C – Functions
C – How to Pass Arrays to Functions
C – Categories of Functions
C – User defined Functions
C – Formal and Actual Arguments
C – Recursion functions
C – Structures Part -1
C – Structures Part -2
C – Unions
C – File Handling
C – File Operations
C – Dynamic Memory Allocation
C Program – Fibonacci Series
C Program – Prime or Not
C Program – Factorial of Number
C Program – Even or Odd
C Program – Sum of digits till Single Digit
C Program – Sum of digits
C Program – Reverse of a number
C Program – Armstrong Numbers
C Program – Print prime Numbers
C Program – GCD of two Numbers
C Program – Number Palindrome or Not
C Program – Find Largest and Smallest number in an Array
C Program – Add elements of an Array
C Program – Addition of Matrices
C Program – Multiplication of Matrices
C Program – Reverse of an Array
C Program – Bubble Sort
C Program – Add and Sub without using + – | [
{
"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,
... |
C# | Nesting of try and catch blocks | 01 Aug, 2019
In C#, the nesting of the try & catch block is allowed. The nesting of try block means one try block can be nested into another try block. The various programmer uses the outer try block to handling serious exceptions, whereas the inner block for handling normal exceptions.
Note:
If an exception raises in the inner try block that is not caught by the catch block associated with the try block, then the exception is promoted to the outer try block. Generally, nested try blocks are used to permit different groups of the error to be handled in different ways.
It is a necessary condition that a try block must be followed by a catch or finally blocks because if you use a try block without a catch or finally then you will tend to a compile-time error.
Syntax:
// outer try block
try
{
// inner try block
try
{
// code...
}
// inner catch block
catch
{
// code...
}
}
// outer catch block
catch
{
// code...
}
Below given are some examples to understand the implementation in a better way:
Example 1: In this program, DivideByZeroException is generated within the inner try block that is caught by a catch block associated with the inner try block and continue the flow of the program. When IndexOutOfRangeException generates within the inner try block which is not caught by the inner catch block then inner try block transfer this exception to the outer try block. After that, the catch block associated with the outer try block caught the exception which causes the program to terminate. Here for 17/0 and 24/0 inner try-catch block is executing but for number 25 outer try-catch block is executing.
// C# program to illustrate how outer// try block will handle the exception// which is not handled by the inner // try catch blockusing System; class GFG { // Main Method static void Main() { // Here, number is greater // than divisor. int[] number = {8, 17, 24, 5, 25}; int[] divisor = {2, 0, 0, 5}; // Outer try block // Here IndexOutOfRangeException occurs // due to which program may terminates try { for (int j = 0; j < number.Length; j++) { // Inner try block // Here DivideByZeroException caught // and allow the program to continue // its execution try { Console.WriteLine("Number: " + number[j] + "\nDivisor: " + divisor[j] + "\nQuotient: " + number[j] / divisor[j]); } // Catch block for inner try block catch (DivideByZeroException) { Console.WriteLine("Inner Try Catch Block"); } } } // Catch block for outer try block catch (IndexOutOfRangeException) { Console.WriteLine("Outer Try Catch Block"); } }}
Number: 8
Divisor: 2
Quotient: 4
Inner Try Catch Block
Inner Try Catch Block
Number: 5
Divisor: 5
Quotient: 1
Outer Try Catch Block
Example 2: In the below example, an exception is generated within the inner try block that is caught by the catch block associated with the inner try block.
// C# program to illustrate// nested try blockusing System; public class Geeks { public string Author_name { get; set; }} // Driver Classpublic class GFG { // Main Method public static void Main() { Geeks str1 = null; // outer try block try { // inner try block try { str1.Author_name = ""; } // catch block for the inner try block catch { Console.WriteLine("Inner try catch block"); } } // catch block for the outer try block catch { Console.WriteLine("Outer try catch block"); } }}
Inner try catch block
mayank5326
CSharp-Exception-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Extension Method in C#
C# | Encapsulation | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2019"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "In C#, the nesting of the try & catch block is allowed. The nesting of try block means one try block can be nested into another try block. The various programmer uses the oute... |
Creating Responsive Grid Vanilla using HTML,CSS and Bootstrap | 13 Aug, 2020
Many modern websites use a grid system to display chunks of data on their home-page as well as other pages. To much extent grid resembles a table, however, it is much more visually appealing and most often displays sibling elements. A grid must be responsive, i.e. it should adjust to the screen size of the user.
Bootstrap is a very popular open-source HTML, CSS, and JavaScript library that helps to design the frontend of a website. Generally, bootstrap code is very compact and robust but there are a few reasons for which every developer should master Vanilla(Customizable) HTML and CSS :
Ample of utilities and components are never used and are therefore a burden on the web page.
Bootstrap code is difficult to customize.
Bootstrap slows downloading of websites a bit because it first loads jQuery, then bootstraps CSS and then bootstrap JS.
The Two Possible Approaches for Creating a Grid:
1. Grid without Bootstrap(Vanilla HTML CSS)
HTML Code: We start with defining three div each with class “customRow“. Then create an img tag within each of the customRow div.
HTML
<!DOCTYPE html><html> <head> <title>geeksforgeeks vanilla grid</title> <!-- Custom CSS Link --> <link rel="stylesheet" type="text/css" href="gfgVanillaGrid.css"></head> <body> <!-- gfg(G),gfg(E) ... gfg(R) are images for corresponding letters --> <div class="customRow"> <!-- First Row G E E K S--> <img src="gfg(G).png" alt=""> <img src="gfg(E).png" alt=""> <img src="gfg(E).png" alt=""> <img src="gfg(K).png" alt=""> <img src="gfg(S).png" alt=""> </div> <div class="customRow"> <!-- Second Row F O R--> <img src="gfg(F).png" alt=""> <img src="gfg(O).png" alt=""> <img src="gfg(R).png" alt=""> </div> <div class="customRow"> <!-- Third Row G E E K S--> <img src="gfg(G).png" alt=""> <img src="gfg(E).png" alt=""> <img src="gfg(E).png" alt=""> <img src="gfg(K).png" alt=""> <img src="gfg(S).png" alt=""> </div> </body> </html>
CSS Code: Most of the styling is predefined. However, we have to set the width of each image as a percentage of the “customRow ”, so that these are responsive i.e. their widths vary as the screen size changes. We set some nonzero margin to rows so that they don’t stick to one another. Lastly, we align all the images to the center of the screen by using the text-align attribute.
CSS
img{ width: 14%;} /* 40px margin on top and bottom, zero margin on left and right*/.customRow{ margin: 40px 0; text-align: center;}
Output:
2. Grid using Bootstrap
HTML Code: First, we need to copy the bootstrap starter template from its official website. This template contains a bootstrap CDN, jQuery CDN, popper.js CDN, and Bootstrap JavaScript file. For convenience, I have put it here.
Then we start with building our grid by creating a div with the class container. This div will wrap all of our rows, then for each row we :
Create a div with class rowInside this “row div”, create as many div as a number of columns required and give a class of col-* to each of these columns div. Here asterisk(*) resembles the width of the column. The total width of any screen is set as 12, this total width is too divided among the columns equally or unequally. In the first row, five columns each with a width of 2 is defined which makes up to a total of 10, the remaining 2(12-10) act for blank space.Then put image tags as requiredTo the center, the images in each row, add a bootstrap class justify-content-center to each “row div”.Put a link to the custom CSS file( gfgBootstrapGrid.css here) in the header.
Create a div with class row
Inside this “row div”, create as many div as a number of columns required and give a class of col-* to each of these columns div. Here asterisk(*) resembles the width of the column. The total width of any screen is set as 12, this total width is too divided among the columns equally or unequally. In the first row, five columns each with a width of 2 is defined which makes up to a total of 10, the remaining 2(12-10) act for blank space.
Then put image tags as required
To the center, the images in each row, add a bootstrap class justify-content-center to each “row div”.
Put a link to the custom CSS file( gfgBootstrapGrid.css here) in the header.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous" /> <!-- Custom CSS Link--> <link rel="stylesheet" href="gfgBootstrapGrid.css" /> <title>Geeksforgeeks grid with bootstrap</title> </head> <body> <!-- gfg(G),gfg(E) ... gfg(R) are images for corresponding letters --> <div class="container-fluid"> <!-- First Row G E E K S--> <div class="row justify-content-center"> <div class="col-2"> <img src="gfg(G).png" alt="" /> </div> <div class="col-2"> <img src="gfg(E).png" alt="" /> </div> <div class="col-2"> <img src="gfg(E).png" alt="" /> </div> <div class="col-2"> <img src="gfg(K).png" alt="" /> </div> <div class="col-2"> <img src="gfg(S).png" alt="" /> </div> </div> <!-- Second Row F O R--> <div class="row justify-content-center"> <div class="col-2"> <img src="gfg(F).png" alt="" /> </div> <div class="col-2"> <img src="gfg(O).png" alt="" /> </div> <div class="col-2"> <img src="gfg(R).png" alt="" /> </div> </div> <!-- Third Row G E E K S--> <div class="row justify-content-center"> <div class="col-2"> <img src="gfg(G).png" alt="" /> </div> <div class="col-2"> <img src="gfg(E).png" alt="" /> </div> <div class="col-2"> <img src="gfg(E).png" alt="" /> </div> <div class="col-2"> <img src="gfg(K).png" alt="" /> </div> <div class="col-2"> <img src="gfg(S).png" alt="" /> </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"> </script> </body></html>
CSS Code: First we need to give margin to each row, to avoid them from sticking. For this, we append the row class of bootstrap and give it a margin of “40px top and bottom” and “0 left and right”. We also resize each image tag to acquire 100% of its parent element(here the “column div”), this makes the images responsive
CSS
.row{ margin: 40px 0;}img{ width: 100%;}
Output:
Differences Between the two approaches:
As the code reflects, for small projects( like this one), custom CSS is the better option. This is because fewer classes and generalization are to be done and the code is written specifically for a particular use-case.However, in case of a large project with a lot of elements(for example a login page, a sign-up page, a home page ... etc) the general margin and padding are always the same. Therefore, using bootstrap will avoid any repetition of code and hence is preferred.As Bootstrap is a predefined library, the chances of buggy code are very less than compared to custom CSS.
As the code reflects, for small projects( like this one), custom CSS is the better option. This is because fewer classes and generalization are to be done and the code is written specifically for a particular use-case.
However, in case of a large project with a lot of elements(for example a login page, a sign-up page, a home page ... etc) the general margin and padding are always the same. Therefore, using bootstrap will avoid any repetition of code and hence is preferred.
As Bootstrap is a predefined library, the chances of buggy code are very less than compared to custom CSS.
Bootstrap-Misc
CSS-Basics
HTML-Basics
Bootstrap
CSS
HTML
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": "\n13 Aug, 2020"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "Many modern websites use a grid system to display chunks of data on their home-page as well as other pages. To much extent grid resembles a table, however, it is much more vis... |
Multiples of 3 and 5 without using % operator | 02 Dec, 2021
Write a short program that prints each number from 1 to n on a new line.
For each multiple of 3, print “Multiple of 3” instead of the number.For each multiple of 5, print “Multiple of 5” instead of the number.For numbers which are multiples of both 3 and 5, print “Multiple of 3. Multiple of 5.” instead of the number.
For each multiple of 3, print “Multiple of 3” instead of the number.
For each multiple of 5, print “Multiple of 5” instead of the number.
For numbers which are multiples of both 3 and 5, print “Multiple of 3. Multiple of 5.” instead of the number.
Examples:
Input : 15
Output : 1
2
Multiple of 3.
4
Multiple of 5.
Multiple of 3.
7
8
Multiple of 3.
Multiple of 5.
11
Multiple of 3.
13
14
Multiple of 3. Multiple of 5.
The idea is iterate from 1 to n and keep track of multiples of 3 and 5 by adding 3 and 5 to current multiple. If current number matches with a multiple, we update our output accordingly.
C++
Java
C#
PHP
Javascript
Python3
// C++ program to print multiples// of 3 and 5 without using % operator.#include <iostream>using namespace std; void findMultiples(int n){ int a = 3; // To keep track of multiples of 3 int b = 5; // To keep track of multiples of 5 for (int i = 1; i <= n; i++) { string s = ""; // Found multiple of 3 if (i == a) { a = a + 3; // Update next multiple of 3 s = s + "Multiple of 3. "; } // Found multiple of 5 if (i == b) { b = b + 5; // Update next multiple of 5 s = s + "Multiple of 5."; } if (s == "") cout << (i) << endl; else cout << (s) << endl; }} // Driver Codeint main(){ findMultiples(20); return 0;} // This code is contributed// by Sach_Code
// Java program to print multiples of 3 and// 5 without using % operator.import java.io.*; class GFG{ static void findMultiples(int n) { int a = 3; // To keep track of multiples of 3 int b = 5; // To keep track of multiples of 5 for (int i=1; i<=n; i++) { String s = ""; // Found multiple of 3 if (i==a) { a = a + 3; // Update next multiple of 3 s = s + "Multiple of 3. "; } // Found multiple of 5 if (i==b) { b = b+5; // Update next multiple of 5 s = s + "Multiple of 5."; } if (s == "") System.out.println(i); else System.out.println(s); } } public static void main (String[] args) { findMultiples(20); }}
// C# program to print multiples of 3 and// 5 without using % operator.using System; public class GFG { static void findMultiples(int n) { // To keep track of multiples of 3 int a = 3; // To keep track of multiples of 5 int b = 5; for (int i = 1; i <= n; i++) { String s = ""; // Found multiple of 3 if (i == a) { // Update next multiple of 3 a = a + 3; s = s + "Multiple of 3. "; } // Found multiple of 5 if (i == b) { // Update next multiple of 5 b = b + 5; s = s + "Multiple of 5."; } if (s == "") Console.WriteLine(i); else Console.WriteLine(s); } } // Driver code public static void Main () { findMultiples(20); }} // This code is contributed by Sam007.
<?php// PHP program to print multiples// of 3 and 5 without using % operator. function findMultiples($n){ $a = 3; // To keep track of multiples of 3 $b = 5; // To keep track of multiples of 5 for ($i = 1; $i <= $n; $i++) { $s = ""; // Found multiple of 3 if ($i == $a) { $a = $a + 3; // Update next multiple of 3 $s = $s . "Multiple of 3. "; } // Found multiple of 5 if ($i == $b) { $b = $b + 5; // Update next multiple of 5 $s = $s . "Multiple of 5."; } if ($s == "") echo ($i). "\n"; else echo ($s). "\n"; }} // Driver CodefindMultiples(20); // This code is contributed// by Akanksha Rai(Abby_akku)
<script> // JavaScript program for the above approach function findMultiples(n) { let a = 3; // To keep track of multiples of 3 let b = 5; // To keep track of multiples of 5 for (let i=1; i<=n; i++) { let s = ""; // Found multiple of 3 if (i==a) { a = a + 3; // Update next multiple of 3 s = s + "Multiple of 3. "; } // Found multiple of 5 if (i==b) { b = b+5; // Update next multiple of 5 s = s + "Multiple of 5."; } if (s == "") { document.write(i); document.write("<br />"); } else { document.write(s); document.write("<br />"); } } } // Driver Code findMultiples(20); // This code is contributed by susmitakundugoaldanga.</script>
# Python 3 program to print multiples# of 3 and 5 without using % operator. def findMultiples(n): a = 3 # To keep track of multiples of 3 b = 5 # To keep track of multiples of 5 for i in range(1,n+1): s = "" # Found multiple of 3 if (i == a): a = a + 3 # Update next multiple of 3 s = s + "Multiple of 3. " # Found multiple of 5 if (i == b): b = b + 5 # Update next multiple of 5 s = s + "Multiple of 5." if (s == ""): print(i) else: print(s) # Driver Codeif __name__ == '__main__': findMultiples(20)
Output:
1
2
Multiple of 3.
4
Multiple of 5.
Multiple of 3.
7
8
Multiple of 3.
Multiple of 5.
11
Multiple of 3.
13
14
Multiple of 3. Multiple of 5.
16
17
Multiple of 3.
19
Multiple of 5.
Time Complexity: O(N)Auxiliary Space: O(1) This article is contributed by Nimish Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
Sach_Code
Akanksha_Rai
susmitakundugoaldanga
pankajsharmagfg
amartyaghoshgfg
Algorithms
Java
Java
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 127,
"s": 52,
"text": "Write a short program that prints each number from 1 to n on a new line. "
},
{
"code": null,
"e": 373,
"s": 127,
"text": "For each multiple of 3, print ... |
Convert multiple JSON files to CSV Python | 29 Dec, 2020
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms :
JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data between an internet application and a server.
CSV File: A CSV may be a comma-separated values file, which allows data to be saved during a tabular format. CSVs appear as if a garden-variety spreadsheet but with a .CSV extension. CSV files are often used with almost any spreadsheet program, like Microsoft Excel or Google Spreadsheets.
To form a CSV file from multiple JSON files, we have to use nested json file, flatten the dataframe or to load the json files into the form of dataframe, concatenate/merge/join these to form one dataframe (at least one column should be same in all json files) and at last convert this dataframe into CSV file. This full procedure of the given task can be understood with the help of examples which are given below :
Example 1: If all columns match
In this example, we will load two json files, concatenate one to another and convert to a CSV file. The json files used for this are :
file1.json
{
"ID":{
"0":23,
"1":43,
"2":12,
"3":13,
"4":67,
"5":89
},
"Name":{
"0":"Ram",
"1":"Deep",
"2":"Yash",
"3":"Aman",
"4":"Arjun",
"5":"Aditya"
},
"Marks":{
"0":89,
"1":97,
"2":45,
"3":78,
"4":56,
"5":76
},
"Grade":{
"0":"B",
"1":"A",
"2":"F",
"3":"C",
"4":"E",
"5":"C"
}
}
file2.json
{
"ID":{
"0":90,
"1":56,
"2":34,
"3":96,
"4":45
},
"Name":{
"0":"Akash",
"1":"Chalsea",
"2":"Divya",
"3":"Sajal",
"4":"Shubham"
},
"Marks":{
"0":81,
"1":87,
"2":100,
"3":89,
"4":78
},
"Grade":{
"0":"B",
"1":"B",
"2":"A",
"3":"B",
"4":"C"
}
}
Step 1: Load the json files with the help of pandas dataframe.Step 2 : Concatenate the dataframes into one dataframe.Step 3: Convert the concatenated dataframe into CSV file.
The complete code with the result is shown below :
Python3
# importing packagesimport pandas as pd # load json file using pandasdf1 = pd.read_json('file1.json') # view dataprint(df1) # load json file using pandasdf2 = pd.read_json('file2.json') # view dataprint(df2) # use pandas.concat method df = pd.concat([df1,df2]) # view the concatenated dataframeprint(df) # convert dataframe to csv filedf.to_csv("CSV.csv",index=False) # load the resultant csv fileresult = pd.read_csv("CSV.csv") # and view the dataprint(result)
Output:
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 13 Aman 78 C
4 67 Arjun 56 E
5 89 Aditya 76 C
ID Name Marks Grade
0 90 Akash 81 B
1 56 Chalsea 87 B
2 34 Divya 100 A
3 96 Sajal 89 B
4 45 Shubham 78 C
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 13 Aman 78 C
4 67 Arjun 56 E
5 89 Aditya 76 C
0 90 Akash 81 B
1 56 Chalsea 87 B
2 34 Divya 100 A
3 96 Sajal 89 B
4 45 Shubham 78 C
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 13 Aman 78 C
4 67 Arjun 56 E
5 89 Aditya 76 C
6 90 Akash 81 B
7 56 Chalsea 87 B
8 34 Divya 100 A
9 96 Sajal 89 B
10 45 Shubham 78 C
Example 2: If some columns match
In this example, we will load two json files, merge these and convert to a CSV file. The json files used for this are :
file3.json
{
"ID":{
"0":23,
"1":43,
"2":12,
"3":13,
"4":67,
"5":89
},
"Name":{
"0":"Ram",
"1":"Deep",
"2":"Yash",
"3":"Aman",
"4":"Arjun",
"5":"Aditya"
},
"Marks":{
"0":89,
"1":97,
"2":45,
"3":78,
"4":56,
"5":76
}
}
file4.json
{
"ID":{
"0":23,
"1":43,
"2":12,
"3":67,
"4":89
},
"Name":{
"0":"Ram",
"1":"Deep",
"2":"Yash",
"3":"Arjun",
"4":"Aditya"
},
"Grade":{
"0":"B",
"1":"A",
"2":"F",
"3":"E",
"4":"C"
}
}
Step 1: Load the json files with the help of pandas dataframe.
Step 2: Merge the dataframes by different methods as inner/outer/left/right joins.
Step 3: Convert the merged dataframe into CSV file.
The complete code with the result is shown below :
Code:
Python3
# importing packagesimport pandas as pd # load json file using pandasdf1 = pd.read_json('file3.json') # view dataprint(df1) # load json file using pandasdf2 = pd.read_json('file4.json') # view dataprint(df2) # use pandas.merge methoddf_inner = pd.merge(df1, df2, how='inner', left_on=[ 'ID', 'Name'], right_on=['ID', 'Name'])df_outer = pd.merge(df1, df2, how='outer', left_on=[ 'ID', 'Name'], right_on=['ID', 'Name'])df_left = pd.merge(df1, df2, how='left', left_on=[ 'ID', 'Name'], right_on=['ID', 'Name'])df_right = pd.merge(df1, df2, how='right', left_on=[ 'ID', 'Name'], right_on=['ID', 'Name']) # convert dataframe to csv filedf_inner.to_csv("CSV_inner.csv", index=False)df_outer.to_csv("CSV_outer.csv", index=False)df_left.to_csv("CSV_left.csv", index=False)df_right.to_csv("CSV_right.csv", index=False) # load the resultant csv fileresult_inner = pd.read_csv("CSV_inner.csv")result_outer = pd.read_csv("CSV_outer.csv")result_left = pd.read_csv("CSV_left.csv")result_right = pd.read_csv("CSV_right.csv") # and view the dataprint(result_outer)print(result_inner)print(result_left)print(result_right)
Output:
ID Name Marks
0 23 Ram 89
1 43 Deep 97
2 12 Yash 45
3 13 Aman 78
4 67 Arjun 56
5 89 Aditya 76
ID Name Grade
0 23 Ram B
1 43 Deep A
2 12 Yash F
3 67 Arjun E
4 89 Aditya C
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 13 Aman 78 NaN
4 67 Arjun 56 E
5 89 Aditya 76 C
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 67 Arjun 56 E
4 89 Aditya 76 C
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 13 Aman 78 NaN
4 67 Arjun 56 E
5 89 Aditya 76 C
ID Name Marks Grade
0 23 Ram 89 B
1 43 Deep 97 A
2 12 Yash 45 F
3 67 Arjun 56 E
4 89 Aditya 76 C
Example 3: If nested json file is given
In this example, we will load nested json file, flatten it and then convert into CSV file. The json file used for this is :
file5.json
{
"tickets":[
{
"Name": "Liam",
"Location": {
"City": "Los Angeles",
"State": "CA"
},
"hobbies": [
"Piano",
"Sports"
],
"year" : 1985,
"teamId" : "ATL",
"playerId" : "barkele01",
"salary" : 870000
},
{
"Name": "John",
"Location": {
"City": "Los Angeles",
"State": "CA"
},
"hobbies": [
"Music",
"Running"
],
"year" : 1985,
"teamId" : "ATL",
"playerId" : "bedrost01",
"salary" : 550000
}
],
"count": 2
}
Step 1: Load the nested json file with the help of json.load() method.
Step 2: Flatten the different column values using pandas methods.
Step 3: Convert the flattened dataframe into CSV file.
Repeat the above steps for both the nested files and then follow either example 1 or example 2 for conversion. To convert a single nested json file follow the method given below.
The complete code with the result is shown below :
Code:
Python3
# importing packagesimport pandas as pdimport json # load json file using json.loadwith open('file5.json') as file: data = json.load(file) # view dataprint(data) # form the dataframedf = pd.DataFrame(data['tickets']) # view dataframeprint(df) # flattern the dataframe and remove unnecessary columnsfor i, item in enumerate(df['Location']): df['location_city'] = dict(df['Location'])[i]['City'] df['location_state'] = dict(df['Location'])[i]['State'] for i, item in enumerate(df['hobbies']): df['hobbies_{}'.format(i)] = dict(df['hobbies'])[i] df = df.drop({'Location', 'hobbies'}, axis=1) # view dataframeprint(df) # convert dataframe to csv filedf.to_csv("CSV.csv", index=False) # load the resultant csv fileresult = pd.read_csv("CSV.csv") # and view the dataprint(result)
Output:
{‘tickets’: [{‘Name’: ‘Liam’, ‘Location’: {‘City’: ‘Los Angeles’, ‘State’: ‘CA’}, ‘hobbies’: [‘Piano’, ‘Sports’], ‘year’: 1985, ‘teamId’: ‘ATL’, ‘playerId’: ‘barkele01’, ‘salary’: 870000}, {‘Name’: ‘John’, ‘Location’: {‘City’: ‘Los Angeles’, ‘State’: ‘CA’}, ‘hobbies’: [‘Music’, ‘Running’], ‘year’: 1985, ‘teamId’: ‘ATL’, ‘playerId’: ‘bedrost01’, ‘salary’: 550000}], ‘count’: 2}
Location Name hobbies playerId \
0 {‘City’: ‘Los Angeles’, ‘State’: ‘CA’} Liam [Piano, Sports] barkele01
1 {‘City’: ‘Los Angeles’, ‘State’: ‘CA’} John [Music, Running] bedrost01
salary teamId year
0 870000 ATL 1985
1 550000 ATL 1985
Name playerId salary teamId year location_city location_state \
0 Liam barkele01 870000 ATL 1985 Los Angeles CA
1 John bedrost01 550000 ATL 1985 Los Angeles CA
hobbies_0 hobbies_1
0 Piano Music
1 Sports Running
Name playerId salary teamId year location_city location_state \
0 Liam barkele01 870000 ATL 1985 Los Angeles CA
1 John bedrost01 550000 ATL 1985 Los Angeles CA
hobbies_0 hobbies_1
0 Piano Music
1 Sports Running
Python json-programs
python-csv
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 178,
"s": 52,
"text": "In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms :"
},
{
"code": null,
"e": 446,
"s... |
Jackson - Object Serialization | let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class. We'll create a student.json file which will have a json representation of Student object.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
Student student1 = tester.readJSON();
System.out.println(student1);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("student.json"), student);
}
private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(new File("student.json"), Student.class);
return student;
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 10 ] | [
{
"code": null,
"e": 2121,
"s": 1887,
"text": "let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class. We'll create a student.json file which will have a json representation of Student object."
},
{
"code... |
Possible to make a divisible by 3 number using all digits in an array | 07 Jun, 2022
Given an array of integers, the task is to find whether it’s possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print “Yes” and if not print “No”. Examples:
Input : arr[] = {40, 50, 90}
Output : Yes
We can construct a number which is
divisible by 3, for example 945000.
So the answer is Yes.
Input : arr[] = {1, 4}
Output : No
The only possible numbers are 14 and 41,
but both of them are not divisible by 3,
so the answer is No.
The idea is based on the fact that a number is divisible by 3 if the sum of its digits is divisible by 3. So we simply find the sum of array elements. If the sum is divisible by 3, our answer is Yes, else No.
CPP
Java
Python3
C#
PHP
Javascript
// C++ program to find if it is possible// to make a number divisible by 3 using// all digits of given array#include <bits/stdc++.h>using namespace std; bool isPossibleToMakeDivisible(int arr[], int n){ // Find remainder of sum when divided by 3 int remainder = 0; for (int i=0; i<n; i++) remainder = (remainder + arr[i]) % 3; // Return true if remainder is 0. return (remainder == 0);} // Driver codeint main(){ int arr[] = { 40, 50, 90 }; int n = sizeof(arr) / sizeof(arr[0]); if (isPossibleToMakeDivisible(arr, n)) printf("Yes\n"); else printf("No\n"); return 0;}
// Java program to find if it is possible// to make a number divisible by 3 using// all digits of given array import java.io.*;import java.util.*; class GFG{ public static boolean isPossibleToMakeDivisible(int arr[], int n) { // Find remainder of sum when divided by 3 int remainder = 0; for (int i=0; i<n; i++) remainder = (remainder + arr[i]) % 3; // Return true if remainder is 0. return (remainder == 0); } public static void main (String[] args) { int arr[] = { 40, 50, 90 }; int n = 3; if (isPossibleToMakeDivisible(arr, n)) System.out.print("Yes\n"); else System.out.print("No\n"); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>
# Python program to find if it is possible# to make a number divisible by 3 using# all digits of given array def isPossibleToMakeDivisible(arr, n): # Find remainder of sum when divided by 3 remainder = 0 for i in range (0, n): remainder = (remainder + arr[i]) % 3 # Return true if remainder is 0. return (remainder == 0) # main() arr = [40, 50, 90 ];n = 3if (isPossibleToMakeDivisible(arr, n)): print("Yes")else: print("No") # Code Contributed by Mohit Gupta_OMG <(0_o)>
// C# program to find if it is possible// to make a number divisible by 3 using// all digits of given arrayusing System; class GFG{ public static bool isPossibleToMakeDivisible(int []arr, int n) { // Find remainder of sum when divided by 3 int remainder = 0; for (int i = 0; i < n; i++) remainder = (remainder + arr[i]) % 3; // Return true if remainder is 0. return (remainder == 0); } public static void Main () { int []arr = { 40, 50, 90 }; int n = 3; if (isPossibleToMakeDivisible(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m
<?php// PHP program to find if it is possible// to make a number divisible by 3 using// all digits of given array function isPossibleToMakeDivisible($arr, $n){ // Find remainder of sum // when divided by 3 $remainder = 0; for ($i = 0; $i < $n; $i++) $remainder = ($remainder + $arr[$i]) % 3; // Return true if remainder is 0. return ($remainder == 0);} // Driver code$arr = array( 40, 50, 90 );$n = sizeof($arr);if (isPossibleToMakeDivisible($arr, $n)) echo("Yes\n");else echo("No\n"); // This code is contributed by Ajit.?>
<script> // javascript program to find if it is possible// to make a number divisible by 3 using// all digits of given array function isPossibleToMakeDivisible(arr , n){ // Find remainder of sum when divided by 3 var remainder = 0; for (i=0; i<n; i++) remainder = (remainder + arr[i]) % 3; // Return true if remainder is 0. return (remainder == 0);} var arr = [ 40, 50, 90 ];var n = 3;if (isPossibleToMakeDivisible(arr, n)) document.write("Yes\n");else document.write("No\n"); // This code contributed by Princi Singh </script>
Output:
Yes
Time Complexity: O(n) Space Complexity: O(1)
jit_t
princi singh
harshmaster07705
divisibility
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 292,
"s": 52,
"text": "Given an array of integers, the task is to find whether it’s possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If i... |
Java Signature getInstance() method with Examples | 12 May, 2021
The getInstance() method of java.security.Provider class is used to return a Signature object that implements the specified signature algorithm.
This method traverses the list of registered security Providers, starting with the most preferred Provider. A new Signature object encapsulating the SignatureSpi implementation from the first Provider that supports the specified algorithm is returned.
Syntax:
public static Signature getInstance(String algorithm)
throws NoSuchAlgorithmException
Parameters: This method takes the standard name of Algorithm as a parameter.Return Value: This method returns the new Signature object.Exception: This method throws NoSuchAlgorithmException if no Provider supports a Signature implementation for the specified algorithm.
Below are the examples to illustrate the getInstance() method:
Example 1:
Java
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of Signature and getting instance // By using getInstance() method Signature sr = Signature.getInstance("SHA1WithRSA"); // getting the status of signature object String str = sr.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } }}
Status : Signature object: SHA1WithRSA
Example 2: To show NoSuchAlgorithmException
Java
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of Signature and getting instance // By using getInstance() method System.out.println("Trying to get the instance of unknown instance"); Signature sr = Signature.getInstance("TAJMAHAL"); // getting the status of signature object String str = sr.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } }}
Trying to get the instance of unknown instance
Exception thrown : java.security.NoSuchAlgorithmException: TAJMAHAL Signature not available
The getInstance() method of java.security.Provider class is used to Returns a Signature object that implements the specified signature algorithm.
A new Signature object encapsulating the SignatureSpi implementation from the specified Provider object is returned. Note that the specified Provider object does not have to be registered in the provider list.
Syntax:
public static Signature
getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException
Parameters: This method takes the following arguments as a parameters:
algorithm– the name of the algorithm requested.
provider– the provider
Return Value: This method returns the new Signature object.
Exception: This method throws following exceptions:
NoSuchAlgorithmException– if a SignatureSpi implementation for the specified algorithm is not available from the specified Provider object.
IllegalArgumentException– if the provider is null.
Below are the examples to illustrate the getInstance() method:
Example 1:
Java
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of Signature and getting instance // By using getInstance() method Signature sr = Signature.getInstance("SHA1WithRSA"); // creating Provider object Provider pd = sr.getProvider(); // getting algorithm name // by using getAlgorithm() method String algo = sr.getAlgorithm(); // creating the object of Signature and getting instance // By using getInstance() method Signature sr1 = Signature.getInstance(algo, pd); // getting the status of signature object String str = sr1.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } }}
Status : Signature object: SHA1WithRSA
Example 2: To show NoSuchAlgorithmException
Java
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of Signature and getting instance // By using getInstance() method Signature sr = Signature.getInstance("SHA1WithRSA"); // creating Provider object Provider pd = sr.getProvider(); // getting algorithm name // by using getAlgorithm() method String algo = sr.getAlgorithm(); // creating the object of Signature and getting instance // By using getInstance() method Signature sr1 = Signature.getInstance("TAJMAHAL", pd); // getting the status of signature object String str = sr1.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } }}
Exception thrown : java.security.NoSuchAlgorithmException: no such algorithm: TAJMAHAL for provider SunRsaSign
Example 3: To show IllegalArgumentException
Java
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of Signature and getting instance // By using getInstance() method Signature sr = Signature.getInstance("SHA1WithRSA"); // creating Provider object Provider pd = null; // getting algorithm name // by using getAlgorithm() method String algo = sr.getAlgorithm(); // creating the object of Signature and getting instance // By using getInstance() method Signature sr1 = Signature.getInstance(algo, pd); // getting the status of signature object String str = sr1.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (ProviderException e) { System.out.println("Exception thrown : " + e); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }}
Exception thrown : java.lang.IllegalArgumentException: missing provider
Akanksha_Rai
anikakapoor
Java-Functions
Java-security package
Java-Signature
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "The getInstance() method of java.security.Provider class is used to return a Signature object that implements the specified signature algorithm."
},
{
"code": null,
... |
Python – Maximum and Minimum K elements in Tuple | 16 Aug, 2021
Sometimes, while dealing with tuples, we can have problem in which we need to extract only extreme K elements, i.e maximum and minimum K elements in Tuple. This problem can have applications across domains such as web development and Data Science. Let’s discuss certain ways in which this problem can be solved.
Input : test_tup = (3, 7, 1, 18, 9), k = 2 Output : (3, 1, 9, 18)Input : test_tup = (3, 7, 1), k=1 Output : (1, 3)
Method #1 : Using sorted() + loop The combination of above functionalities can be used to solve this problem. In this, we perform the sort operation using sorted(), and the problem of extraction of max and min K elements using loop.
Python3
# Python3 code to demonstrate working of# Maximum and Minimum K elements in Tuple# Using sorted() + loop # initializing tupletest_tup = (5, 20, 3, 7, 6, 8) # printing original tupleprint("The original tuple is : " + str(test_tup)) # initializing KK = 2 # Maximum and Minimum K elements in Tuple# Using sorted() + loopres = []test_tup = list(sorted(test_tup)) for idx, val in enumerate(test_tup): if idx < K or idx >= len(test_tup) - K: res.append(val)res = tuple(res) # printing resultprint("The extracted values : " + str(res))
The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)
Method #2 : Using list slicing + sorted() The combination of above functions can be used to solve this problem. In this, we perform the task of max, min extraction using slicing rather than brute force loop logic.
Python3
# Python3 code to demonstrate working of# Maximum and Minimum K elements in Tuple# Using slicing + sorted() # initializing tupletest_tup = (5, 20, 3, 7, 6, 8) # printing original tupleprint("The original tuple is : " + str(test_tup)) # initializing KK = 2 # Maximum and Minimum K elements in Tuple# Using slicing + sorted()test_tup = list(test_tup)temp = sorted(test_tup)res = tuple(temp[:K] + temp[-K:]) # printing resultprint("The extracted values : " + str(res))
The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)
dasaritejaswaroop8
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 365,
"s": 52,
"text": "Sometimes, while dealing with tuples, we can have problem in which we need to extract only extreme K elements, i.e maximum and minimum K elements in Tuple. This problem can h... |
How to filter nested objects in JavaScript ? | 05 Nov, 2020
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Approach 1: This approach uses filter() method to filter the nested object in JavaScript.
Example:
HTML
<!DOCTYPE html><html> <body> <h2>Output</h2> <p id="Output"></p> <script> var nestedObject = [ { itemId: 1, itemDetails: { name: "C", caregory: "Programming Language", price: 500, }, itemCategory: "Basic", }, { itemId: 2, itemDetails: { name: "C++", caregory: "Programming Language", price: 700, }, itemCategory: "Beginner", }, { itemId: 1, itemDetails: { name: "Java Script", caregory: "Web Development", price: 1500, }, itemCategory: "Advanced", }] let itemNames = nestedObject.filter( eachObj => eachObj.itemDetails.price === 1500); document.getElementById("Output").innerHTML = JSON.stringify(itemNames); </script></body> </html>
Output:
In the above example, only “JavaScript” is the name of the course with price “1500”.
Approach 2: This approach uses some() method to filter the nested objects. The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
Example:
HTML
<!DOCTYPE html><html> <body> <h2>Output</h2> <p id="Output"></p> <script> const fruitData = [ { name: "Apples", details: [ { fruitId: '1', gradingDetails: [{ grade: 'A' }] }, { fruitId: '2', gradingDetails: [{ grade: 'B' }] } ] }, { name: "Oranges", details: [ { fruitId: '3', gradingDetails: [{ grade: 'B' }] }, { fruitId: '4', gradingDetails: [{ grade: 'D' }] } ] }, ]; let output = fruitData.filter(eachVal => { let opt = eachVal.details.some(( { gradingDetails }) => gradingDetails .some(({ grade }) => grade === 'A')); return opt; }) console.log(output); document.getElementById("Output").innerHTML = JSON.stringify(output); </script></body> </html>
Output:
In the above example, the fruitId is 1 for “Apples”and grade is “A”. But for Oranges neither of them satisfies the option.
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 169,
"s": 54,
"text": "The filter() method creates a new array with all elements that pass the test implemented by the provided function."
},
{
"code": null,
"e": 259,
"s": 169,
... |
Creating array of pointers in C++ | 23 Jun, 2022
An array of pointers is an array of pointer variables. It is also known as pointer arrays. We will discuss how to create a 1D and 2D array of pointers dynamically. The word dynamic signifies that the memory is allocated during the runtime, and it allocates memory in Heap Section. In a Stack, memory is limited but is depending upon which language/OS is used, the average size is 1MB.
Dynamic 1D Array in C++: An array of pointers is a type of array that consists of variables of the pointer type. It means that those variables can point to some other array elements.
Example:
int *p[3];
// Now P[0], P[1], P[2] can point to int memory blocks.
In a dynamically allocated array of size N, the block is created in the heap and returns the address of the first memory block. By using that address every element can be accessed. The dynamic array in C++ one should be familiar with the new keywords or malloc(), calloc() can be used.
Syntax:
<dataType> * <pointer name> = new <dataType> [<size>];
Example:
int *p = new int [5];
Accessing Elements of a Dynamic Array:
1. 1D array of size N(= 5) is created and the base address is assigned to the variable P. If the below statement is written then the output is 1000.
cout << p;
If the value in the 1000th address is wanted then dereferenced it using the * (asterisk) symbol as illustrated below:
cout << *P;
// It is the same as P[0]. The output is 23.
Basic Pointer Arithmetic: Below is some points regarding Pointer Arithmetic:
*(P + 1):
P = 1000 and 1 = sizeof(int) = 4 bytes.Hence, *(1004) and dereferencing by * (asterisk) symbol. Now, the final result is 38.
*(P) + 1:
P = 1000 Hence, *(1000) and dereferencing by * (asterisk) symbol and then by adding 1 modifies the result to 23 + 1 = 24.
Below is the C++ program to illustrate the above concepts:
C++
// C++ program to illustrate the concepts// of creating 1D array of pointers#include <iostream>using namespace std; // Driver Codeint main(){ // Dynamically creating the array // of size = 5 int* p = new int[5]; // Initialize the array p[] as // {10, 20, 30, 40, 50} for (int i = 0; i < 5; i++) { p[i] = 10 * (i + 1); } // Print the values using pointers cout << *p << endl; cout << *p + 1 << endl; cout << *(p + 1) << endl; cout << 2 [p] << endl; cout << p[2] << endl; *p++; // Pointing to next location cout << *p; return 0;}
10
11
20
30
30
20
Dynamic 2D Array of Pointers in C++: A dynamic array of pointers is basically an array of pointers where every array index points to a memory block. This represents a 2D view in our mind. But logically it is a continuous memory block.
Syntax:
<dataType> **<Pointer name> = new <dataType> *[<size>];
Example:
int **P = new int *[4];
Note: The *(asterisk) symbol defines the level of the pointer, one * means one level of pointers, where ** implies two levels of pointers, and so on. Also, the level of the pointer must be the same as the dimensional array you want to create dynamically.
Approach:
Create a 1D array of pointers.
Now, create the column as array of pointers for each row as:P[0] = new int [3];P[1] = new int [3];P[2] = new int [3];P[3] = new int [3];
P[0] = new int [3];
P[1] = new int [3];
P[2] = new int [3];
P[3] = new int [3];
The 1D array of pointers are pointing to a memory block(size is mentioned). Basically, P[0], ..., P[3] are pointing to a 1D array of integers.
Accessing the array elements:
*P is equal to P[0] which is the address of the 1st row, 1st column is &P[0][0] = 3000.
*(P + 1) is equal to ‘P‘ is 1000 + 1(sizeof int) = 1004 and * means dereferencing. So the value stored at the address is printed i.e., *1004 = 4000.
*(P + 1) + 2 is same as above case but +2 means (&P[1] + 2) is equal to &P[1] [2] = 4008.
*(*(P + 1) + 2) is same as above case but that first asterisk ‘*(....)’ means dereferencing that address. Therefore, the result is equal to the value in &P[1][2] = *(4008) = 54.
Below is the C++ program to illustrate the above concepts:
C++
// C++ program to illustrate the concepts// of creating 2-D array of pointers#include <iostream>using namespace std; // Driver Codeint main(){ int N = 3; // Creating the array of pointers // of size N int** p = new int*[N]; int x = 1; // For multiplying for (int i = 0; i < N; i++) { p[i] = new int[N]; // Creating N sized int memory // block for (int j = 0; j < N; j++, x++) { p[i][j] = 10 * x; // The above statement can // also be written as: // *(*(p+i)+j) = 10 * x } } // Print the values using pointers cout << *p << endl; cout << **p << endl; cout << *p + 1 << endl; cout << **p + 1 << endl; cout << *(*(p + 1) + 0) << endl; cout << p[2][2] << endl; return 0;}
0x158de90
10
0x158de94
11
40
90
sazinsamin
akashmishra983963
CPP-Basics
cpp-pointer
Pointers
C++
C++ Programs
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 437,
"s": 52,
"text": "An array of pointers is an array of pointer variables. It is also known as pointer arrays. We will discuss how to create a 1D and 2D array of pointers dynamically. The word d... |
How to get all alphabetic chars in an array in PHP ? | 10 Oct, 2019
All alphabetic characters in an array can be achieved by using chr(), range() with for and foreach loop in PHP. To display the array elements as output we can use echo, print_r() and var_dump() function.
Using range() function: This function is used to create an array of elements of any kind such as integer, alphabets within a given range (from low to high) i.e, the first element of list is considered as low and last one is considered as high. It returns an array of alphabets if the range from A to Z i.e. range(A, Z).
Syntax:
array range( mixed first, mixed second, number steps )
Example 1: Below example illustrate how to display an array of all alphabetic character using range() function.
<?php // Loop to take values from given range// and display the range elementsforeach( range('A', 'Z') as $elements) { // Display all alphabetic elements // one after another echo $elements . ", ";} ?>
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
Example 2: Below example illustrate how to display an array of all Alphabetic character using range() function along with array_combine.
<?php // Merge the lower and upper case alphabetic// characters and store it into an array$alphachar = array_merge(range('A', 'Z'), range('a', 'z')); // Loop executes upto all array elementsforeach ($alphachar as $element) { // Display the array elements echo $element . " ";} ?>
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
Using chr() function: The chr() function is used to convert an ASCII value to a character. It accepts an ASCII value as a parameter and returns a string representing a character from the specified ASCII value. The ASCII value can be specified in decimal, octal, or hex values. It returns an array of alphabet if the chr() has its ASCII values from 65 to 91 for alphabet.
Syntax:
string chr( <>int $value )
Example 1: Below example illustrate to display an array of all Alphabetic character using ASCII values.
<?php // Declare an empty array$array = Array(); // Loop to convert ASCII value// into characters and store// it into variablesfor( $i = 65; $i < 91; $i++) { $array[] = chr($i);} // Loop to display the array elementsforeach( $array as $k => $v) { // Display the key and its // value of an array echo $k . " => " . $v . ", ";} ?>
0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H,
8 => I, 9 => J, 10 => K, 11 => L, 12 => M, 13 => N, 14 => O,
15 => P, 16 => Q, 17 => R, 18 => S, 19 => T, 20 => U, 21 => V,
22 => W, 23 => X, 24 => Y, 25 => Z,
Example 2: Below example illustrate to display an array of all Alphabetic character using ASCII values with the help of chr() function.
<?php // Loop to display the ASCII value and// its corresponding characterfor( $x = 65; $x <= 90; $x++) { echo $x . " => " . chr($x) . ", ";} ?>
65 => A, 66 => B, 67 => C, 68 => D, 69 => E, 70 => F, 71 => G,
72 => H, 73 => I, 74 => J, 75 => K, 76 => L, 77 => M, 78 => N,
79 => O, 80 => P, 81 => Q, 82 => R, 83 => S, 84 => T, 85 => U,
86 => V, 87 => W, 88 => X, 89 => Y, 90 => Z,
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
How to create admin login page using PHP?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to send an email using PHPMailer ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2019"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "All alphabetic characters in an array can be achieved by using chr(), range() with for and foreach loop in PHP. To display the array elements as output we can use echo, print_... |
Python | Pandas Series.subtract() | 05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.subtract() function basically perform subtraction of series and other, element-wise (binary operator sub). It is equivalent to series - other, but with support to substitute a fill_value for missing data in one of the inputs.
Syntax: Series.subtract(other, level=None, fill_value=None, axis=0)
Parameter :other : Series or scalar valuefill_value : Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation.level : Broadcast across a level, matching Index values on the passed MultiIndex level
Returns : Series
Example #1 : Use Series.subtract() function to subtract a scalar from the given Series object element-wise.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)
Output :
Now we will use Series.subtract() function to perform subtraction of the series with a scalar element-wise.
# subtract all the elements of the # series by 10sr.subtract(10)
Output :
As we can see in the output, Series.subtract() function has successfully subtracted all the elements of the given Series object by 10. Notice no subtraction has been performed on the missing values. Example #2 : Use Series.subtract() function to subtract a scalar from the given Series object element-wise. Also replace the missing values by 100.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)
Output :
Now we will use Series.subtract() function to perform subtraction of the series with a scalar element-wise. We will replace the missing value in our series object by 100.
# subtract all the elements of the # series by 10 and also fill 100 at# the place of missing values.sr.subtract(10, fill_value = 100)
Output :
As we can see in the output, Series.subtract() function has successfully subtracted all the elements of the given Series object by 10. Notice how we have substituted 100 at the places of the missing values.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based index... |
How to modify existing figure instance in Matplotlib? | 13 Dec, 2021
In Python matplotlib.pyplot.figure() is used to modify existing Figure instance or make a new Figure instance. Generally, it is used to alter the basic properties of existing plots. It takes references to the concerned plots in case if it is used to alter the properties of the already formed plots. It returns the Figure instance and passes the same to new_figure_manager in the backend, which in return allows to custom hook Figure classes into the pyplot interface.
Syntax: matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs)
Parameters
num : It is a unique identifier for the figure. If the Figure instance is already there with the same value, that instance is returned else a new instance is created and random number assigned to it. In case the value is number then it acts as a unique id and in case of string it also acts as Image label. This parameter is optional.
figsize: It is a parameter which takes in a tuple or a list of 2 floats mentioning the width and height of the figure respectively. By default it is set as [6.4, 4.8]
dpi: As the name suggest, it takes in the dots per inch as a float value. Default value is 100.
facecolor : It is used to set the background color of the figure. Default value is ‘white’.
edgecolor: It is used to set the border color of the figure. Default value is ‘white’.
FigureClass: Takes in the subclass of Figure Optionally used for referring any custom Figure instance.
clear: used to clear any existing figure on the respective instance.
Return: instance.close()
It is recommended to use the .close() method after using figure to use a clean the unnecessary memory. so to close the figure instance, write.
Example 1: Extract a Figure instance using a figure()
The example mentioned below shows how the figure method is used to label any plot and using this same label as a reference point to fetch the Figure instance. The asset statement confirms the fact that both instances are pointing to the same reference point.
Python3
import matplotlib.pyplot as plt # Figure instance with label => labelfig = plt.figure( num = 'label' ) fig.get_label() # This will fetch Figure instance fig onlyfig2 = plt.figure( num = 'label' )assert fig == fig2
Example 2: Plotting graph with custom height, width, and background
This example tells about how to plot a graph using the custom size of any plot and using custom dpi along with it. Here the background is also changed to yellow from white. The height is set to 10 and width to 7.
Python3
import matplotlib.pyplot as plt # plotting a yellow background# graph with dpi => 50plt.figure(num='label', facecolor='yellow', figsize=[10, 7], dpi=50) plt.plot([2.5, 1, 2.5, 4, 2.5], [1, 2.5, 4, 2.5, 1])
Output
Yellow background
Example 3: Example to clear the graph
The first code here is to show how the code will if two different plots are made on a single instance without using clear. The ideal thing that will work here is that it will plot both of them on a single figure.
Python3
import matplotlib.pyplot as plt plt.plot([2.5, 1, 2.5, 4, 2.5], [1, 2.5, 4, 2.5, 1]) plt.plot([1, 2, 3, 4], [1, 2, 3, 4])
Output
Both plotted
Now execute the same code but by clearing the first plot just before implementing the 2nd one.
Python3
import matplotlib.pyplot as plt plt.plot([2.5, 1, 2.5, 4, 2.5], [1, 2.5, 4, 2.5, 1]) # This will clear the first plotplt.figure(clear=True) # This will make a new plot on a# different instanceplt.plot([1, 2, 3, 4], [1, 2, 3, 4])
Output
Two different plots on clearing
Example 4: Check the return type
The figure() returns a Figure instance, the next example just verifies this fact.
Python3
import matplotlib.pyplot as plt # the type comes out as Figure Instance.print(type(plt.figure()))
Output:
adnanirshad158
sagartomar9927
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 497,
"s": 28,
"text": "In Python matplotlib.pyplot.figure() is used to modify existing Figure instance or make a new Figure instance. Generally, it is used to alter the basic properties of existing ... |
Difference between 3-address instruction and 2-address instructions | 20 Jun, 2020
Prerequisite – Instruction Formats1. Three-Address Instructions :Three-address instruction is a format of machine instruction. It has one opcode and three address fields. One address field is used for destination and two address fields for source.
Example –
X = (A + B) x (C + D)
Solution:
ADD R1, A, B R1 <- M[A] + M[B]
ADD R2, C, D R2 <- M[C] + M[D]
MUL X, R1, R2 M[X] <- R1 x R2
2. Two-Address Instructions :Two-address instruction is a format of machine instruction. It has one opcode and two address fields. One address field is common and can be used for either destination or source and other address field for source.
Example –
X = (A + B) x (C + D)
Solution:
MOV R1, A R1 <- M[A]
ADD R1, B R1 <- R1 + M[B]
MOV R2, C R2 <- M[C]
ADD R2, D R2 <- R2 + D
MUL R1, R2 R1 <- R1 x R2
MOV X, R1 M[X] <- R1
Difference between Three-Address Instruction and Two-Address Instruction :
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jun, 2020"
},
{
"code": null,
"e": 302,
"s": 54,
"text": "Prerequisite – Instruction Formats1. Three-Address Instructions :Three-address instruction is a format of machine instruction. It has one opcode and three address fields. One... |
PHP 7 - Return Type Declarations | In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.
int
float
bool
string
interfaces
array
callable
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
return $value;
}
print(returnIntValue(5));
?>
It produces the following browser output −
5
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
return $value + 1.0;
}
print(returnIntValue(5));
?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned... | [
{
"code": null,
"e": 2415,
"s": 2211,
"text": "In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared."
},
{
"code": null,
"e": 2419,
"s... |
Iterative Postorder Traversal | Set 1 (Using Two Stacks) | 21 Jun, 2022
We have discussed iterative inorder and iterative preorder traversals. In this post, iterative postorder traversal is discussed, which is more complex than the other two traversals (due to its nature of non-tail recursion, there is an extra statement after the final recursive call to itself). Postorder traversal can easily be done using two stacks, though. The idea is to push reverse postorder traversal to a stack. Once we have the reversed postorder traversal in a stack, we can just pop all items one by one from the stack and print them; this order of printing will be in postorder because of the LIFO property of stacks. Now the question is, how to get reversed postorder elements in a stack – the second stack is used for this purpose. For example, in the following tree, we need to get 1, 3, 7, 6, 2, 5, 4 in a stack. If take a closer look at this sequence, we can observe that this sequence is very similar to the preorder traversal. The only difference is that the right child is visited before left child, and therefore the sequence is “root right left” instead of “root left right”. So, we can do something like iterative preorder traversal with the following differences: a) Instead of printing an item, we push it to a stack. b) We push the left subtree before the right subtree.Following is the complete algorithm. After step 2, we get the reverse of a postorder traversal in the second stack. We use the first stack to get the correct order.
1. Push root to first stack.
2. Loop while first stack is not empty
2.1 Pop a node from first stack and push it to second stack
2.2 Push left and right children of the popped node to first stack
3. Print contents of second stack
Let us consider the following tree
Following are the steps to print postorder traversal of the above tree using two stacks.
1. Push 1 to first stack.
First stack: 1
Second stack: Empty
2. Pop 1 from first stack and push it to second stack.
Push left and right children of 1 to first stack
First stack: 2, 3
Second stack: 1
3. Pop 3 from first stack and push it to second stack.
Push left and right children of 3 to first stack
First stack: 2, 6, 7
Second stack: 1, 3
4. Pop 7 from first stack and push it to second stack.
First stack: 2, 6
Second stack: 1, 3, 7
5. Pop 6 from first stack and push it to second stack.
First stack: 2
Second stack: 1, 3, 7, 6
6. Pop 2 from first stack and push it to second stack.
Push left and right children of 2 to first stack
First stack: 4, 5
Second stack: 1, 3, 7, 6, 2
7. Pop 5 from first stack and push it to second stack.
First stack: 4
Second stack: 1, 3, 7, 6, 2, 5
8. Pop 4 from first stack and push it to second stack.
First stack: Empty
Second stack: 1, 3, 7, 6, 2, 5, 4
The algorithm stops here since there are no more items in the first stack.
Observe that the contents of second stack are in postorder fashion. Print them.
Following is the implementation of iterative postorder traversal using two stacks.
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // A tree nodestruct Node { int data; Node *left, *right;}; // Function to create a new node with the given dataNode* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node;}// An iterative function to do post order// traversal of a given binary treevoid postOrderIterative(Node* root){ if (root == NULL) return; // Create two stacks stack<Node *> s1, s2; // push root to first stack s1.push(root); Node* node; // Run while first stack is not empty while (!s1.empty()) { // Pop an item from s1 and push it to s2 node = s1.top(); s1.pop(); s2.push(node); // Push left and right children // of removed item to s1 if (node->left) s1.push(node->left); if (node->right) s1.push(node->right); } // Print all elements of second stack while (!s2.empty()) { node = s2.top(); s2.pop(); cout << node->data << " "; }} // Driver codeint main(){ // Let us construct the tree // shown in above figure Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); postOrderIterative(root); return 0;}
#include <stdio.h>#include <stdlib.h> // Maximum stack size#define MAX_SIZE 100 // A tree nodestruct Node { int data; struct Node *left, *right;}; // Stack typestruct Stack { int size; int top; struct Node** array;}; // A utility function to create a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A utility function to create a stack of given sizestruct Stack* createStack(int size){ struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->size = size; stack->top = -1; stack->array = (struct Node**)malloc(stack->size * sizeof(struct Node*)); return stack;} // BASIC OPERATIONS OF STACKint isFull(struct Stack* stack){ return stack->top - 1 == stack->size;} int isEmpty(struct Stack* stack){ return stack->top == -1;} void push(struct Stack* stack, struct Node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;} struct Node* pop(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];} // An iterative function to do post order traversal of a given binary treevoid postOrderIterative(struct Node* root){ if (root == NULL) return; // Create two stacks struct Stack* s1 = createStack(MAX_SIZE); struct Stack* s2 = createStack(MAX_SIZE); // push root to first stack push(s1, root); struct Node* node; // Run while first stack is not empty while (!isEmpty(s1)) { // Pop an item from s1 and push it to s2 node = pop(s1); push(s2, node); // Push left and right children of removed item to s1 if (node->left) push(s1, node->left); if (node->right) push(s1, node->right); } // Print all elements of second stack while (!isEmpty(s2)) { node = pop(s2); printf("%d ", node->data); }} // Driver program to test above functionsint main(){ // Let us construct the tree shown in above figure struct Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); postOrderIterative(root); return 0;}
// Java program for iterative post// order using two stacks import java.util.*;public class IterativePostorder { static class node { int data; node left, right; public node(int data) { this.data = data; } } // Two stacks as used in explanation static Stack<node> s1, s2; static void postOrderIterative(node root) { // Create two stacks s1 = new Stack<>(); s2 = new Stack<>(); if (root == null) return; // push root to first stack s1.push(root); // Run while first stack is not empty while (!s1.isEmpty()) { // Pop an item from s1 and push it to s2 node temp = s1.pop(); s2.push(temp); // Push left and right children of // removed item to s1 if (temp.left != null) s1.push(temp.left); if (temp.right != null) s1.push(temp.right); } // Print all elements of second stack while (!s2.isEmpty()) { node temp = s2.pop(); System.out.print(temp.data + " "); } } public static void main(String[] args) { // Let us construct the tree // shown in above figure node root = null; root = new node(1); root.left = new node(2); root.right = new node(3); root.left.left = new node(4); root.left.right = new node(5); root.right.left = new node(6); root.right.right = new node(7); postOrderIterative(root); }} // This code is contributed by Rishabh Mahrsee
# Python program for iterative postorder# traversal using two stacks # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # An iterative function to do postorder# traversal of a given binary treedef postOrderIterative(root): if root is None: return # Create two stacks s1 = [] s2 = [] # Push root to first stack s1.append(root) # Run while first stack is not empty while s1: # Pop an item from s1 and # append it to s2 node = s1.pop() s2.append(node) # Push left and right children of # removed item to s1 if node.left: s1.append(node.left) if node.right: s1.append(node.right) # Print all elements of second stack while s2: node = s2.pop() print(node.data,end=" ") # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)postOrderIterative(root)
// C# program for iterative post// order using two stacksusing System;using System.Collections;public class IterativePostorder { public class node { public int data; public node left, right; public node(int data) { this.data = data; } } // Two stacks as used in explanation static public Stack s1, s2; static void postOrderIterative(node root) { // Create two stacks s1 = new Stack(); s2 = new Stack(); if (root == null) return; // Push root to first stack s1.Push(root); // Run while first stack is not empty while (s1.Count > 0) { // Pop an item from s1 and Push it to s2 node temp = (node)s1.Pop(); s2.Push(temp); // Push left and right children of // removed item to s1 if (temp.left != null) s1.Push(temp.left); if (temp.right != null) s1.Push(temp.right); } // Print all elements of second stack while (s2.Count > 0) { node temp = (node)s2.Pop(); Console.Write(temp.data + " "); } } public static void Main(String[] args) { // Let us construct the tree // shown in above figure node root = null; root = new node(1); root.left = new node(2); root.right = new node(3); root.left.left = new node(4); root.left.right = new node(5); root.right.left = new node(6); root.right.right = new node(7); postOrderIterative(root); }} // This code is contributed by Arnab Kundu
<script> // JavaScript program for iterative post // order using two stacks class node { constructor(data) { this.data = data; this.left = null; this.right = null; } } function postOrderIterative(root) { // Two stacks as used in explanation // Create two stacks var s1 = []; var s2 = []; if (root == null) return; // Push root to first stack s1.push(root); // Run while first stack is not empty while (s1.length > 0) { // Pop an item from s1 and Push it to s2 var temp = s1.pop(); s2.push(temp); // Push left and right children of // removed item to s1 if (temp.left != null) s1.push(temp.left); if (temp.right != null) s1.push(temp.right); } // Print all elements of second stack while (s2.length > 0) { var temp = s2.pop(); document.write(temp.data + " "); } } // Let us construct the tree // shown in above figure var root = null; root = new node(1); root.left = new node(2); root.right = new node(3); root.left.left = new node(4); root.left.right = new node(5); root.right.left = new node(6); root.right.right = new node(7); postOrderIterative(root); </script>
Output:
4 5 2 6 7 3 1
Time complexity: O(n) where n is no of nodes in a binary tree
Iterative Postorder Traversal | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersIterative Postorder Traversal | 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 / 4:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=G7tvjUGMBJ4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Following is an overview of the above post. Iterative preorder traversal can be easily implemented using two stacks. The first stack is used to get the reverse postorder traversal. The steps to get a reverse postorder are similar to iterative preorder.You may also like to see a method which uses only one stack.This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
IshitaTripathi
andrew1234
rathbhupendra
dkp1903
rdtank
nivedkml
amartyaghoshgfg
noviced3vq6
Stack
Tree
Stack
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 1516,
"s": 54,
"text": "We have discussed iterative inorder and iterative preorder traversals. In this post, iterative postorder traversal is discussed, which is more complex than the other two tra... |
Node JS | Password Hashing with Crypto module | 06 Dec, 2019
In real life applications with User authentication functionality, it is not practical to store user password as the original string in the database but it is good practice to hash the password and then store them into the database.
Crypto module for Node JS helps developers to hash user password.
Examples:
Original Password : portalforgeeks
Hashed Password : bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f
1e3cf110b352c3ca6cc057955ace9d541573929cd7a74a
280a02e8cb549136b43df7704caaa555b38a
Password Hashing with Crypto module
To demonstrate the use of Crypto module, we can create a simple login and signup API and test it using Postman.We will use two functions:
cryto.randomBytes(“length”) : generates cryptographically strong data of given “length”.crypto.pbkdf2Sync(“password”, “salt”, “iterations”, “length”, “digest”) : hashes “password” with “salt” with number of iterations equal to given “iterations” (More iterations means more secure key) and uses algorithm given in “digest” and generates key of length equal to given “length”.
cryto.randomBytes(“length”) : generates cryptographically strong data of given “length”.
crypto.pbkdf2Sync(“password”, “salt”, “iterations”, “length”, “digest”) : hashes “password” with “salt” with number of iterations equal to given “iterations” (More iterations means more secure key) and uses algorithm given in “digest” and generates key of length equal to given “length”.
Project Dependencies:
node JS: For Backend Server.
express module for creating server.
mongoose module for MongoDB connection and queries.
Crypto module for hashing.
body-parser for parsing json data.
Steps to perform the operation
First create a directory structure as below :hashApp
--model
----user.js
--route
----user.js
--server.js
Create model/user.js file which defines user schema// Importing modulesconst mongoose = require('mongoose');var crypto = require('crypto'); // Creating user schemaconst UserSchema = mongoose.Schema({ name : { type : String, required : true }, email : { type : String, required : true }, hash : String, salt : String}); // Method to set salt and hash the password for a user// setPassword method first creates a salt unique for every user// then it hashes the salt with user password and creates a hash// this hash is stored in the database as user passwordUserSchema.methods.setPassword = function(password) { // Creating a unique salt for a particular user this.salt = crypto.randomBytes(16).toString('hex'); // Hashing user's salt and password with 1000 iterations, 64 length and sha512 digest this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`);}; // Method to check the entered password is correct or not// valid password method checks whether the user// password is correct or not// It takes the user password from the request // and salt from user database entry// It then hashes user password and salt// then checks if this generated hash is equal// to user's hash in the database or not// If the user's hash is equal to generated hash // then the password is correct otherwise notUserSchema.methods.validPassword = function(password) { var .hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`); return this.hash === hash;}; // Exporting module to allow it to be imported in other filesconst User = module.exports = mongoose.model('User', UserSchema);Create route/user.js file :// Importing modulesconst express = require('express');const router = express.Router(); // Importing User Schemaconst User = require('../model/user'); // User login apirouter.post('/login', (req, res) => { // Find user with requested email User.findOne({ email : req.body.email }, function(err, user) { if (user === null) { return res.status(400).send({ message : "User not found." }); } else { if (user.validPassword(req.body.password)) { return res.status(201).send({ message : "User Logged In", }) } else { return res.status(400).send({ message : "Wrong Password" }); } } });}); // User signup apirouter.post('/signup', (req, res, next) => { // Creating empty user object let newUser = new User(); // Initialize newUser object with request data newUser.name = req.body.name, newUser.email = req.body.email // Call setPassword function to hash password newUser.setPassword(req.body.password); // Save newUser object to database newUser.save((err, User) => { if (err) { return res.status(400).send({ message : "Failed to add user." }); } else { return res.status(201).send({ message : "User added successfully." }); } });}); // Export module to allow it to be imported in other filesmodule.exports = router;Create server.js file :// Importing modulesvar express = require('express');var mongoose = require('mongoose');var bodyparser = require('body-parser'); // Initialize express appvar app = express(); // Mongodb connection urlvar MONGODB_URI = "mongodb://localhost:27017/hashAppDb"; // Connect to MongoDBmongoose.connect(MONGODB_URI);mongoose.connection.on('connected', () => { console.log('Connected to MongoDB @ 27017');}); // Using bodyparser to parse json dataapp.use(bodyparser.json()); // Importing routesconst user = require('./route/user'); // Use user route when url matches /api/user/app.use('/api/user', user); // Creating serverconst port = 3000;app.listen(port, () => { console.log("Server running at port: " + port);});Run server.js file using command node server.js from the hashApp directoryOpen Postman and create a post request to localhost:3000/api/user/signup as below:You will get the response as below:User data is stored in the database as below:{
"_id": {
"$oid": "5ab71ef2afb6db0148052f6f"
},
"name": "geeksforgeeks",
"email": "geek@geeksforgeeks.org",
"salt": "ddee18ef6a6804fbb919b25f790005e3",
"hash": "bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f1e3cf110
b352c3ca6cc057955ace9d541573929cd7a74a280a02e8cb549136b43df7704caaa555b38a",
"__v": 0
}
From Postman create a post request to localhost:3000/api/user/login as below:You will get the response as below:
First create a directory structure as below :hashApp
--model
----user.js
--route
----user.js
--server.js
hashApp
--model
----user.js
--route
----user.js
--server.js
Create model/user.js file which defines user schema// Importing modulesconst mongoose = require('mongoose');var crypto = require('crypto'); // Creating user schemaconst UserSchema = mongoose.Schema({ name : { type : String, required : true }, email : { type : String, required : true }, hash : String, salt : String}); // Method to set salt and hash the password for a user// setPassword method first creates a salt unique for every user// then it hashes the salt with user password and creates a hash// this hash is stored in the database as user passwordUserSchema.methods.setPassword = function(password) { // Creating a unique salt for a particular user this.salt = crypto.randomBytes(16).toString('hex'); // Hashing user's salt and password with 1000 iterations, 64 length and sha512 digest this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`);}; // Method to check the entered password is correct or not// valid password method checks whether the user// password is correct or not// It takes the user password from the request // and salt from user database entry// It then hashes user password and salt// then checks if this generated hash is equal// to user's hash in the database or not// If the user's hash is equal to generated hash // then the password is correct otherwise notUserSchema.methods.validPassword = function(password) { var .hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`); return this.hash === hash;}; // Exporting module to allow it to be imported in other filesconst User = module.exports = mongoose.model('User', UserSchema);
// Importing modulesconst mongoose = require('mongoose');var crypto = require('crypto'); // Creating user schemaconst UserSchema = mongoose.Schema({ name : { type : String, required : true }, email : { type : String, required : true }, hash : String, salt : String}); // Method to set salt and hash the password for a user// setPassword method first creates a salt unique for every user// then it hashes the salt with user password and creates a hash// this hash is stored in the database as user passwordUserSchema.methods.setPassword = function(password) { // Creating a unique salt for a particular user this.salt = crypto.randomBytes(16).toString('hex'); // Hashing user's salt and password with 1000 iterations, 64 length and sha512 digest this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`);}; // Method to check the entered password is correct or not// valid password method checks whether the user// password is correct or not// It takes the user password from the request // and salt from user database entry// It then hashes user password and salt// then checks if this generated hash is equal// to user's hash in the database or not// If the user's hash is equal to generated hash // then the password is correct otherwise notUserSchema.methods.validPassword = function(password) { var .hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`); return this.hash === hash;}; // Exporting module to allow it to be imported in other filesconst User = module.exports = mongoose.model('User', UserSchema);
Create route/user.js file :// Importing modulesconst express = require('express');const router = express.Router(); // Importing User Schemaconst User = require('../model/user'); // User login apirouter.post('/login', (req, res) => { // Find user with requested email User.findOne({ email : req.body.email }, function(err, user) { if (user === null) { return res.status(400).send({ message : "User not found." }); } else { if (user.validPassword(req.body.password)) { return res.status(201).send({ message : "User Logged In", }) } else { return res.status(400).send({ message : "Wrong Password" }); } } });}); // User signup apirouter.post('/signup', (req, res, next) => { // Creating empty user object let newUser = new User(); // Initialize newUser object with request data newUser.name = req.body.name, newUser.email = req.body.email // Call setPassword function to hash password newUser.setPassword(req.body.password); // Save newUser object to database newUser.save((err, User) => { if (err) { return res.status(400).send({ message : "Failed to add user." }); } else { return res.status(201).send({ message : "User added successfully." }); } });}); // Export module to allow it to be imported in other filesmodule.exports = router;
// Importing modulesconst express = require('express');const router = express.Router(); // Importing User Schemaconst User = require('../model/user'); // User login apirouter.post('/login', (req, res) => { // Find user with requested email User.findOne({ email : req.body.email }, function(err, user) { if (user === null) { return res.status(400).send({ message : "User not found." }); } else { if (user.validPassword(req.body.password)) { return res.status(201).send({ message : "User Logged In", }) } else { return res.status(400).send({ message : "Wrong Password" }); } } });}); // User signup apirouter.post('/signup', (req, res, next) => { // Creating empty user object let newUser = new User(); // Initialize newUser object with request data newUser.name = req.body.name, newUser.email = req.body.email // Call setPassword function to hash password newUser.setPassword(req.body.password); // Save newUser object to database newUser.save((err, User) => { if (err) { return res.status(400).send({ message : "Failed to add user." }); } else { return res.status(201).send({ message : "User added successfully." }); } });}); // Export module to allow it to be imported in other filesmodule.exports = router;
Create server.js file :// Importing modulesvar express = require('express');var mongoose = require('mongoose');var bodyparser = require('body-parser'); // Initialize express appvar app = express(); // Mongodb connection urlvar MONGODB_URI = "mongodb://localhost:27017/hashAppDb"; // Connect to MongoDBmongoose.connect(MONGODB_URI);mongoose.connection.on('connected', () => { console.log('Connected to MongoDB @ 27017');}); // Using bodyparser to parse json dataapp.use(bodyparser.json()); // Importing routesconst user = require('./route/user'); // Use user route when url matches /api/user/app.use('/api/user', user); // Creating serverconst port = 3000;app.listen(port, () => { console.log("Server running at port: " + port);});
// Importing modulesvar express = require('express');var mongoose = require('mongoose');var bodyparser = require('body-parser'); // Initialize express appvar app = express(); // Mongodb connection urlvar MONGODB_URI = "mongodb://localhost:27017/hashAppDb"; // Connect to MongoDBmongoose.connect(MONGODB_URI);mongoose.connection.on('connected', () => { console.log('Connected to MongoDB @ 27017');}); // Using bodyparser to parse json dataapp.use(bodyparser.json()); // Importing routesconst user = require('./route/user'); // Use user route when url matches /api/user/app.use('/api/user', user); // Creating serverconst port = 3000;app.listen(port, () => { console.log("Server running at port: " + port);});
Run server.js file using command node server.js from the hashApp directory
Open Postman and create a post request to localhost:3000/api/user/signup as below:You will get the response as below:User data is stored in the database as below:{
"_id": {
"$oid": "5ab71ef2afb6db0148052f6f"
},
"name": "geeksforgeeks",
"email": "geek@geeksforgeeks.org",
"salt": "ddee18ef6a6804fbb919b25f790005e3",
"hash": "bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f1e3cf110
b352c3ca6cc057955ace9d541573929cd7a74a280a02e8cb549136b43df7704caaa555b38a",
"__v": 0
}
You will get the response as below:
User data is stored in the database as below:
{
"_id": {
"$oid": "5ab71ef2afb6db0148052f6f"
},
"name": "geeksforgeeks",
"email": "geek@geeksforgeeks.org",
"salt": "ddee18ef6a6804fbb919b25f790005e3",
"hash": "bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f1e3cf110
b352c3ca6cc057955ace9d541573929cd7a74a280a02e8cb549136b43df7704caaa555b38a",
"__v": 0
}
From Postman create a post request to localhost:3000/api/user/login as below:You will get the response as below:
You will get the response as below:
Applications:
Hashing password is necessary for practical application.
Crypto module makes hashing easy to implement.
Hashing passwords ensure user’s privacy.
References:
https://nodejs.org/api/crypto.html
https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
ssshivyasaxena20
shubham_singh
nidhi_biet
Node.js
GBlog
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
How to Learn Data Science in 10 weeks?
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
What is Data Structure: Types, Classifications and Applications
Roadmap to Learn JavaScript For Beginners
Axios in React: A Guide for Beginners
A Freshers Guide To Programming | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 284,
"s": 52,
"text": "In real life applications with User authentication functionality, it is not practical to store user password as the original string in the database but it is good practice to... |
Java Program to Remove Duplicate Elements From the Array | 13 Jun, 2022
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value
Given an array, the task is to remove the duplicate elements from the array.
Examples:
Input : a[] = {1, 1, 2, 2, 2}
Output : a[] = {1,2}
new size = 2
Input : a[] = {5,2,6,8,6,7,5,2,8}
Output : a[] = {2,5,6,7,8}
new size = 5
The ways for removing duplicate elements from the array:
Using extra spaceConstant extra spaceUsing SetUsing Frequency arrayUsing HashMap
Using extra space
Constant extra space
Using Set
Using Frequency array
Using HashMap
Method 1: (Using extra space)
Create a temporary array temp[] to store unique elements.Traverse input array and copy all the unique elements of a[] to temp[]. Also, keep count of unique elements. Let this count be j.Copy j elements from temp[] to a[].
Create a temporary array temp[] to store unique elements.
Traverse input array and copy all the unique elements of a[] to temp[]. Also, keep count of unique elements. Let this count be j.
Copy j elements from temp[] to a[].
Note: This approach is applicable when the array is sorted.
Java
// Java Program to Remove Duplicate Elements// From the Array using extra space public class Main { public static int removeduplicates(int a[], int n) { if (n == 0 || n == 1) { return n; } // creating another array for only storing // the unique elements int[] temp = new int[n]; int j = 0; for (int i = 0; i < n - 1; i++) { if (a[i] != a[i + 1]) { temp[j++] = a[i]; } } temp[j++] = a[n - 1]; // Changing the original array for (int i = 0; i < j; i++) { a[i] = temp[i]; } return j; } public static void main(String[] args) { int a[] = { 1, 1, 2, 2, 2 }; int n = a.length; n = removeduplicates(a, n); // Printing The array elements for (int i = 0; i < n; i++) System.out.print(a[i] + " "); }}
1 2
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: (Constant extra space)
Just maintain a separate index for the same array as maintained for different array in Method 1.
Java
// Java Program to Remove Duplicate Elements// From the Array using extra space public class Main { public static int removeDuplicates(int a[], int n) { // if(array size if 0 or 1 array is already sorted) if (n == 0 || n == 1) { return n; } int j = 0; // check if the ith element is not equal to // the (i+1)th element, then add that element // at the jth index in the same array // which indicates that te particular element // will only be added once in the array for (int i = 0; i < n - 1; i++) { if (a[i] != a[i + 1]) { a[j++] = a[i]; } } a[j++] = a[n - 1]; return j; } public static void main(String[] args) { int a[] = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6 }; int n = a.length; int j=0; // the function will modify the array a[] // such that the starting j elements // will be having all unique elements // and no element will be appearing more than // once j = removeDuplicates(a, n); // printing array elements for (int i = 0; i < j; i++) System.out.print(a[i] + " "); }}
1 2 3 4 5 6
Time Complexity: O(n)
Auxiliary Space: O(1)
Note: Both the methods mentioned above can be used if the array is sorted. So for using above-mentioned method is array is not sorted you need to sort the array. You can use the in-built method Arrays.sort() to sort the array. If sorting of the array is done using this method then the Time complexity of the program increases from O(n) to O(nlogn).
Method 3: Using Set
This method can be used even if the array is not sorted.
Approach:
Take a SetInsert all array elements in the Set. Set does not allow duplicates and sets like LinkedHashSet maintains the order of insertion so it will remove duplicates and elements will be printed in the same order in which it is inserted.Print elements of Set.
Take a Set
Insert all array elements in the Set. Set does not allow duplicates and sets like LinkedHashSet maintains the order of insertion so it will remove duplicates and elements will be printed in the same order in which it is inserted.
Print elements of Set.
Java
// Java Program to Remove Duplicate Elements// From the Array using Set import java.util.*; class GFG { // Function to remove duplicate from array public static void removeDuplicates(int[] a) { LinkedHashSet<Integer> set = new LinkedHashSet<Integer>(); // adding elements to LinkedHashSet for (int i = 0; i < a.length; i++) set.add(a[i]); // Print the elements of LinkedHashSet System.out.print(set); } // Driver code public static void main(String[] args) { int a[] = {5,2,6,8,6,7,5,2,8}; // Function call removeDuplicates(a); }}
[5, 2, 6, 8, 7]
Method 4: Using Frequency array
We can use the frequency array if the range of the number in the array is limited, or we can also use a set or map interface to remove duplicates if the range of numbers in the array is too large.
Approach:
Find the Maximum element (m) in the array.Create a new array of size m+1.Now traverse the input array and count the frequency of every element in the input array.Now traverse the frequency array and check for the frequency of every number if the frequency of the particular element is greater than 0 then print the number.
Find the Maximum element (m) in the array.
Create a new array of size m+1.
Now traverse the input array and count the frequency of every element in the input array.
Now traverse the frequency array and check for the frequency of every number if the frequency of the particular element is greater than 0 then print the number.
Java
// Java Program to Remove Duplicate Elements// From the Array by maintaining frequency array import java.util.*; class GFG { public static void main(String[] args) { int a[] = { 5, 2, 6, 8, 6, 7, 5, 2, 8 }; int n = a.length; // m will have the maximum element in the array. int m = 0; for (int i = 0; i < n; i++) { m = Math.max(m, a[i]); } // creating the frequency array int[] f = new int[m + 1]; // initializing the f[] with 0 for (int i = 0; i < m + 1; i++) { f[i] = 0; } // incrementing the value at a[i]th index // in the frequency array for (int i = 0; i < n; i++) { f[a[i]]++; } for (int i = 0; i < m + 1; i++) { // if the frequency of the particular element // is greater than 0, then print it once if (f[i] > 1) { System.out.print(i + " "); } } }}
2 5 6 8
Time Complexity: O(n)
Auxiliary Space: O(m)
Method 5: Using HashMap
The above frequency method will not be useful if the number is greater than 106 or if the array is of strings. In this case, we have to use HashMap.
Approach:
Create a HashMap to store the unique elements.
Traverse the array.
Check if the element is present in the HashMap.
If yes, continue traversing the array.
Else Print the element and store the element in HashMap.
Java
// Java Program to Remove Duplicate Elements// From the Array using HashMap import java.util.HashMap; class GFG { static void removeDups(int[] a, int n) { // Hash map which will store the // elements which has appeared previously. HashMap<Integer, Boolean> mp = new HashMap<>(); for (int i = 0; i < n; ++i) { // Print the element if it is not // present there in the hash map // and Insert the element in the hash map if (mp.get(a[i]) == null) { System.out.print(a[i] + " "); mp.put(a[i], true); } } } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 5, 1, 7, 2, 4, 2 }; int n = arr.length; removeDups(arr, n); }}
1 2 5 7 4
Time Complexity: O(n)
Auxiliary Space: O(m)
abhishekabhi7352
surinderdawra388
aniket_sonkar
Java-Array-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 263,
"s": 28,
"text": "An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. For simplicity, we can think of an arra... |
Rendering Data-Frame to html template in table view using Django Framework | 05 Sep, 2020
In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use ‘render’ and ‘HttpResponse’ functions to manipulate the data inside the DataFrame.
Sample DataFrame:
Methods to render dataframe to html template –
Using pandas.DataFrame.to_html(): By using this inbuilt function ‘to_html()‘ to convert DataFrame into HTML template. After using this method, the overall DataFrame is converted to ‘table’ html element, while the name of each column are transformed into ‘thead’ tag of table head. Whereas, each row of the DataFrame is transformed into ‘tr’ tag of table row element in HTML template page.views.pyfrom django.shortcuts import HttpResponseimport pandas as pd def Table(request): df = pd.read_csv("tableview/static/csv/20_Startups.csv") #'tableview/static/csv/20_Startups.csv' is the django # directory where csv file exist. # Manipulate DataFrame using to_html() function geeks_object = df.to_html() return HttpResponse(geeks_object)urls.py"""The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/Examples:Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name ='home')Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name ='home')Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))"""from django.contrib import adminfrom django.urls import pathfrom tableview import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Table, name ="table"),]Output:
from django.shortcuts import HttpResponseimport pandas as pd def Table(request): df = pd.read_csv("tableview/static/csv/20_Startups.csv") #'tableview/static/csv/20_Startups.csv' is the django # directory where csv file exist. # Manipulate DataFrame using to_html() function geeks_object = df.to_html() return HttpResponse(geeks_object)
urls.py
"""The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/Examples:Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name ='home')Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name ='home')Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))"""from django.contrib import adminfrom django.urls import pathfrom tableview import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Table, name ="table"),]
Output:
Parsing DataFrame into Json objects and render into bootstrap template: Here we use proper bootstrap template and get a table view using render() function.views.py# Write Python3 code herefrom django.shortcuts import renderimport pandas as pdimport json # Create your views here.def Table(request): df = pd.read_csv("tableview/static/csv/20_Startups.csv") # parsing the DataFrame in json format. json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'d': data} return render(request, 'table.html', context)table.html (‘Bootstrap HTML Template’)<!-- Write HTML code here --><!DOCTYPE html><html lang="en"><head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script></head><body> <div class="container"> <h2 class="text-center"><u>20 - Startups Table</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>R&D Spend</th> <th>Administration</th> <th>Marketing Spend</th> <th>State</th> <th>Profit</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% for i in d %} <tr> <td>{{i.RD_Spend}}</td> <td>{{i.Administration}}</td> <td>{{i.Marketing_Spend}}</td> <td>{{i.State}}</td> <td>{{i.Profit}}</td> </tr> {% endfor %} {% endif %} </tbody> </table></div> </body></html>Output:
# Write Python3 code herefrom django.shortcuts import renderimport pandas as pdimport json # Create your views here.def Table(request): df = pd.read_csv("tableview/static/csv/20_Startups.csv") # parsing the DataFrame in json format. json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'d': data} return render(request, 'table.html', context)
table.html (‘Bootstrap HTML Template’)
<!-- Write HTML code here --><!DOCTYPE html><html lang="en"><head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script></head><body> <div class="container"> <h2 class="text-center"><u>20 - Startups Table</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>R&D Spend</th> <th>Administration</th> <th>Marketing Spend</th> <th>State</th> <th>Profit</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% for i in d %} <tr> <td>{{i.RD_Spend}}</td> <td>{{i.Administration}}</td> <td>{{i.Marketing_Spend}}</td> <td>{{i.State}}</td> <td>{{i.Profit}}</td> </tr> {% endfor %} {% endif %} </tbody> </table></div> </body></html>
Output:
Python Django
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 384,
"s": 52,
"text": "In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for ... |
Graph representations using set and hash | 30 Jun, 2022
We have introduced Graph implementation using array of vectors in Graph implementation using STL for competitive programming | Set 1. In this post, a different implementation is used which can be used to implement graphs using sets. The implementation is for adjacency list representation of graph.
A set is different from a vector in two ways: it stores elements in a sorted way, and duplicate elements are not allowed. Therefore, this approach cannot be used for graphs containing parallel edges. Since sets are internally implemented as binary search trees, an edge between two vertices can be searched in O(logV) time, where V is the number of vertices in the graph. Sets in python are unordered and not indexed. Hence, for python we will be using dictionary which will have source vertex as key and its adjacency list will be stored in a set format as value for that key.
Following is an example of an undirected and unweighted graph with 5 vertices.
Below is adjacency list representation of this graph using array of sets.
Below is the code for adjacency list representation of an undirected graph using sets:
C++
Java
Python3
Javascript
// A C++ program to demonstrate adjacency list// representation of graphs using sets#include <bits/stdc++.h>using namespace std; struct Graph { int V; set<int, greater<int> >* adjList;}; // A utility function that creates a graph of V verticesGraph* createGraph(int V){ Graph* graph = new Graph; graph->V = V; // Create an array of sets representing // adjacency lists. Size of the array will be V graph->adjList = new set<int, greater<int> >[V]; return graph;} // Adds an edge to an undirected graphvoid addEdge(Graph* graph, int src, int dest){ // Add an edge from src to dest. A new // element is inserted to the adjacent // list of src. graph->adjList[src].insert(dest); // Since graph is undirected, add an edge // from dest to src also graph->adjList[dest].insert(src);} // A utility function to print the adjacency// list representation of graphvoid printGraph(Graph* graph){ for (int i = 0; i < graph->V; ++i) { set<int, greater<int> > lst = graph->adjList[i]; cout << endl << "Adjacency list of vertex " << i << endl; for (auto itr = lst.begin(); itr != lst.end(); ++itr) cout << *itr << " "; cout << endl; }} // Searches for a given edge in the graphvoid searchEdge(Graph* graph, int src, int dest){ auto itr = graph->adjList[src].find(dest); if (itr == graph->adjList[src].end()) cout << endl << "Edge from " << src << " to " << dest << " not found." << endl; else cout << endl << "Edge from " << src << " to " << dest << " found." << endl;} // Driver codeint main(){ // Create the graph given in the above figure int V = 5; struct Graph* graph = createGraph(V); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); // Print the adjacency list representation of // the above graph printGraph(graph); // Search the given edge in the graph searchEdge(graph, 2, 1); searchEdge(graph, 0, 3); return 0;}
// A Java program to demonstrate adjacency// list using HashMap and TreeSet// representation of graphs using setsimport java.util.*; class Graph{ // TreeSet is used to get clear// understand of graph.HashMap<Integer, TreeSet<Integer>> graph;static int v; // Graph Constructorpublic Graph(){ graph = new HashMap<>(); for(int i = 0; i < v; i++) { graph.put(i, new TreeSet<>()); }} // Adds an edge to an undirected graphpublic void addEdge(int src, int dest){ // Add an edge from src to dest into the set graph.get(src).add(dest); // Since graph is undirected, add an edge // from dest to src into the set graph.get(dest).add(src);} // A utility function to print the graphpublic void printGraph(){ for(int i = 0; i < v; i++) { System.out.println("Adjacency list of vertex " + i); Iterator set = graph.get(i).iterator(); while (set.hasNext()) System.out.print(set.next() + " "); System.out.println(); System.out.println(); }} // Searches for a given edge in the graphpublic void searchEdge(int src, int dest){ Iterator set = graph.get(src).iterator(); if (graph.get(src).contains(dest)) System.out.println("Edge from " + src + " to " + dest + " found"); else System.out.println("Edge from " + src + " to " + dest + " not found"); System.out.println();} // Driver codepublic static void main(String[] args){ // Create the graph given in the above figure v = 5; Graph graph = new Graph(); graph.addEdge(0, 1); graph.addEdge(0, 4); graph.addEdge(1, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.addEdge(2, 3); graph.addEdge(3, 4); // Print the adjacency list representation of // the above graph graph.printGraph(); // Search the given edge in the graph graph.searchEdge(2, 1); graph.searchEdge(0, 3);}} // This code is contributed by rexj8
# Python3 program to represent adjacency# list using dictionaryfrom collections import defaultdict class graph(object): def __init__(self, v): self.v = v self.graph = defaultdict(set) # Adds an edge to undirected graph def addEdge(self, source, destination): # Add an edge from source to destination. # If source is not present in dict add source to dict self.graph.add(destination) # Add an dge from destination to source. # If destination is not present in dict add destination to dict self.graph[destination].add(source) # A utility function to print the adjacency # list representation of graph def print(self): for i, adjlist in sorted(self.graph.items()): print("Adjacency list of vertex ", i) for j in sorted(adjlist, reverse = True): print(j, end = " ") print('\n') # Search for a given edge in graph def searchEdge(self,source,destination): if source in self.graph: if destination in self.graph: if destination in self.graph: if source in self.graph[destination]: print("Edge from {0} to {1} found.\n".format(source, destination)) return else: print("Edge from {0} to {1} not found.\n".format(source, destination)) return else: print("Edge from {0} to {1} not found.\n".format(source, destination)) return else: print("Destination vertex {} is not present in graph.\n".format(destination)) return else: print("Source vertex {} is not present in graph.\n".format(source)) # Driver codeif __name__=="__main__": g = graph(5) g.addEdge(0, 1) g.addEdge(0, 4) g.addEdge(1, 2) g.addEdge(1, 3) g.addEdge(1, 4) g.addEdge(2, 3) g.addEdge(3, 4) # Print adjacenecy list # representation of graph g.print() # Search the given edge in a graph g.searchEdge(2, 1) g.searchEdge(0, 3) #This code is contributed by Yalavarthi Supriya
<script> // A Javascript program to demonstrate adjacency list// representation of graphs using sets class Graph { constructor() { this.V = 0; this.adjList = new Set(); }}; // A utility function that creates a graph of V verticesfunction createGraph(V){ var graph = new Graph(); graph.V = V; // Create an array of sets representing // adjacency lists. Size of the array will be V graph.adjList = Array.from(Array(V), ()=>new Set()); return graph;} // Adds an edge to an undirected graphfunction addEdge(graph, src, dest){ // Add an edge from src to dest. A new // element is inserted to the adjacent // list of src. graph.adjList[src].add(dest); // Since graph is undirected, add an edge // from dest to src also graph.adjList[dest].add(src);} // A utility function to print the adjacency// list representation of graphfunction printGraph(graph){ for (var i = 0; i < graph.V; ++i) { var lst = graph.adjList[i]; document.write( "<br>" + "Adjacency list of vertex " + i + "<br>"); for(var item of [...lst].reverse()) document.write( item + " "); document.write("<br>"); }} // Searches for a given edge in the graphfunction searchEdge(graph, src, dest){ if (!graph.adjList[src].has(dest)) document.write( "Edge from " + src + " to " + dest + " not found.<br>"); else document.write( "<br> Edge from " + src + " to " + dest + " found." + "<br><br>");} // Driver code// Create the graph given in the above figurevar V = 5;var graph = createGraph(V);addEdge(graph, 0, 1);addEdge(graph, 0, 4);addEdge(graph, 1, 2);addEdge(graph, 1, 3);addEdge(graph, 1, 4);addEdge(graph, 2, 3);addEdge(graph, 3, 4); // Print the adjacency list representation of// the above graphprintGraph(graph); // Search the given edge in the graphsearchEdge(graph, 2, 1);searchEdge(graph, 0, 3); // This code is contributed by rutvik_56.</script>
Adjacency list of vertex 0
4 1
Adjacency list of vertex 1
4 3 2 0
Adjacency list of vertex 2
3 1
Adjacency list of vertex 3
4 2 1
Adjacency list of vertex 4
3 1 0
Edge from 2 to 1 found.
Edge from 0 to 3 not found.
Pros: Queries like whether there is an edge from vertex u to vertex v can be done in O(log V).Cons:
Adding an edge takes O(log V), as opposed to O(1) in vector implementation.
Graphs containing parallel edge(s) cannot be implemented through this method.
Further Optimization of Edge Search Operation using unordered_set (or hashing): The edge search operation can be further optimized to O(1) using unordered_set which uses hashing internally.
C++
// A C++ program to demonstrate adjacency list// representation of graphs using sets#include <bits/stdc++.h>using namespace std; struct Graph { int V; unordered_set<int>* adjList;}; // A utility function that creates a graph of// V verticesGraph* createGraph(int V){ Graph* graph = new Graph; graph->V = V; // Create an array of sets representing // adjacency lists. Size of the array will be V graph->adjList = new unordered_set<int>[V]; return graph;} // Adds an edge to an undirected graphvoid addEdge(Graph* graph, int src, int dest){ // Add an edge from src to dest. A new // element is inserted to the adjacent // list of src. graph->adjList[src].insert(dest); // Since graph is undirected, add an edge // from dest to src also graph->adjList[dest].insert(src);} // A utility function to print the adjacency// list representation of graphvoid printGraph(Graph* graph){ for (int i = 0; i < graph->V; ++i) { unordered_set<int> lst = graph->adjList[i]; cout << endl << "Adjacency list of vertex " << i << endl; for (auto itr = lst.begin(); itr != lst.end(); ++itr) cout << *itr << " "; cout << endl; }} // Searches for a given edge in the graphvoid searchEdge(Graph* graph, int src, int dest){ auto itr = graph->adjList[src].find(dest); if (itr == graph->adjList[src].end()) cout << endl << "Edge from " << src << " to " << dest << " not found." << endl; else cout << endl << "Edge from " << src << " to " << dest << " found." << endl;} // Driver codeint main(){ // Create the graph given in the above figure int V = 5; struct Graph* graph = createGraph(V); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); // Print the adjacency list representation of // the above graph printGraph(graph); // Search the given edge in the graph searchEdge(graph, 2, 1); searchEdge(graph, 0, 3); return 0;}
Adjacency list of vertex 0
4 1
Adjacency list of vertex 1
4 3 0 2
Adjacency list of vertex 2
3 1
Adjacency list of vertex 3
4 1 2
Adjacency list of vertex 4
3 0 1
Edge from 2 to 1 found.
Edge from 0 to 3 not found.
Pros:
Queries like whether there is an edge from vertex u to vertex v can be done in O(1).
Adding an edge takes O(1).
Cons:
Graphs containing parallel edge(s) cannot be implemented through this method.
Edges are stored in any order.
Note : adjacency matrix representation is the most optimized for edge search, but space requirements of adjacency matrix are comparatively high for big sparse graphs. Moreover adjacency matrix has other disadvantages as well like BFS and DFS become costly as we can’t quickly get all adjacent of a node. This article is contributed by vaibhav29498. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shubhamdp2012
sailees14032000
rexj8
rutvik_56
g92ez0hprcf53bhvjokltn0cf5n4camp5gi3jvjm
om06
chandkommanaboyina
graph-basics
Graph
Hash
Hash
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 351,
"s": 52,
"text": "We have introduced Graph implementation using array of vectors in Graph implementation using STL for competitive programming | Set 1. In this post, a different implementation... |
\Bbbk - Tex Command | \Bbbk - Used to draw blackboard-bold lowercase k.
{ \Bbbk }
\Bbbk command draws draw blackboard-bold lowercase k. | [
{
"code": null,
"e": 8170,
"s": 8120,
"text": "\\Bbbk - Used to draw blackboard-bold lowercase k."
},
{
"code": null,
"e": 8180,
"s": 8170,
"text": "{ \\Bbbk }"
}
] |
C Program for Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) | 22 Dec, 2021
A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. A union-find algorithm is an algorithm that performs two useful operations on such a data structure:
Find: Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset.
Union: Join two subsets into a single subset.
In this post, we will discuss the application of Disjoint Set Data Structure. The application is to check whether a given graph contains a cycle or not.
Union-Find Algorithm can be used to check whether an undirected graph contains cycle or not. Note that we have discussed an algorithm to detect cycle. This is another method based on Union-Find. This method assumes that the graph doesn\’t contain any self-loops.We can keep track of the subsets in a 1D array, let\’s call it parent[].
Let us consider the following graph:For each edge, make subsets using both the vertices of the edge. If both the vertices are in the same subset, a cycle is found.
Initially, all slots of parent array are initialized to -1 (means there is only one item in every subset).
0 1 2
-1 -1 -1
Now process all edges one by one.
Edge 0-1: Find the subsets in which vertices 0 and 1 are. Since they are in different subsets, we take the union of them. For taking the union, either make node 0 as parent of node 1 or vice-versa.
0 1 2 <----- 1 is made parent of 0 (1 is now representative of subset {0, 1})
1 -1 -1
Edge 1-2: 1 is in subset 1 and 2 is in subset 2. So, take union.
0 1 2 <----- 2 is made parent of 1 (2 is now representative of subset {0, 1, 2})
1 2 -1
Edge 0-2: 0 is in subset 2 and 2 is also in subset 2. Hence, including this edge forms a cycle.
How subset of 0 is same as 2?0->1->2 // 1 is parent of 0 and 2 is parent of 1
C/C++
// A union-find algorithm to detect cycle in a graph#include <stdio.h>#include <stdlib.h>#include <string.h> // a structure to represent an edge in graphstruct Edge{ int src, dest;}; // a structure to represent a graphstruct Graph{ // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) ); graph->V = V; graph->E = E; graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do union of two subsets void Union(int parent[], int x, int y){ int xset = find(parent, x); int yset = find(parent, y); if(xset!=yset){ parent[xset] = yset; }} // The main function to check whether a given graph contains // cycle or notint isCycle( struct Graph* graph ){ // Allocate memory for creating V subsets int *parent = (int*) malloc( graph->V * sizeof(int) ); // Initialize all subsets as single element sets memset(parent, -1, sizeof(int) * graph->V); // Iterate through all edges of graph, find subset of both // vertices of every edge, if both subsets are same, then // there is cycle in graph. for(int i = 0; i < graph->E; ++i) { int x = find(parent, graph->edge[i].src); int y = find(parent, graph->edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver program to test above functionsint main(){ /* Let us create the following graph 0 | \ | \ 1-----2 */ int V = 3, E = 3; struct Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 1-2 graph->edge[1].src = 1; graph->edge[1].dest = 2; // add edge 0-2 graph->edge[2].src = 0; graph->edge[2].dest = 2; if (isCycle(graph)) printf( "graph contains cycle" ); else printf( "graph doesn\'t contain cycle" ); return 0;}
Please refer complete article on Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
C Program for Tower of Hanoi
Conditional wait and signal in multi-threading | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 282,
"s": 28,
"text": "A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. A union-find algorithm... |
Type Switches in GoLang | 15 Oct, 2021
A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable. A type switch is a construct that performs multiple type assertions to determine the type of variable (rather than values) and runs the first matching switch case of the specified type. It is used when we do not know what the interface{} type could be.Example 1:
C
// Golang program to illustrate the// concept of type switchespackage main import ( "fmt") // main functionfunc main() { // an interface that has // a string value var value interface{} = "GeeksforGeeks" // type switch to find // out interface{} type switch t := value.(type){ case int64: // if type is an integer fmt.Println("Type is an integer:", t) case float64: // if type is a floating point number fmt.Println("Type is a float:", t) case string: // if type is a string fmt.Println("Type is a string:", t) case nil: // if type is nil (zero-value) fmt.Println("Type is nil.") case bool: // if type is a boolean fmt.Println("Type is a bool:", t) default: // if type is other than above fmt.Println("Type is unknown!") }}
Output:
Type is a string: GeeksforGeeks
The switch can have multiple value cases for different types and is used to select a common block of code for many similar cases.Note: Golang does not needs a ‘break’ keyword at the end of each case in the switch.Example 2:
C
// Golang program to illustrate the// concept of type switch with// multiple value casespackage main import ( "fmt") // function which implements type// switch with multiple cases valuefunc find_type(value interface{}) { // type switch to find // out interface{} type switch t := value.(type) { case int, float64: // type is an int or float fmt.Println("Type is a number, either an int or a float:", t) case string, bool: // type is a string or bool fmt.Println("Type is either a string or a bool:", t) case *int, *bool: // type is either an int pointer // or a bool pointer fmt.Println("Type is a pointer to an int or a bool:", t) default: // type of the interface is unknown fmt.Println("Type unknown!") }} // main functionfunc main() { // an interface that has // a string value var v interface{} = "GeeksforGeeks" // calling the find_type method // to determine type of interface find_type(v) // re-assigning v with a // float64 value v = 34.55 find_type(v)}
Output:
Type is either a string or a bool: GeeksforGeeks
Type is a number, either an int or a float: 34.55
surinderdawra388
Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 454,
"s": 28,
"text": "A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable. A type switch... |
Count All Palindrome Sub-Strings in a String | Set 1 - GeeksforGeeks | 13 May, 2022
Given a string, the task is to count all palindrome sub string in a given string. Length of palindrome sub string is greater than or equal to 2.
Examples:
Input : str = "abaab"
Output: 3
Explanation :
All palindrome substring are :
"aba" , "aa" , "baab"
Input : str = "abbaeae"
Output: 4
Explanation :
All palindrome substring are :
"bb" , "abba" ,"aea","eae"
We have discussed a similar problem below. Find all distinct palindromic sub-strings of a given string
The above problem can be recursively defined.
Initial Values : i = 0, j = n-1;
Given string 'str'
CountPS(i, j)
// If length of string is 2 then we
// check both character are same or not
If (j == i+1)
return str[i] == str[j]
//this condition shows that in recursion if i crosses j then it will be a invalid substring or
//if i==j that means only one character is remaining and we require substring of length 2
//in both the conditions we need to return 0
Else if(i == j || i > j) return 0;
Else If str[i..j] is PALINDROME
// increment count by 1 and check for
// rest palindromic substring (i, j-1), (i+1, j)
// remove common palindrome substring (i+1, j-1)
return countPS(i+1, j) + countPS(i, j-1) + 1 -
countPS(i+1, j-1);
Else // if NOT PALINDROME
// We check for rest palindromic substrings (i, j-1)
// and (i+1, j)
// remove common palindrome substring (i+1 , j-1)
return countPS(i+1, j) + countPS(i, j-1) -
countPS(i+1 , j-1);
If we draw recursion tree of above recursive solution, we can observe overlapping Subproblems. Since the problem has overlapping sub-problems, we can solve it efficiently using Dynamic Programming. Below is a Dynamic Programming based solution.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find palindromic substrings of a string#include <bits/stdc++.h>using namespace std; // Returns total number of palindrome substring of// length greater than equal to 2int CountPS(char str[], int n){ // create empty 2-D matrix that counts all palindrome // substring. dp[i][j] stores counts of palindromic // substrings in st[i..j] int dp[n][n]; memset(dp, 0, sizeof(dp)); // P[i][j] = true if substring str[i..j] is palindrome, // else false bool P[n][n]; memset(P, false, sizeof(P)); // palindrome of single length for (int i = 0; i < n; i++) P[i][i] = true; // palindrome of length 2 for (int i = 0; i < n - 1; i++) { if (str[i] == str[i + 1]) { P[i][i + 1] = true; dp[i][i + 1] = 1; } } // Palindromes of length more than 2. This loop is // similar to Matrix Chain Multiplication. We start with // a gap of length 2 and fill the DP table in a way that // gap between starting and ending indexes increases one // by one by outer loop. for (int gap = 2; gap < n; gap++) { // Pick starting point for current gap for (int i = 0; i < n - gap; i++) { // Set ending point int j = gap + i; // If current string is palindrome if (str[i] == str[j] && P[i + 1][j - 1]) P[i][j] = true; // Add current palindrome substring ( + 1) // and rest palindrome substring (dp[i][j-1] + // dp[i+1][j]) remove common palindrome // substrings (- dp[i+1][j-1]) if (P[i][j] == true) dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1 - dp[i + 1][j - 1]; else dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } } // return total palindromic substrings return dp[0][n - 1];} // Driver codeint main(){ char str[] = "abaab"; int n = strlen(str); cout << CountPS(str, n) << endl; return 0;}
// Java program to find palindromic substrings of a string public class GFG { // Returns total number of palindrome substring of // length greater than equal to 2 static int CountPS(char str[], int n) { // create empty 2-D matrix that counts all // palindrome substring. dp[i][j] stores counts of // palindromic substrings in st[i..j] int dp[][] = new int[n][n]; // P[i][j] = true if substring str[i..j] is // palindrome, else false boolean P[][] = new boolean[n][n]; // palindrome of single length for (int i = 0; i < n; i++) P[i][i] = true; // palindrome of length 2 for (int i = 0; i < n - 1; i++) { if (str[i] == str[i + 1]) { P[i][i + 1] = true; dp[i][i + 1] = 1; } } // Palindromes of length more than 2. This loop is // similar to Matrix Chain Multiplication. We start // with a gap of length 2 and fill the DP table in a // way that gap between starting and ending indexes // increases one by one by outer loop. for (int gap = 2; gap < n; gap++) { // Pick starting point for current gap for (int i = 0; i < n - gap; i++) { // Set ending point int j = gap + i; // If current string is palindrome if (str[i] == str[j] && P[i + 1][j - 1]) P[i][j] = true; // Add current palindrome substring ( + 1) // and rest palindrome substring (dp[i][j-1] // + dp[i+1][j]) remove common palindrome // substrings (- dp[i+1][j-1]) if (P[i][j] == true) dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1 - dp[i + 1][j - 1]; else dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } } // return total palindromic substrings return dp[0][n - 1]; } // Driver code public static void main(String[] args) { String str = "abaab"; System.out.println( CountPS(str.toCharArray(), str.length())); }}
# Python3 program to find palindromic# substrings of a string # Returns total number of palindrome# substring of length greater than# equal to 2 def CountPS(str, n): # create empty 2-D matrix that counts # all palindrome substring. dp[i][j] # stores counts of palindromic # substrings in st[i..j] dp = [[0 for x in range(n)] for y in range(n)] # P[i][j] = true if substring str[i..j] # is palindrome, else false P = [[False for x in range(n)] for y in range(n)] # palindrome of single length for i in range(n): P[i][i] = True # palindrome of length 2 for i in range(n - 1): if (str[i] == str[i + 1]): P[i][i + 1] = True dp[i][i + 1] = 1 # Palindromes of length more than 2. This # loop is similar to Matrix Chain Multiplication. # We start with a gap of length 2 and fill DP # table in a way that the gap between starting and # ending indexes increase one by one by # outer loop. for gap in range(2, n): # Pick a starting point for the current gap for i in range(n - gap): # Set ending point j = gap + i # If current string is palindrome if (str[i] == str[j] and P[i + 1][j - 1]): P[i][j] = True # Add current palindrome substring ( + 1) # and rest palindrome substring (dp[i][j-1] + # dp[i+1][j]) remove common palindrome # substrings (- dp[i+1][j-1]) if (P[i][j] == True): dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] + 1 - dp[i + 1][j - 1]) else: dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]) # return total palindromic substrings return dp[0][n - 1] # Driver Codeif __name__ == "__main__": str = "abaab" n = len(str) print(CountPS(str, n)) # This code is contributed by ita_c
// C# program to find palindromic// substrings of a stringusing System; class GFG { // Returns total number of // palindrome substring of // length greater than equal to 2 public static int CountPS(char[] str, int n) { // create empty 2-D matrix that counts // all palindrome substring. dp[i][j] // stores counts of palindromic // substrings in st[i..j] int[][] dp = RectangularArrays.ReturnRectangularIntArray( n, n); // P[i][j] = true if substring str[i..j] // is palindrome, else false bool[][] P = RectangularArrays.ReturnRectangularBoolArray( n, n); // palindrome of single length for (int i = 0; i < n; i++) { P[i][i] = true; } // palindrome of length 2 for (int i = 0; i < n - 1; i++) { if (str[i] == str[i + 1]) { P[i][i + 1] = true; dp[i][i + 1] = 1; } } // Palindromes of length more then 2. // This loop is similar to Matrix Chain // Multiplication. We start with a gap // of length 2 and fill DP table in a // way that gap between starting and // ending indexes increases one by one // by outer loop. for (int gap = 2; gap < n; gap++) { // Pick starting point for current gap for (int i = 0; i < n - gap; i++) { // Set ending point int j = gap + i; // If current string is palindrome if (str[i] == str[j] && P[i + 1][j - 1]) { P[i][j] = true; } // Add current palindrome substring // ( + 1) and rest palindrome substring // (dp[i][j-1] + dp[i+1][j]) remove common // palindrome substrings (- dp[i+1][j-1]) if (P[i][j] == true) { dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1 - dp[i + 1][j - 1]; } else { dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } } } // return total palindromic substrings return dp[0][n - 1]; } public static class RectangularArrays { public static int[][] ReturnRectangularIntArray( int size1, int size2) { int[][] newArray = new int[size1][]; for (int array1 = 0; array1 < size1; array1++) { newArray[array1] = new int[size2]; } return newArray; } public static bool[][] ReturnRectangularBoolArray( int size1, int size2) { bool[][] newArray = new bool[size1][]; for (int array1 = 0; array1 < size1; array1++) { newArray[array1] = new bool[size2]; } return newArray; } } // Driver Code public static void Main(string[] args) { string str = "abaab"; Console.WriteLine( CountPS(str.ToCharArray(), str.Length)); }} // This code is contributed by Shrikant13
<?php// PHP program to find palindromic substrings// of a string // Returns total number of palindrome// substring of length greater than equal to 2function CountPS($str, $n){ // create empty 2-D matrix that counts // all palindrome substring. dp[i][j] // stores counts of palindromic // substrings in st[i..j] $dp = array(array()); for ($i = 0; $i < $n; $i++) for($j = 0; $j < $n; $j++) $dp[$i][$j] = 0; // P[i][j] = true if substring str[i..j] // is palindrome, else false $P = array(array()); for ($i = 0; $i < $n; $i++) for($j = 0; $j < $n; $j++) $P[$i][$j] = false; // palindrome of single length for ($i= 0; $i< $n; $i++) $P[$i][$i] = true; // palindrome of length 2 for ($i = 0; $i < $n - 1; $i++) { if ($str[$i] == $str[$i + 1]) { $P[$i][$i + 1] = true; $dp[$i][$i + 1] = 1; } } // Palindromes of length more then 2. This // loop is similar to Matrix Chain Multiplication. // We start with a gap of length 2 and fill DP // table in a way that gap between starting and // ending indexes increases one by one by // outer loop. for ($gap = 2; $gap < $n; $gap++) { // Pick starting point for current gap for ($i = 0; $i < $n - $gap; $i++) { // Set ending point $j = $gap + $i; // If current string is palindrome if ($str[$i] == $str[$j] && $P[$i + 1][$j - 1]) $P[$i][$j] = true; // Add current palindrome substring (+ 1) // and rest palindrome substring (dp[i][j-1] + // dp[i+1][j]) remove common palindrome // substrings (- dp[i+1][j-1]) if ($P[$i][$j] == true) $dp[$i][$j] = $dp[$i][$j - 1] + $dp[$i + 1][$j] + 1 - $dp[$i + 1][$j - 1]; else $dp[$i][$j] = $dp[$i][$j - 1] + $dp[$i + 1][$j] - $dp[$i + 1][$j - 1]; } } // return total palindromic substrings return $dp[0][$n - 1];} // Driver Code$str = "abaab";$n = strlen($str);echo CountPS($str, $n); // This code is contributed by Ryuga?>
<script> // Javascript program to find palindromic substrings of a string // Returns total number of palindrome substring of // length greater than equal to 2 function CountPS(str,n) { // create empty 2-D matrix that counts all // palindrome substring. dp[i][j] stores counts of // palindromic substrings in st[i..j] let dp=new Array(n); // P[i][j] = true if substring str[i..j] is // palindrome, else false let P=new Array(n); for(let i=0;i<n;i++) { dp[i]=new Array(n); P[i]=new Array(n); for(let j=0;j<n;j++) { dp[i][j]=0; P[i][j]=false; } } // palindrome of single length for (let i = 0; i < n; i++) P[i][i] = true; // palindrome of length 2 for (let i = 0; i < n - 1; i++) { if (str[i] == str[i + 1]) { P[i][i + 1] = true; dp[i][i + 1] = 1; } } // Palindromes of length more than 2. This loop is // similar to Matrix Chain Multiplication. We start // with a gap of length 2 and fill the DP table in a // way that gap between starting and ending indexes // increases one by one by outer loop. for (let gap = 2; gap < n; gap++) { // Pick starting point for current gap for (let i = 0; i < n - gap; i++) { // Set ending point let j = gap + i; // If current string is palindrome if (str[i] == str[j] && P[i + 1][j - 1]) P[i][j] = true; // Add current palindrome substring ( + 1) // and rest palindrome substring (dp[i][j-1] // + dp[i+1][j]) remove common palindrome // substrings (- dp[i+1][j-1]) if (P[i][j] == true) dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1 - dp[i + 1][j - 1]; else dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } } // return total palindromic substrings return dp[0][n - 1]; } // Driver code let str = "abaab"; document.write( CountPS(str.split(""), str.length)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
3
Time complexity: O(n2) Auxiliary Space: O(n2)
This approach uses Top Down DP i.e memoized version of recursion.
Recursive soln:
1. Here base condition comes out to be i>j if we hit this condition, return 1.
2. We check for each and every i and j, if the characters are equal,
if that is not the case, return 0.
3. Call the is_palindrome function again with incremented i and decremented j.
4. Check this for all values of i and j by applying 2 for loops.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; int dp[1001][1001]; // 2D matrixbool isPal(string s, int i, int j){ // Base condition if (i > j) return 1; // check if the recursive tree // for given i, j // has already been executed if (dp[i][j] != -1) return dp[i][j]; // If first and last characters of // substring are unequal if (s[i] != s[j]) return dp[i][j] = 0; // memoization return dp[i][j] = isPal(s, i + 1, j - 1);} int countSubstrings(string s){ memset(dp, -1, sizeof(dp)); int n = s.length(); int count = 0; // 2 for loops are required to check for // all the palindromes in the string. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Increment count for every palindrome if (isPal(s, i, j)) count++; } } // return total palindromic substrings return count;} // Driver codeint main(){ string s = "abbaeae"; cout << countSubstrings(s); //"bb" , "abba" ,"aea", "eae" are // the 4 palindromic substrings. // This code is contributed by Bhavneet Singh return 0;}
import java.util.*;public class Main{ static int dp[][] = new int[1001][1001]; // 2D matrix public static int isPal(String s, int i, int j) { // Base condition if (i > j) return 1; // check if the recursive tree // for given i, j // has already been executed if (dp[i][j] != -1) return dp[i][j]; // If first and last characters of // substring are unequal if (s.charAt(i) != s.charAt(j)) return dp[i][j] = 0; // memoization return dp[i][j] = isPal(s, i + 1, j - 1); } public static int countSubstrings(String s) { for (int[] row: dp) { Arrays.fill(row, -1); } int n = s.length(); int count = 0; // 2 for loops are required to check for // all the palindromes in the string. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Increment count for every palindrome if (isPal(s, i, j) != 0) count++; } } // return total palindromic substrings return count; } public static void main(String[] args) { String s = "abbaeae"; System.out.println(countSubstrings(s)); }} // This code is contributed by divyeshrabadiya07
# 2D matrixdp = [[-1 for i in range(1001)] for j in range(1001)] def isPal(s, i, j): # Base condition if (i > j): return 1 # Check if the recursive tree # for given i, j # has already been executed if (dp[i][j] != -1): return dp[i][j] # If first and last characters of # substring are unequal if (s[i] != s[j]): dp[i][j] = 0 return dp[i][j] # Memoization dp[i][j] = isPal(s, i + 1, j - 1) return dp[i][j] def countSubstrings(s): n = len(s) count = 0 # 2 for loops are required to check for # all the palindromes in the string. for i in range(n): for j in range(i + 1, n): # Increment count for every palindrome if (isPal(s, i, j)): count += 1 # Return total palindromic substrings return count # Driver codes = "abbaeae" print(countSubstrings(s)) # This code is contributed by rag2127
using System; class GFG{ // 2D matrixstatic int[,] dp = new int[1001, 1001]; static int isPal(string s, int i, int j){ // Base condition if (i > j) return 1; // Check if the recursive tree // for given i, j // has already been executed if (dp[i, j] != -1) return dp[i, j]; // If first and last characters of // substring are unequal if (s[i] != s[j]) return dp[i, j] = 0; // Memoization return dp[i, j] = isPal(s, i + 1, j - 1);} static int countSubstrings(string s){ for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i, j] = -1; } } int n = s.Length; int count = 0; // 2 for loops are required to check for // all the palindromes in the string. for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { // Increment count for every palindrome if (isPal(s, i, j) != 0) count++; } } // Return total palindromic substrings return count;} // Driver Code static void Main(){ string s = "abbaeae"; Console.WriteLine(countSubstrings(s));}} // This code is contributed by divyesh072019
<script> var dp = Array(1001).fill().map(()=>Array(1001).fill(-1)); // 2D matrix function isPal( s , i , j) { // Base condition if (i > j) return 1; // check if the recursive tree // for given i, j // has already been executed if (dp[i][j] != -1) return dp[i][j]; // If first and last characters of // substring are unequal if (s.charAt(i) != s.charAt(j)) return dp[i][j] = 0; // memoization return dp[i][j] = isPal(s, i + 1, j - 1); } function countSubstrings( s) { var n = s.length; var count = 0; // 2 for loops are required to check for // all the palindromes in the string. for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // Increment count for every palindrome if (isPal(s, i, j) != 0) count++; } } // return total palindromic substrings return count; } // Driver code var s = "abbaeae"; document.write(countSubstrings(s)); // This code is contributed by Rajput-Ji</script>
4
Count All Palindrome Sub-Strings in a String | Set 2
This article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
ukasp
ankthon
Shivam.Pradhan
Shivam_k
shubham_singh
arunnegi815
bhavneet2000
divyeshrabadiya07
divyesh072019
rag2127
avanitrachhadiya2155
anikakapoor
Rajput-Ji
simmytarika5
Amazon
Morgan Stanley
Ola Cabs
SAP Labs
Dynamic Programming
Strings
Morgan Stanley
Amazon
Ola Cabs
SAP Labs
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 26119,
"s": 26091,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 26265,
"s": 26119,
"text": "Given a string, the task is to count all palindrome sub string in a given string. Length of palindrome sub string is greater than or equal to 2. "
},
{
"co... |
Divide a number into two unequal even parts - GeeksforGeeks | 29 Dec, 2021
Given a positive integer N. The task is to decide whether the integer can be divided into two unequal positive even parts or not.
Examples:
Input: N = 8Output: YESExplanation: 8 can be divided into two different even parts i.e. 2 and 6.
Input: N = 5Output: NOExplanation: 5 can not be divided into two even parts in any way.
Input: N = 4Output: NOExplanation: 4 can be divided into two even parts, 2 and 2. Since the numbers are equal, the output is NO.
Prerequisites: Knowledge of if-else conditional statements.
Approach: The core concept of the problem lies in the following observation:
The sum of any two even numbers is always even. Conversely any even number can be expressed as sum of two even numbers.
But here is two exceptions
The number 2 is an exception here. It can only be expressed as the sum of two odd numbers (1 + 1).
The number 4 can only be expressed as the sum of equal even numbers (2 + 2).
Hence, it is possible to express N as the sum of two even numbers only if N is even and not equal to 2 or 4. If N is odd, it is impossible to divide it into two even parts. Follow the steps mentioned below:
Check if N = 2 or N = 4.If yes, then print NO.Else check if N is even (i.e. a multiple of 2)If yes, then print YES.Else, print NO.
Check if N = 2 or N = 4.
If yes, then print NO.
Else check if N is even (i.e. a multiple of 2)
If yes, then print YES.
Else, print NO.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code to implement above approach#include<iostream>using namespace std; // Function to check if N can be divided // into two unequal even partsbool evenParts(int N){ // Check if N is equal to 2 or 4 if(N == 2 || N == 4) return false; // Check if N is even if(N % 2 == 0) return true; else return false;} //Driver codeint main(){ int N = 8; // Function call bool ans = evenParts(N); if(ans) std::cout << "YES" << '\n'; else std::cout << "NO" << '\n'; return 0;}
// Java code to implement above approachimport java.util.*;public class GFG { // Function to check if N can be divided // into two unequal even parts static boolean evenParts(int N) { // Check if N is equal to 2 or 4 if(N == 2 || N == 4) return false; // Check if N is even if(N % 2 == 0) return true; else return false; } // Driver code public static void main(String args[]) { int N = 8; // Function call boolean ans = evenParts(N); if(ans) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Function to check if N can be divided# into two unequal even partsdef evenParts(N): # Check if N is equal to 2 or 4 if (N == 2 or N == 4): return False # Check if N is even if (N % 2 == 0): return True else: return False # Driver codeN = 8 # Function callans = evenParts(N)if (ans): print("YES")else: print("NO") # This code is contributed by Saurabh Jaiswal.
// C# code to implement above approachusing System;class GFG { // Function to check if N can be divided // into two unequal even parts static bool evenParts(int N) { // Check if N is equal to 2 or 4 if(N == 2 || N == 4) return false; // Check if N is even if(N % 2 == 0) return true; else return false; } // Driver code public static void Main() { int N = 8; // Function call bool ans = evenParts(N); if(ans) Console.Write("YES" + '\n'); else Console.Write("NO" + '\n'); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript code for the above approach // Function to check if N can be divided // into two unequal even parts function evenParts(N) { // Check if N is equal to 2 or 4 if (N == 2 || N == 4) return false; // Check if N is even if (N % 2 == 0) return true; else return false; } // Driver code let N = 8; // Function call let ans = evenParts(N); if (ans) document.write("YES" + '<br>') else document.write("NO" + '<br>') // This code is contributed by Potta Lokesh </script>
YES
Time Complexity: O(1)Auxiliary Space: O(1)
lokeshpotta20
samim2000
_saurabh_jaiswal
Algo-Geek 2021
Algo Geek
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find sum of factorials till N factorial (1! + 2! + 3! + ... + N!)
Maximize partitions that if sorted individually makes the whole Array sorted
Generate string after adding spaces at specific positions in a given String
Maximum count of adjacent pairs with even sum in given Circular Array
Day-Stout-Warren algorithm to balance given Binary Search Tree
Program for Fibonacci numbers
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
C++ Data Types
Coin Change | DP-7 | [
{
"code": null,
"e": 26726,
"s": 26698,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 26856,
"s": 26726,
"text": "Given a positive integer N. The task is to decide whether the integer can be divided into two unequal positive even parts or not."
},
{
"code": null,
"... |
Output of C programs | Set 33 (rand() and srand()) - GeeksforGeeks | 22 Apr, 2021
You came across how to generate random numbers and use of two C function rand() and srand() from the article rand() and srand() in C\C++.Listed below are some output related multiple choice question on random numbers.1. Return type of rand() function is: a) short b) int c) char d) float Answer:
b
Explanation : return type of rand() is integer.2. The function srand(unsigned): a) Sets the seed for rand() b) generate random number c) Is an error d) generate constant. Answer:
a
Explanation : srand() always set the seed for rand() function.3. rand() and srand() functions are used: a) To find sqrt b) For and operations c) For or operations d) To generate random numbers Answer:
d
4. The best way to generate numbers between 0 to 99? a) rand()-100 b) rand()%100 c) rand(100) d) srand(100) Answer:
b
Explanation : rand() will generate random number from 0 to RAND_MAX, it’s modulus with 100 ensures that our result must be between 0 and 99 inclusive.5. Random number between minimum and maximum can be generated by: a) minimum + (rand() % (maximum – minimum)); b) minimum + (rand() % (maximum – minimum + 1)); c) minimum * (rand() % (maximum – minimum)) d) minimum – (rand() % (maximum+minimum)); Answer:
b
Explanation : (maximum – minimum + 1) is interval size of interval from minimum to maximum, hence rand() % (maximum – minimum + 1) will give us random integer between 0 to interval size which when added to minimum gives random number between minimum and maximum.6. Which of the following snippet will effectively generate random numbers with widest range? a) rand(); b) rand(10); c) rand(time(NULL)); d) All of the mentioned Answer:
a
Explanation : rand() generate random number between the wide range of 0 to RAND_MAX.7. For the function call time(), what type of parameter is accepted? a) int b) int * c) time_t d) time_t * Answer:
d
Explanation : Parameter for time() is pointer to an object of type time_t, where the time value is stored.8. What is the output of this C code?
C
#include <stdio.h>#include <stdlib.h> int main() { printf("%d\n", rand() % 1000); return 0; }
a) Compile time error b) An integer between 0-1000 c) An integer between 0-999 including 0 and 999. d) An integer between 0-1000 including 1000 Answer:
c
Explanation : rand() generate random number and (rand() % 1000) shorten it to range [0, 999].9. In the below program every time program is run different numbers are generated. True or False?
C
#include <stdio.h>#include <stdlib.h> int main() { srand(time(NULL)); printf("%d\n", rand()); return 0; }
a) true b) false c) Depends on the platform d) Depends on the compiler Answer:
a
Explanation : srand() will always set new seed for rand() on each program run.10. What is the output of this C code?
C
#include <stdio.h>#include <stdlib.h> int main() { srand(9000); printf("%d\n", rand()); return 0; }
a) Compile time error b) An integer in the range 0 to RAND_MAX. c) A double in the range 0 to 1 d) A float in the range 0 to 1. Answer:
b
Explanation : rand() will generate integer in range [0, RAND_MAX].11. What is the output of this C code?
C
#include <stdio.h>#include <stdlib.h> int main() { srand(time(NULL)); printf("%d\n", rand()); return 0; }
a) Compile time error b) An integer in the range 0 to RAND_MAX. c) A double in the range 0 to 1 d) A float in the range 0 to 1. Answer: b Explanation : rand() will generate integer in range [0, RAND_MAX], but on running program, every time it will generate different random number because of srand(time(NULL)).12. What is the output of this C code?
C
#include <stdio.h>#include <stdlib.h> int main() { printf("%d\n", srand(9000)); return 0; }
a) Compile time error b) An integer in the range 0 to 9000 c) A float in the range 0 to 1 d) A double in the range 0 to 9000 Answer:
a
Explanation : return type of srand() id object of type time_t.13. In the below program everytime program is run different numbers are generated.
C
#include <stdio.h>#include <stdlib.h> int main() { printf("%d\n", rand()); return 0; }
a) true b) false c) Depends on the platform d) Depends on the compiler Answer:
b
Explanation : for that srand() must be used.14. Which of these is a correct way to generate numbers between 0 to 1(inclusive) randomly? a) rand() / RAND_MAX b) rand() % 2 c) rand(0, 1) d) None of the mentioned Answer:
a
Explanation : generate random numbers between [0, 1].This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
simmytarika5
C-Library
C-Output
CPP-Library
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java programs | Set 13 (Collections)
Output of Java Program | Set 3
Runtime Errors
Output of Java program | Set 28
Output of Java program | Set 5
Output of Java Programs | Set 12 | [
{
"code": null,
"e": 25573,
"s": 25545,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25870,
"s": 25573,
"text": "You came across how to generate random numbers and use of two C function rand() and srand() from the article rand() and srand() in C\\C++.Listed below are some out... |
Java AWT | Canvas Class - GeeksforGeeks | 02 Jul, 2021
Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user can draw or trap input from the user. Canvas class inherits the Component class.Constructor of the Canvas class are :
Canvas(): Creates a new blank canvas.Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics configuration.
Canvas(): Creates a new blank canvas.
Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics configuration.
Commonly used Methods in Canvas Class
Below programs illustrate the use of Canvas Class :
Program 1: To create a canvas and paint the canvas.
Java
// Java Program to create a to create// a canvas and paint the canvasimport java.awt.*;import javax.swing.*;class canvas extends JFrame { // constructor canvas() { super("canvas"); // create a empty canvas Canvas c = new Canvas() { // paint the canvas public void paint(Graphics g) { // set color to red g.setColor(Color.red); // set Font g.setFont(new Font("Bold", 1, 20)); // draw a string g.drawString("This is a canvas", 100, 100); } }; // set background c.setBackground(Color.black); add(c); setSize(400, 300); show(); } // Main Method public static void main(String args[]) { canvas c = new canvas(); }}
Output:
Program 2: To create a canvas and add mouse listener to the canvas(a circle of radius 5 will appear at the points where mouse are clicked or dragged on the canvas).
Java
// Java Program to create a// canvas and mouse listener to the// canvas ( a circle of radius 5 will appear// at the points where mouse are clicked or// dragged on the canvas)import java.awt.*;import javax.swing.*;import java.awt.event.*; class canvas extends JFrame implements MouseListener, MouseMotionListener { // create a canvas Canvas c; // constructor canvas() { super("canvas"); // create a empty canvas c = new Canvas() { public void paint(Graphics g) { } }; // set background c.setBackground(Color.black); // add mouse listener c.addMouseListener(this); c.addMouseMotionListener(this); add(c); setSize(400, 300); show(); } // mouse listener and mouse motion listener methods public void mouseClicked(MouseEvent e) { Graphics g = c.getGraphics(); g.setColor(Color.red); // get X and y position int x, y; x = e.getX(); y = e.getY(); // draw a Oval at the point // where mouse is moved g.fillOval(x, y, 5, 5); } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { Graphics g = c.getGraphics(); g.setColor(Color.red); // get X and y position int x, y; x = e.getX(); y = e.getY(); // draw a Oval at the point where mouse is moved g.fillOval(x, y, 5, 5); } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mousePressed(MouseEvent e) { } // main class public static void main(String args[]) { canvas c = new canvas(); }}
Output:
Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/Canvas.html
ManasChhabra2
sweetyty
ruhelaa48
Java-AWT
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25731,
"s": 25703,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 25937,
"s": 25731,
"text": "Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user can draw or trap input from the user. Canvas class inherits the Component cla... |
How to add filter to the background image using CSS ? - GeeksforGeeks | 15 Oct, 2020
The purpose of this article is to learn how to add filters to an image using CSS. The CSS filter property is used to set the visual effect of an element. This property is mostly used in image content.
Syntax:
filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | url();
Example:
HTML
<!DOCTYPE html><html> <head> <style> body { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png"); filter: brightness(90%); filter: grayscale(70%); } </style></head> <body> <center> <h2> GeeksForGeeks </h2> <h2> How to add a filter to a background image using CSS? </h2> </center></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <style> .darkened-image { filter: brightness(50%); background-image: url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png"); height: 94px; width: 120px; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <p> The image below is the normal image </p> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png"> <p> The image below is the darkened image: </p> <div class="darkened-image"></div></body> </html>
Output:
Supported browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
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 ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 26822,
"s": 26621,
"text": "The purpose of this article is to learn how to add filters to an image using CSS. The CSS filter property is used to set the visual effect of an element. This prop... |
Closest leaf to a given node in Binary Tree - GeeksforGeeks | 10 May, 2021
Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples:
Input: Root of below tree
And x = pointer to node 13
10
/ \
12 13
/
14
Output 1
Distance 1. Closest leaf is 14.
Input: Root of below tree
And x = pointer to node 13
10
/ \
12 13
/ \
14 15
/ \ / \
21 22 23 24
/\ /\ /\ /\
1 2 3 4 5 6 7 8
Output 2
Closest leaf is 12 through 10.
We strongly recommend you to minimize your browser and try this yourself first. The idea is to first traverse the subtree rooted with give node and find the closest leaf in this subtree. Store this distance. Now traverse tree starting from root. If given node x is in left subtree of root, then find the closest leaf in right subtree, else find the closest left in left subtree. Below is the implementation of this idea.
C++
Java
Python3
C#
Javascript
/* Find closest leaf to the given node x in a tree */#include<bits/stdc++.h>using namespace std; // A Tree nodestruct Node{ int key; struct Node* left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // This function finds closest leaf to root. This distance// is stored at *minDist.void findLeafDown(Node *root, int lev, int *minDist){ // base case if (root == NULL) return ; // If this is a leaf node, then check if it is closer // than the closest so far if (root->left == NULL && root->right == NULL) { if (lev < (*minDist)) *minDist = lev; return; } // Recur for left and right subtrees findLeafDown(root->left, lev+1, minDist); findLeafDown(root->right, lev+1, minDist);} // This function finds if there is closer leaf to x through// parent node.int findThroughParent(Node * root, Node *x, int *minDist){ // Base cases if (root == NULL) return -1; if (root == x) return 0; // Search x in left subtree of root int l = findThroughParent(root->left, x, minDist); // If left subtree has x if (l != -1) { // Find closest leaf in right subtree findLeafDown(root->right, l+2, minDist); return l+1; } // Search x in right subtree of root int r = findThroughParent(root->right, x, minDist); // If right subtree has x if (r != -1) { // Find closest leaf in left subtree findLeafDown(root->left, r+2, minDist); return r+1; } return -1;} // Returns minimum distance of a leaf from given node xint minimumDistance(Node *root, Node *x){ // Initialize result (minimum distance from a leaf) int minDist = INT_MAX; // Find closest leaf down to x findLeafDown(x, 0, &minDist); // See if there is a closer leaf through parent findThroughParent(root, x, &minDist); return minDist;} // Driver programint main (){ // Let us create Binary Tree shown in above example Node *root = newNode(1); root->left = newNode(12); root->right = newNode(13); root->right->left = newNode(14); root->right->right = newNode(15); root->right->left->left = newNode(21); root->right->left->right = newNode(22); root->right->right->left = newNode(23); root->right->right->right = newNode(24); root->right->left->left->left = newNode(1); root->right->left->left->right = newNode(2); root->right->left->right->left = newNode(3); root->right->left->right->right = newNode(4); root->right->right->left->left = newNode(5); root->right->right->left->right = newNode(6); root->right->right->right->left = newNode(7); root->right->right->right->right = newNode(8); Node *x = root->right; cout << "The closest leaf to the node with value " << x->key << " is at a distance of " << minimumDistance(root, x) << endl; return 0;}
// Java program to find closest leaf to given node x in a tree // A binary tree nodeclass Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class Distance{ int minDis = Integer.MAX_VALUE;} class BinaryTree{ Node root; // This function finds closest leaf to root. This distance // is stored at *minDist. void findLeafDown(Node root, int lev, Distance minDist) { // base case if (root == null) return; // If this is a leaf node, then check if it is closer // than the closest so far if (root.left == null && root.right == null) { if (lev < (minDist.minDis)) minDist.minDis = lev; return; } // Recur for left and right subtrees findLeafDown(root.left, lev + 1, minDist); findLeafDown(root.right, lev + 1, minDist); } // This function finds if there is closer leaf to x through // parent node. int findThroughParent(Node root, Node x, Distance minDist) { // Base cases if (root == null) return -1; if (root == x) return 0; // Search x in left subtree of root int l = findThroughParent(root.left, x, minDist); // If left subtree has x if (l != -1) { // Find closest leaf in right subtree findLeafDown(root.right, l + 2, minDist); return l + 1; } // Search x in right subtree of root int r = findThroughParent(root.right, x, minDist); // If right subtree has x if (r != -1) { // Find closest leaf in left subtree findLeafDown(root.left, r + 2, minDist); return r + 1; } return -1; } // Returns minimum distance of a leaf from given node x int minimumDistance(Node root, Node x) { // Initialize result (minimum distance from a leaf) Distance d = new Distance(); // Find closest leaf down to x findLeafDown(x, 0, d); // See if there is a closer leaf through parent findThroughParent(root, x, d); return d.minDis; } // Driver program public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Let us create Binary Tree shown in above example tree.root = new Node(1); tree.root.left = new Node(12); tree.root.right = new Node(13); tree.root.right.left = new Node(14); tree.root.right.right = new Node(15); tree.root.right.left.left = new Node(21); tree.root.right.left.right = new Node(22); tree.root.right.right.left = new Node(23); tree.root.right.right.right = new Node(24); tree.root.right.left.left.left = new Node(1); tree.root.right.left.left.right = new Node(2); tree.root.right.left.right.left = new Node(3); tree.root.right.left.right.right = new Node(4); tree.root.right.right.left.left = new Node(5); tree.root.right.right.left.right = new Node(6); tree.root.right.right.right.left = new Node(7); tree.root.right.right.right.right = new Node(8); Node x = tree.root.right; System.out.println("The closest leaf to node with value " + x.key + " is at a distance of " + tree.minimumDistance(tree.root, x)); }} // This code has been contributed by mayank_24
# Find closest leaf to the given# node x in a tree # Utility class to create a new nodeclass newNode: def __init__(self, key): self.key = key self.left = self.right = None # This function finds closest leaf to# root. This distance is stored at *minDist.def findLeafDown(root, lev, minDist): # base case if (root == None): return # If this is a leaf node, then check if # it is closer than the closest so far if (root.left == None and root.right == None): if (lev < (minDist[0])): minDist[0] = lev return # Recur for left and right subtrees findLeafDown(root.left, lev + 1, minDist) findLeafDown(root.right, lev + 1, minDist) # This function finds if there is# closer leaf to x through parent node.def findThroughParent(root, x, minDist): # Base cases if (root == None): return -1 if (root == x): return 0 # Search x in left subtree of root l = findThroughParent(root.left, x, minDist) # If left subtree has x if (l != -1): # Find closest leaf in right subtree findLeafDown(root.right, l + 2, minDist) return l + 1 # Search x in right subtree of root r = findThroughParent(root.right, x, minDist) # If right subtree has x if (r != -1): # Find closest leaf in left subtree findLeafDown(root.left, r + 2, minDist) return r + 1 return -1 # Returns minimum distance of a leaf# from given node xdef minimumDistance(root, x): # Initialize result (minimum # distance from a leaf) minDist = [999999999999] # Find closest leaf down to x findLeafDown(x, 0, minDist) # See if there is a closer leaf # through parent findThroughParent(root, x, minDist) return minDist[0] # Driver Codeif __name__ == '__main__': # Let us create Binary Tree shown # in above example root = newNode(1) root.left = newNode(12) root.right = newNode(13) root.right.left = newNode(14) root.right.right = newNode(15) root.right.left.left = newNode(21) root.right.left.right = newNode(22) root.right.right.left = newNode(23) root.right.right.right = newNode(24) root.right.left.left.left = newNode(1) root.right.left.left.right = newNode(2) root.right.left.right.left = newNode(3) root.right.left.right.right = newNode(4) root.right.right.left.left = newNode(5) root.right.right.left.right = newNode(6) root.right.right.right.left = newNode(7) root.right.right.right.right = newNode(8) x = root.right print("The closest leaf to the node with value", x.key, "is at a distance of", minimumDistance(root, x)) # This code is contributed by PranchalK
using System; // C# program to find closest leaf to given node x in a tree // A binary tree nodepublic class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} public class Distance{ public int minDis = int.MaxValue;} public class BinaryTree{ public Node root; // This function finds closest leaf to root. This distance // is stored at *minDist. public virtual void findLeafDown(Node root, int lev, Distance minDist) { // base case if (root == null) { return; } // If this is a leaf node, then check if it is closer // than the closest so far if (root.left == null && root.right == null) { if (lev < (minDist.minDis)) { minDist.minDis = lev; } return; } // Recur for left and right subtrees findLeafDown(root.left, lev + 1, minDist); findLeafDown(root.right, lev + 1, minDist); } // This function finds if there is closer leaf to x through // parent node. public virtual int findThroughParent(Node root, Node x, Distance minDist) { // Base cases if (root == null) { return -1; } if (root == x) { return 0; } // Search x in left subtree of root int l = findThroughParent(root.left, x, minDist); // If left subtree has x if (l != -1) { // Find closest leaf in right subtree findLeafDown(root.right, l + 2, minDist); return l + 1; } // Search x in right subtree of root int r = findThroughParent(root.right, x, minDist); // If right subtree has x if (r != -1) { // Find closest leaf in left subtree findLeafDown(root.left, r + 2, minDist); return r + 1; } return -1; } // Returns minimum distance of a leaf from given node x public virtual int minimumDistance(Node root, Node x) { // Initialize result (minimum distance from a leaf) Distance d = new Distance(); // Find closest leaf down to x findLeafDown(x, 0, d); // See if there is a closer leaf through parent findThroughParent(root, x, d); return d.minDis; } // Driver program public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Let us create Binary Tree shown in above example tree.root = new Node(1); tree.root.left = new Node(12); tree.root.right = new Node(13); tree.root.right.left = new Node(14); tree.root.right.right = new Node(15); tree.root.right.left.left = new Node(21); tree.root.right.left.right = new Node(22); tree.root.right.right.left = new Node(23); tree.root.right.right.right = new Node(24); tree.root.right.left.left.left = new Node(1); tree.root.right.left.left.right = new Node(2); tree.root.right.left.right.left = new Node(3); tree.root.right.left.right.right = new Node(4); tree.root.right.right.left.left = new Node(5); tree.root.right.right.left.right = new Node(6); tree.root.right.right.right.left = new Node(7); tree.root.right.right.right.right = new Node(8); Node x = tree.root.right; Console.WriteLine("The closest leaf to node with value " + x.key + " is at a distance of " + tree.minimumDistance(tree.root, x)); }} // This code is contributed by Shrikant13
<script>// javascript program to find closest leaf to given node x in a tree // A binary tree nodeclass Node { constructor(key) { this.key = key; this.left = this.right = null; }} class Distance {constructor(){ this.minDis = Number.MAX_VALUE; }} var root; // This function finds closest leaf to root. This distance // is stored at *minDist. function findLeafDown( root , lev, minDist) { // base case if (root == null) return; // If this is a leaf node, then check if it is closer // than the closest so far if (root.left == null && root.right == null) { if (lev < (minDist.minDis)) minDist.minDis = lev; return; } // Recur for left and right subtrees findLeafDown(root.left, lev + 1, minDist); findLeafDown(root.right, lev + 1, minDist); } // This function finds if there is closer leaf to x through // parent node. function findThroughParent( root, x, minDist) { // Base cases if (root == null) return -1; if (root == x) return 0; // Search x in left subtree of root var l = findThroughParent(root.left, x, minDist); // If left subtree has x if (l != -1) { // Find closest leaf in right subtree findLeafDown(root.right, l + 2, minDist); return l + 1; } // Search x in right subtree of root var r = findThroughParent(root.right, x, minDist); // If right subtree has x if (r != -1) { // Find closest leaf in left subtree findLeafDown(root.left, r + 2, minDist); return r + 1; } return -1; } // Returns minimum distance of a leaf from given node x function minimumDistance( root, x) { // Initialize result (minimum distance from a leaf) d = new Distance(); // Find closest leaf down to x findLeafDown(x, 0, d); // See if there is a closer leaf through parent findThroughParent(root, x, d); return d.minDis; } // Driver program // Let us create Binary Tree shown in above example root = new Node(1); root.left = new Node(12); root.right = new Node(13); root.right.left = new Node(14); root.right.right = new Node(15); root.right.left.left = new Node(21); root.right.left.right = new Node(22); root.right.right.left = new Node(23); root.right.right.right = new Node(24); root.right.left.left.left = new Node(1); root.right.left.left.right = new Node(2); root.right.left.right.left = new Node(3); root.right.left.right.right = new Node(4); root.right.right.left.left = new Node(5); root.right.right.left.right = new Node(6); root.right.right.right.left = new Node(7); root.right.right.right.right = new Node(8); x = root.right; document.write("The closest leaf to node with value " + x.key + " is at a distance of " + minimumDistance(root, x)); // This code contributed by umadevi9616</script>
Output:
The closest leaf to the node with value 13 is at a distance of 2
Time Complexity of this above solution is O(n) as it does at most two traversals of given Binary Tree.This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
PranchalKatiyar
umadevi9616
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Expression Tree
BFS vs DFS for Binary Tree | [
{
"code": null,
"e": 26701,
"s": 26673,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 26859,
"s": 26701,
"text": "Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples: "
},... |
Node.js assert.throws() Function - GeeksforGeeks | 06 Oct, 2021
The assert module provides a set of assertion functions for verifying invariants. The assert.throws() is used when the code throws an exception based on a specific circumstances, to catch the error object for testing and comparison.
Syntax:
assert.throws(fn[, error][, message])
Parameters:
This function accepts the following parameters as mentioned above and described below:
fn: This parameter is a function which does not throw an error.
error: This parameter is a regular expression or function. It is the specified error. It is an optional parameter.
message: This parameter holds the error message of string or error type. It is an optional parameter.
Return Value: This function returns assertion error of object type.
Installation of assert module:
npm install assert
Note: Installation is an optional step as it is a inbuilt Node.js module.
2. After installing the assert module, you can check your assert version in command prompt using the command.
npm version assert
3. After that, you can just create a folder and add a file for example, index.js as shown below.
Example 1:
index.js
// Requiring the module const assert = require('assert'); var invalidNum = function(){ throw console.log("Invalid Number")}; var someFunc = function(a){ if(a>10){ invalidNum(); } else{ console.log("Valid number"); }}; assert.throws(function(){ someFunc(5);});
Steps to run the program:
Run index.js file using below command:
node index.js
Output:
Valid number
assert.js:105
throw new AssertionError(obj);
^
AssertionError [ERR_ASSERTION]: Missing expected exception.
at Object.<anonymous> (F:\Blogs\GFG\Assert.throw\index.js:18:8)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: undefined,
operator: 'throws'
}
Example 2:
index.js
// Requiring the module const assert = require('assert'); var invalidNum = function(){ throw console.log("Invalid Number")}; var someFunc = function(a){ if(a>10){ invalidNum(); } else{ console.log("Valid number"); }}; assert.throws(function(){ someFunc(12);});
Steps to run the program:
Run index.js file using below command:
node index.js
Output:
Invalid Number
Reference: https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message
NodeJS-function
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26293,
"s": 26265,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26526,
"s": 26293,
"text": "The assert module provides a set of assertion functions for verifying invariants. The assert.throws() is used when the code throws an exception based on a specific... |
Number validation in JavaScript - GeeksforGeeks | 14 Aug, 2020
Sometimes the data entered into a text field needs to be in the right format and must be of a particular type in order to effectively use the form. For instance, Phone number, Roll number, etc are some details that are must be in digits not in alphabets.
Approach:
We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.
Below is a code in HTML and JavaScript to validate a text field if it contains digit or not.
Example:
<!DOCTYPE html><html> <head> <script> /* this function is called when we click on the submit button*/ function numberValidation() { /*get the value of the textfield using a combination of name and id*/ //form is the name of the form coded below //numbers are the name of the inputfield /*value is used to fetch the value written in that particular field*/ var n = document.form.numbers.value; /* isNan() function check whether passed variable is number or not*/ if (isNaN(n)) {/*numberText is the ID of span that print "Please enter Numeric value" if the value of inputfield is not a number*/ document.getElementById( "numberText").innerHTML = "Please enter Numeric value"; return false; } else { /*numberText is the ID of span that print "Numeric value" if the value of inputfield is a number*/ document.getElementById( "numberText").innerHTML = "Numeric value is: " + n; return true; } } </script> </head> <body> <!-- GeeksforGeeks image logo--> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png" alt="Avatar" style="width: 200px;" /> <!-- making the form with form tag than conatins inputField and a button --> <!-- onsubmit calls the numberValidation function which is created above --> <form name="form" onsubmit="return numberValidation()"> <!-- name of input type is numbers and create of id of span as numberText--> <!-- Respective output of input is printed in span field --> Number: <input type="text" name="numbers" /> <span id="numberText"></span> <br /> <input type="submit" value="submit" /> </form> </body></html>
Output:Case 1: Textfield contain alphabets
Case 2: Textfield contain alphabets and digitsCase 3: Textfield contain only digits
JavaScript-Numbers
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26125,
"s": 26097,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 26380,
"s": 26125,
"text": "Sometimes the data entered into a text field needs to be in the right format and must be of a particular type in order to effectively use the form. For instance, P... |
Line chart in Matplotlib - Python - GeeksforGeeks | 20 Oct, 2020
Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of matplotlib, is a collection of functions that helps in creating a variety of charts. Line charts are used to represent the relation between two data X and Y on a different axis. Here we will see some of the examples of a line chart in Python :
First import Matplotlib.pyplot library for plotting functions. Also, import the Numpy library as per requirement. Then define data values x and y.
Python3
# importing the required librariesimport matplotlib.pyplot as pltimport numpy as np # define data valuesx = np.array([1, 2, 3, 4]) # X-axis pointsy = x*2 # Y-axis points plt.plot(x, y) # Plot the chartplt.show() # display
Output:
Simple line plot between X and Y data
we can see in the above output image that there is no label on the x-axis and y-axis. Since labeling is necessary for understanding the chart dimensions. In the following example, we will see how to add labels, Ident in the charts
Python3
import matplotlib.pyplot as pltimport numpy as np # Define X and Y variable datax = np.array([1, 2, 3, 4])y = x*2 plt.plot(x, y)plt.xlabel("X-axis") # add X-axis labelplt.ylabel("Y-axis") # add Y-axis labelplt.title("Any suitable title") # add titleplt.show()
Output:
Simple line plot with labels and title
We can display more than one chart in the same container by using pyplot.figure() function. This will help us in comparing the different charts and also control the look and feel of charts .
Python3
import matplotlib.pyplot as pltimport numpy as np x = np.array([1, 2, 3, 4])y = x*2 plt.plot(x, y)plt.xlabel("X-axis")plt.ylabel("Y-axis")plt.title("Any suitable title")plt.show() # show first chart # The figure() function helps in creating a# new figure that can hold a new chart in it.plt.figure()x1 = [2, 4, 6, 8]y1 = [3, 5, 7, 9]plt.plot(x1, y1, '-.') # Show another chart with '-' dotted lineplt.show()
Output:
Here we will see how to add 2 plots within the same axis.
Python3
import matplotlib.pyplot as pltimport numpy as np x = np.array([1, 2, 3, 4])y = x*2 # first plot with X and Y dataplt.plot(x, y) x1 = [2, 4, 6, 8]y1 = [3, 5, 7, 9] # second plot with x1 and y1 dataplt.plot(x1, y1, '-.') plt.xlabel("X-axis data")plt.ylabel("Y-axis data")plt.title('multiple plots')plt.show()
Output:
Using the pyplot.fill_between() function we can fill in the region between two line plots in the same graph. This will help us in understanding the margin of data between two line plots based on certain conditions.
Python3
import matplotlib.pyplot as pltimport numpy as np x = np.array([1, 2, 3, 4])y = x*2 plt.plot(x, y) x1 = [2, 4, 6, 8]y1 = [3, 5, 7, 9] plt.plot(x, y1, '-.')plt.xlabel("X-axis data")plt.ylabel("Y-axis data")plt.title('multiple plots') plt.fill_between(x, y, y1, color='green', alpha=0.5)plt.show()
Output:
Fill the area between Y and Y1 data corresponding to X-axis data
Data Visualization
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 31573,
"s": 31545,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 31900,
"s": 31573,
"text": "Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of matplotlib, is a collection of functions that helps in creating a variety of char... |
LocalDate isEqual() method in Java with Examples - GeeksforGeeks | 29 Nov, 2018
The isEqual() method of LocalDate class in Java checks if this date is equal to the specified date or not.
Syntax:
public boolean isEqual(ChronoLocalDate date2)
Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null.
Return Value: The function returns true if this date is equal to the specified date.
Below programs illustrate the isEqual() method of LocalDate in Java:
Program 1:
// Program to illustrate the isEqual() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the first date LocalDate dt1 = LocalDate.parse("2018-11-27"); // Parses the second date LocalDate dt2 = LocalDate.parse("2018-11-27"); // Checks System.out.println(dt1.isEqual(dt2)); }}
true
Program 2:
// Program to illustrate the isEqual() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the first date LocalDate dt1 = LocalDate.parse("2018-11-27"); // Parses the second date LocalDate dt2 = LocalDate.parse("2015-11-27"); // Checks System.out.println(dt1.isEqual(dt2)); }}
false
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#isEqual(java.time.chrono.ChronoLocalDate)
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 25332,
"s": 25225,
"text": "The isEqual() method of LocalDate class in Java checks if this date is equal to the specified date or not."
},
{
"code": null,
"e": 25340,
"s": 253... |
Predicting Stars, Galaxies & Quasars with Random Forest Classifiers in Python | by Theodore Yoong | Towards Data Science | Recently, in my quest to search for interesting (physics-related) datasets, I chanced upon the Sloan Digital Sky Survey (SDSS) dataset on Kaggle, as well as a brilliant Kaggle kernel by Faraz Rahman which predicted the different types of astronomical objects (stars, galaxies, and quasars) using Support Vector Machines in R. However, as R brings back some horrible memories and training SVMs requires a lot of computational effort, I decided to give this classification problem a go using scikit-learn’s Random Forest Classifier.
So what exactly are stars, galaxies, and quasars? Had you asked me prior to starting this project, I would’ve not been able to answer (shame on me). Fortunately, Faraz’s notebook succinctly summarises what they are:
A GALAXY is a gravitationally bound system of stars, stellar remnants, interstellar gas, dust, and dark matter. Galaxies are categorised according to their visual morphology as elliptical, spiral, or irregular. Many galaxies are thought to have supermassive black holes at their active centers.
A STAR is a type of astronomical object consisting of a luminous spheroid of plasma held together by its own gravity. The nearest star to Earth is the Sun.
A QUASAR, also known as quasi-stellar object, is an extremely luminous active galactic nucleus (AGN). The power radiated by quasars is enormous. The most powerful quasars have luminosities exceeding 1041 watts, thousands of times greater than an ordinary large galaxy such as the Milky Way.
Professor Andrew Bunker’s page on the Short Option course on Stars and Galaxies (S26) is also a great resource.
The details of the details can be found on on the Kaggle dataset overview. A summary of the more important features are:
ra, dec — right ascension and declination respectively
u, g, r, i, z — filter bands (a.k.a. photometric system or astronomical magnitudes)
run, rerun, camcol, field — descriptors of fields (i.e. 2048 x 1489 pixels) within image
redshift — increase in wavelength due to motion of astronomical object
plate — plate number
mjd — modified Julian date of observation
fiberid — optic fiber ID
The analysis here follows that of Faraz’s. I’ll let the visualisations speak for themselves.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinedf = pd.read_csv("skyserver.csv")
Naturally, I started with df.head(), df.describe(), and df.info(). The output of df.info() is shown below:
<class 'pandas.core.frame.DataFrame'>RangeIndex: 10000 entries, 0 to 9999Data columns (total 18 columns):objid 10000 non-null float64ra 10000 non-null float64dec 10000 non-null float64u 10000 non-null float64g 10000 non-null float64r 10000 non-null float64i 10000 non-null float64z 10000 non-null float64run 10000 non-null int64rerun 10000 non-null int64camcol 10000 non-null int64field 10000 non-null int64specobjid 10000 non-null float64class 10000 non-null objectredshift 10000 non-null float64plate 10000 non-null int64mjd 10000 non-null int64fiberid 10000 non-null int64dtypes: float64(10), int64(7), object(1)memory usage: 1.4+ MB
None of the entries are NaN, as expected of a well-maintained dataset. Cleaning is not necessary.
The nunique() method returns Series objects with the number of unique entries for each column.
df.nunique().to_frame().transpose()
I then ran value_counts() on the class column.
occurrences = df['class'].value_counts().to_frame().rename(index=str, columns={'class': 'Occurrences'})occurrences
We see that majority of the entries are either galaxies or stars. Only 8.5% of the entries are classified as quasars.
Using a kernel density estimation (kde), I plotted (smooth) density distributions of the various features.
featuredf = df.drop(['class','objid'], axis=1)featurecols = list(featuredf)astrObjs = df['class'].unique()colours = ['indigo', '#FF69B4', 'cyan']plt.figure(figsize=(15,10))for i in range(len(featurecols)): plt.subplot(4, 4, i+1) for j in range(len(astrObjs)): sns.distplot(df[df['class']==astrObjs[j]][featurecols[i]], hist = False, kde = True, color = colours[j], kde_kws = {'shade': True, 'linewidth': 3}, label = astrObjs[j]) plt.legend() plt.title('Density Plot') plt.xlabel(featurecols[i]) plt.ylabel('Density')plt.tight_layout()
Filter band densities are also plotted for each class.
filterbands = pd.concat([df.iloc[:,3:8], df['class']],axis=1)plt.figure(figsize=(15,5))plt.suptitle('Density Plots')sns.set_style("ticks")for i in range(len(astrObjs)): plt.subplot(1, 3, i+1) for j in range(len(featurecols2)): sns.distplot(df[df['class']==astrObjs[i]][featurecols2[j]], hist = False, kde = True, kde_kws = {'shade': True, 'linewidth': 3}, label = featurecols2[j]) plt.legend() plt.xlabel(astrObjs[i]) plt.ylabel('Density')plt.tight_layout()
For completeness, I include a 3D plot, identical to that of the original notebook. The original intention seems to be determining if a linear kernel for the SVM works (correct me if I’m wrong please). There was a lot of clustering at the bottom, and I took the log of the redshift (ignoring the errors) to make the visualisation clearer.
from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(5,5))ax = Axes3D(fig)for obj in astrObjs: luminous = df[df['class'] == obj] ax.scatter(luminous['ra'], luminous['dec'], np.log10(luminous['redshift']))ax.set_xlabel('ra')ax.set_ylabel('dec')ax.set_zlabel('log redshift')ax.view_init(elev = 0, azim=45)plt.show()
The traditional train-test split can be done by:
from sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierx_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=123, stratify=labels)clf = RandomForestClassifier()
When I initially attempted to train my data with sklearn.svm.linearSVC, my laptop started to overheat pretty badly. Training time complexity is generally between O(mn2) and O(mn3), where m is the number of features and n is the number of observations, as explained by Jessica Mick here. On the other hand, the training complexity of growing CART (Classification and Regression Trees) is O(mn logn) and O(mn2), as explained here (a random forest is an ensemble of CARTs). With limited time, patience, and coffee on hand, I decided to make the swap to a random forest model.
In hindsight, one thing I could’ve done to speed up the SVM (and even the random forest) was to scale my data to [-1,1], as mentioned by Shelby Matlock in the same thread. I would also get more stable prediction results that way.
from sklearn.preprocessing import MinMaxScalerscaling = MinMaxScaler(feature_range=(-1,1)).fit(x_train)x_train_scaled = scaling.transform(x_train)x_test_scaled = scaling.transform(x_test)
For hyperparameter tuning, I found this and this rather handy. We begin by instantiating a random forest and looking at the default values of the available hyperparameters. Pretty-printing the get_params() method:
from pprint import pprintpprint(clf.get_params())
This gave:
{'bootstrap': True, 'class_weight': None, 'criterion': 'gini', 'max_depth': None, 'max_features': 'auto', 'max_leaf_nodes': None, 'min_impurity_decrease': 0.0, 'min_impurity_split': None, 'min_samples_leaf': 1, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'n_estimators': 10, 'n_jobs': None, 'oob_score': False, 'random_state': None, 'verbose': 0, 'warm_start': False}
The hyperparameters which I decided to focus on are:
n_estimators (number of trees in the forest)
max_features (max. no. of features used in node splitting, usu. < no. of features in dataset)
max_depth (max. no. of levels in each decision tree)
min_samples_split (min. no. of data points in a node before node is split)
min_samples_leaf (min. no. of data points allowed in node)
criterion (metric used to determine stopping criteria for the decision trees)
To narrow down my search, I first ran a Randomised Search Cross-Validation. Here, I performed a random search of parameters using k = 10 fold cross-validation (cv=10), across 100 different combinations (n_iter=100), and with all available cores concurrently (n_jobs=-1). Random search selects a combination of features at random instead of iterating across every possible combination. A higher n_iter and cv results in more combinations and less possibility of overfitting respectively.
from sklearn.model_selection import RandomizedSearchCVhyperparameters = {'max_features':[None, 'auto', 'sqrt', 'log2'], 'max_depth':[None, 1, 5, 10, 15, 20], 'min_samples_leaf': [1, 2, 4], 'min_samples_split': [2, 5, 10], 'n_estimators': [int(x) for x in np.linspace(start = 10, stop = 100, num = 10)], 'criterion': ['gini', 'entropy']}rf_random = RandomizedSearchCV(clf, hyperparameters, n_iter = 100, cv = 10, verbose=2, random_state=123, n_jobs = -1)rf_random.fit(x_train, y_train)
A huge bunch of stuff comes up. To obtain the best parameters, I called:
rf_random.best_params_
This gave:
{'n_estimators': 100, 'min_samples_split': 5, 'min_samples_leaf': 2, 'max_features': None, 'max_depth': 15, 'criterion': 'entropy'}
I could now specify a narrower range of hyperparameters to concentrate on. GridSearchCV is perfect for the fine-tuning of the hyperparameters.
from sklearn.model_selection import GridSearchCVhyperparameters = {'max_features':[None], 'max_depth':[14, 15, 16], 'min_samples_leaf': [1, 2, 3], 'min_samples_split': [4, 5, 6], 'n_estimators': [90, 100, 110], 'criterion': ['entropy']}rf_grid = GridSearchCV(clf, hyperparameters, cv = 10, n_jobs = -1, verbose = 2)rf_grid.fit(x_train, y_train)
This took me roughly 50 minutes. I called:
rf_grid.best_params_
This returned:
{'criterion': 'entropy', 'max_depth': 14, 'max_features': None, 'min_samples_leaf': 2, 'min_samples_split': 5, 'n_estimators': 100}
I finally updated the classifier with the optimal hyperparameters.
clf.set_params(criterion = 'entropy', max_features = None, max_depth = 14, min_samples_leaf = 2, min_samples_split = 5, n_estimators = 100)
I then tested the updated classifier on the test set, and evaluated it against a couple of metrics.
Note that accuracy_score refers to the fraction of correction predictions, and f1_score is the weighted average of precision (the ability of the classifier not to label as positive a sample that is negative) and recall (the ability of the classifier to find all the positive samples). The scikit-learn documentation explains these concepts best:
sklearn.metrics has these readily available. The order of the scores in the f1_score list corresponds to the way the classes were encoded, which can be accessed by using the .classes_ attribute of the classifier.
from sklearn.metrics import accuracy_score, f1_scoresortedlabels = clf.classes_accscore = accuracy_score(y_test, y_pred)f1score = f1_score(y_test, y_pred, average = None)print(accscore)for i in range: print((sortedlabels[i],f1score[i]), end=" ")
This returns very pleasing scores.
0.99('GALAXY', 0.9900265957446809) ('QSO', 0.9596774193548387) ('STAR', 0.9959935897435898)
A confusion matrix C has matrix elements C_(i,j) corresponding to the number of observations known to be in group i but predicted to be in group j. In other words, diagonal elements represent correct predictions, while off-diagonal elements represent mislabelling. We aim to have large diagonal values C_(i,i) of the confusion matrix.
We take a look at the classification report and confusion matrix.
from sklearn.metrics import classification_report, confusion_matrixcm = confusion_matrix(y_test, y_pred, sortedlabels)print(classification_report(y_test, y_pred))print(cm)
This returns:
precision recall f1-score support GALAXY 0.98 0.99 0.98 1499 QSO 0.95 0.89 0.92 255 STAR 0.99 1.00 1.00 1246 micro avg 0.98 0.98 0.98 3000 macro avg 0.97 0.96 0.97 3000weighted avg 0.98 0.98 0.98 3000[[1481 11 7] [ 29 226 0] [ 1 1 1244]]
I generally find it useful (and pretty!) to plot the confusion matrix. In the seaborn colour palette I have chosen, the darker colour implies a larger number of entries.
cm = pd.DataFrame(cm, index=sortedlabels, columns=sortedlabels)sns.set(font_scale=1.2)sns.heatmap(cm, linewidths=0.5, cmap=sns.light_palette((1, 0.2, 0.6),n_colors=10000), annot=True)plt.xlabel('Predicted')plt.ylabel('True')
If you have feedback/constructive criticism, feel free to comment it down below! | [
{
"code": null,
"e": 703,
"s": 172,
"text": "Recently, in my quest to search for interesting (physics-related) datasets, I chanced upon the Sloan Digital Sky Survey (SDSS) dataset on Kaggle, as well as a brilliant Kaggle kernel by Faraz Rahman which predicted the different types of astronomical obje... |
How to convert NaN to 0 using JavaScript ? - GeeksforGeeks | 15 Apr, 2020
NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. In this article, we will convert the NaN to 0.
Using isNaN() method: The isNan() method is used to check the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0.
Example:<script> number = NaN; if (isNaN(number)) number = 0; console.log(number);</script>
<script> number = NaN; if (isNaN(number)) number = 0; console.log(number);</script>
Output:0
0
Using || Operator: If “number” is any falsey value, it will be assigned to 0.
Example:<script> number = NaN; number = number || 0; console.log(number);</script>
<script> number = NaN; number = number || 0; console.log(number);</script>
Output:0
0
Using ternary operator: Here number is checked via ternary operator, similar to 1, if NaN it converts to 0.
Example:<script> number = NaN; number = number ? number : 0; console.log(number);</script>
<script> number = NaN; number = number ? number : 0; console.log(number);</script>
Output:0
0
Note: While executing the code on our IDE or on your browser, check console (F12) to see the result.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24954,
"s": 24926,
"text": "\n15 Apr, 2020"
},
{
"code": null,
"e": 25163,
"s": 24954,
"text": "NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. I... |
Medical X-ray ⚕️ Image Classification using Convolutional Neural Network | by Hardik Deshmukh | Towards Data Science | The web application has been deployed to streamlit share : https://share.streamlit.io/smarthardik10/xray-classifier/main/webapp.py
The DatasetInitializePreparing the Data
The Dataset
Initialize
Preparing the Data
3.1 Data Augmentation
3.2 Loading the images
4. Convolutional Neural Network
4.1 Necessary imports
4.2 CNN Architecture
4.3 Fit the model
5. Evaluate
The dataset that we are going to use for the image classification is Chest X-Ray images, which consists of 2 categories, Pneumonia and Normal. This dataset was published by Paulo Breviglieri, a revised version of Paul Mooney's most popular dataset. This updated version of the dataset has a more balanced distribution of the images in the validation set and the testing set. The data set is organised into 3 folders (train, test, val) and contains subfolders for each image category Opacity(viz. Pneumonia) & Normal.
Total number of observations (images): 5,856Training observations: 4,192 (1,082 normal cases, 3,110 lung opacity cases)Validation observations: 1,040 (267 normal cases, 773 lung opacity cases)Testing observations: 624 (234 normal cases, 390 lung opacity cases)
First, we will extract the dataset directly from Kaggle using the Kaggle API. To do this, we need to create an API token that is located in the Account section under the Kaggle API tab. Click on ‘Create a new API token’ and a json file will be downloaded.Run the following lines of codes to instal the needed libraries and upload the json file.
! pip install -q kagglefrom google.colab import filesfiles.upload()! mkdir ~/.kaggle! cp kaggle.json ~/.kaggle/! chmod 600 ~/.kaggle/kaggle.json
When prompted to ‘Choose Files,’ upload the downloaded json file. Running the next line of code is going to download the dataset. To get the dataset API command to download the dataset, click the 3 dots in the data section of the Kaggle dataset page and click the ‘Copy API command’ button and paste it with the !
! kaggle datasets download -d pcbreviglieri/pneumonia-xray-images
Since I use Google Colab to run this project, the dataset zip file is downloaded to the Sample Data Folder. Now, by running the next lines of codes, we unzip folders and files to the desired target folder using the zipfile library.
import zipfilezf = "/content/pneumonia-xray-images.zip"target_dir = "/content/dataset/cnn/pneumonia_revamped"zfile = zipfile.ZipFile(zf)zfile.extractall(target_dir)
Now that our dataset is ready, let's get rolling!
Let’s take a look at our dataset directory tree.
content└───dataset └───cnn └───pneumonia_revamped ├───test │ ├───Normal │ │ ├───image1.jpg │ │ └───image2.jpg │ └───Opacity │ ├───image1.jpg │ └───image2.jpg ├───train │ ├───Normal │ │ ├───image1.jpg │ │ └───image2.jpg │ └───Opacity │ ├───image1.jpg │ └───image2.jpg └───val ├───Normal │ ├───image1.jpg │ └───image2.jpg └───Opacity ├───image1.jpg └───image2.jpg
In this part of the code, we will define the directory path, import some needed libraries, and define some common constant parameters that we will often use in later parts of the project.
#Some Basic Importsimport matplotlib.pyplot as plt #For Visualizationimport numpy as np #For handling arraysimport pandas as pd # For handling data#Define Directories for train, test & Validation Settrain_path = '/content/dataset/cnn/pneumonia_revamped/train'test_path = '/content/dataset/cnn/pneumonia_revamped/test'valid_path = '/content/dataset/cnn/pneumonia_revamped/val'#Define some often used standard parameters#The batch refers to the number of training examples utilized in one #iterationbatch_size = 16 #The dimension of the images we are going to define is 500x500 img_height = 500img_width = 500The dimension size of 500 or more than 500 with batch size greater than 16 may result in a crash as the RAM gets completely used in such cases. A lower dimension size with greater batch size is one of the options to try.
We will increase the size of the image training dataset artificially by performing some Image Augmentation technique.
Image Augmentation expands the size of the dataset by creating a modified version of the existing training set images that helps to increase dataset variation and ultimately improve the ability of the model to predict new images.
from tensorflow.keras.preprocessing.image import ImageDataGenerator# Create Image Data Generator for Train Setimage_gen = ImageDataGenerator( rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, )# Create Image Data Generator for Test/Validation Settest_data_gen = ImageDataGenerator(rescale = 1./255)
Using the tensorflow.keras.preprocessing.image library, for the Train Set, we created an Image Data Generator that randomly applies defined parameters to the train set and for the Test & Validation set, we’re just going to rescale them to avoid manipulating the test data beforehand.
Defining some of the Image Data Generator parameters:-
rescale —Each digital image is created by a pixel with a value between 0 and 255. 0 in black, 255 in white. So rescale the scales array of the original image pixel values to be between [0,1] which makes the images contribute more equally to the overall loss. Otherwise, higher pixel range image results in greater loss and a lower learning rate should be used, lower pixel range image would require a higher learning rate.shear_range — The shape of the image is the transformation of the shear. It fixes one axis and stretches the image at a certain angle known as the angle of the shear.zoom_range — The image is enlarged by a zoom of less than 1.0. The image is more than 1.0 zoomed out of the picture.horizontal_flip —Some images are flipped horizontally at randomvertical_flip — Some images are flipped vertically at randomroataion_range — Randomly, the image is rotated by some degree in the range 0 to 180.width_shift_range — Shifts the image horizontally.height_shift_range — Shifts the image vertically.brightness_range — brightness of 0.0 corresponds to absolutely no brightness, and 1.0 corresponds to maximum brightnessfill_mode — Fills the missing value of the image to the nearest value or to the wrapped value or to the reflecting value.
rescale —Each digital image is created by a pixel with a value between 0 and 255. 0 in black, 255 in white. So rescale the scales array of the original image pixel values to be between [0,1] which makes the images contribute more equally to the overall loss. Otherwise, higher pixel range image results in greater loss and a lower learning rate should be used, lower pixel range image would require a higher learning rate.
shear_range — The shape of the image is the transformation of the shear. It fixes one axis and stretches the image at a certain angle known as the angle of the shear.
zoom_range — The image is enlarged by a zoom of less than 1.0. The image is more than 1.0 zoomed out of the picture.
horizontal_flip —Some images are flipped horizontally at random
vertical_flip — Some images are flipped vertically at random
roataion_range — Randomly, the image is rotated by some degree in the range 0 to 180.
width_shift_range — Shifts the image horizontally.
height_shift_range — Shifts the image vertically.
brightness_range — brightness of 0.0 corresponds to absolutely no brightness, and 1.0 corresponds to maximum brightness
fill_mode — Fills the missing value of the image to the nearest value or to the wrapped value or to the reflecting value.
These transformation techniques are applied randomly to the images, except for the rescale. All images have been rescaled.
The Image Data Generator has a class known as flow from directory to read the images from folders containing images. Returns the DirectoryIterator typetensorflow.python.keras.preprocessing.image.DirectoryIterator.
train = image_gen.flow_from_directory( train_path, target_size=(img_height, img_width), color_mode='grayscale', class_mode='binary', batch_size=batch_size )test = test_data_gen.flow_from_directory( test_path, target_size=(img_height, img_width), color_mode='grayscale', shuffle=False, #setting shuffle as False just so we can later compare it with predicted values without having indexing problem class_mode='binary', batch_size=batch_size )valid = test_data_gen.flow_from_directory( valid_path, target_size=(img_height, img_width), color_mode='grayscale', class_mode='binary', batch_size=batch_size )
Found 4192 images belonging to 2 classes. Found 624 images belonging to 2 classes. Found 1040 images belonging to 2 classes.
Some of the parameters it takes in are defined below :-
directory — The first parameter used is the path of the train, test & validation folder that we defined earlier.target_size — The target size is the size of your input images, each image will be resized to this size. We have defined the target size earlier as 500 x 500.color_mode —If the image is either black and white or grayscale set to “grayscale” or if the image has three colour channels set to “rgb.” We’re going to work with the grayscale, because it’s the X-Ray images.batch_size — Number of images to be generated by batch from the generator. We defined the batch size as 16 earlier. We choose 16 because the size of the images is too large to handle the RAM.class_mode — Set “binary” if you only have two classes to predict, if you are not set to “categorical,” if you develop an Autoencoder system, both input and output are likely to be the same image, set to “input” in this case. Here we’re going to set it to binary because we’ve only got 2 classes to predict.
directory — The first parameter used is the path of the train, test & validation folder that we defined earlier.
target_size — The target size is the size of your input images, each image will be resized to this size. We have defined the target size earlier as 500 x 500.
color_mode —If the image is either black and white or grayscale set to “grayscale” or if the image has three colour channels set to “rgb.” We’re going to work with the grayscale, because it’s the X-Ray images.
batch_size — Number of images to be generated by batch from the generator. We defined the batch size as 16 earlier. We choose 16 because the size of the images is too large to handle the RAM.
class_mode — Set “binary” if you only have two classes to predict, if you are not set to “categorical,” if you develop an Autoencoder system, both input and output are likely to be the same image, set to “input” in this case. Here we’re going to set it to binary because we’ve only got 2 classes to predict.
Let’s take a look at some of the train set images that we obtained from the Data Augmentation
plt.figure(figsize=(12, 12))for i in range(0, 10): plt.subplot(2, 5, i+1) for X_batch, Y_batch in train: image = X_batch[0] dic = {0:’NORMAL’, 1:’PNEUMONIA’} plt.title(dic.get(Y_batch[0])) plt.axis(’off’) plt.imshow(np.squeeze(image),cmap=’gray’,interpolation=’nearest’) breakplt.tight_layout()plt.show()
Well, I can’t tell just by looking at these pictures which one is a case of pneumonia and which one is a normal case. For that, I would need a bachelor’s degree in radiology that takes from two to four years and costs Rs 46.6 Lakhs for the first year only. Well, do not worry, you can teach a computer to tell the difference between them as a data science practitioner. We can hopefully achieve great accuracy in it or else the degree of radiologist it is.
Tell me what is CNN in one sentence — It an artificial neural network that has the ability to pin point or detect patterns in the images.
Explain what’s going on inside a CNN architecture — CNN CNN architecture is based on layers of convolution. The convolution layers receive input and transform the data from the image and pass it as input to the next layer. The transformation is known as the operation of convolution. We need to define the number of filters for each convolution layer. These filters detect patterns such as edges, shapes, curves, objects, textures, or even colors. The more sophisticated patterns or objects it detects are more deeply layered. In essence, filters are image kernels that we can define as 3x3 or 4x4, which is a small matrix applied to an image as a whole. We will use Pooling layer together with Convolution layer as well as the goal is to down-sample an input representation (image), decrease its dimensionality by retaining the maximum value (activated features) in the sub regions binding. The number of pixels moving across the input matrix is called Stride. When the stride is 1 we move the filter to 1 pixel at a time. When the stride is 2 then we move the filter to 2 pixels at a time, and so on. Larger filter sizes and strides may be used to reduce the size of a large image to a moderate size.
Okay, if you hate math, all these complex mathematical operations are performed behind the scenes, all we need to do is define hyper parameters and layers. You can refer to the links in the reference section if you love math and want to see how these mathemagicical operations work.
There is great video on YT in which they try to create human neural network.
Lock and load as we start creating the CNN architecture.
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense,Conv2D,Flatten,MaxPooling2Dfrom tensorflow.keras.callbacks import EarlyStopping,ReduceLROnPlateau
Things to note before starting to build a CNN model:-
Always begin with a lower filter value such as 32 and begin to increase it layer wise.Construct the model with a layer of Conv2D followed by a layer of MaxPooling.The kernel_size is preferred to be odd number like 3x3.Tanh, relu, etc. can be used for activation function, but relu is the most preferred activation function.input_shape takes in image width & height with last dimension as color channel.Flattening the input after CNN layers and adding ANN layers.Use activation function as softmax for the last layer If the problem is more than 2 classes, define units as the total number of classes and use sigmoid for binary classification and set unit to 1.
Always begin with a lower filter value such as 32 and begin to increase it layer wise.
Construct the model with a layer of Conv2D followed by a layer of MaxPooling.
The kernel_size is preferred to be odd number like 3x3.
Tanh, relu, etc. can be used for activation function, but relu is the most preferred activation function.
input_shape takes in image width & height with last dimension as color channel.
Flattening the input after CNN layers and adding ANN layers.
Use activation function as softmax for the last layer If the problem is more than 2 classes, define units as the total number of classes and use sigmoid for binary classification and set unit to 1.
Note :- You can always experiment with these hyperparameters as there is no fixed value on which we can settle.
cnn = Sequential()cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(img_width, img_height, 1)))cnn.add(MaxPooling2D(pool_size = (2, 2)))cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(img_width, img_height, 1)))cnn.add(MaxPooling2D(pool_size = (2, 2)))cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(img_width, img_height, 1)))cnn.add(MaxPooling2D(pool_size = (2, 2)))cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(img_width, img_height, 1)))cnn.add(MaxPooling2D(pool_size = (2, 2)))cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(img_width, img_height, 1)))cnn.add(MaxPooling2D(pool_size = (2, 2)))cnn.add(Flatten())cnn.add(Dense(activation = 'relu', units = 128))cnn.add(Dense(activation = 'relu', units = 64))cnn.add(Dense(activation = 'sigmoid', units = 1))cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
Now we’ve developed the CNN model, let’s see in depth what’s going on here.
cnn.summary()Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_3 (Conv2D) (None, 498, 498, 32) 320 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 249, 249, 32) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 247, 247, 32) 9248 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 123, 123, 32) 0 _________________________________________________________________ conv2d_5 (Conv2D) (None, 121, 121, 32) 9248 _________________________________________________________________ max_pooling2d_5 (MaxPooling2 (None, 60, 60, 32) 0 _________________________________________________________________ conv2d_6 (Conv2D) (None, 58, 58, 64) 18496 _________________________________________________________________ max_pooling2d_6 (MaxPooling2 (None, 29, 29, 64) 0 _________________________________________________________________ conv2d_7 (Conv2D) (None, 27, 27, 64) 36928 _________________________________________________________________ max_pooling2d_7 (MaxPooling2 (None, 13, 13, 64) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 10816) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 1384576 _________________________________________________________________ dense_3 (Dense) (None, 64) 8256 _________________________________________________________________ dense_4 (Dense) (None, 1) 65 ================================================================= Total params: 1,467,137 Trainable params: 1,467,137 Non-trainable params: 0 _________________________________________________________________
# Hyperparameters of Conv2DConv2D( filters, kernel_size, strides=(1, 1), padding="valid", activation=None, input_shape=(height,width,color channel) )# Hyperparameters of MaxPooling2D MaxPooling2D( pool_size=(2, 2), strides=None, padding="valid" )
The input shape of the images are (500,500,1) as we defined the height & width earlier. And the 1 represents the color channel as the images are grayscale the color channel for it is 1 and for rgb images it is 3.
(none,500,500,1) Over here Keras adds an extra dimension none since batch size can vary.
In First Conv2d layer Convolution operation on image of (500,500) with a (3,3) kernel size with strides and dilation set 1 by default and padding set to ‘valid’, it spits out output size of (500-3+1 , 500-3+1 ) = (498,498) And the number of filters we defined is 32, the output shape is now(None,498,498,32)
Now in the first Max Pooling layer, we have defined the kernel size as (2,2) and strides are by default (2,2) applying that to input of image size of (498,498) we get ((498–2//2)+1,(498–2//2)+1))= (249,249)
The Flatten layer takes all of the pixels along all channels and creates a 1D vector without considering batchsize. The input of (13, 13, 64) is therefore flattened to (13*13*64) = 10816 values.
The parameter value is calculated by (kernel_height * kernel_width * input_channels * output_channels) + (output_channels) which gives (3*3*1*32)+(32) = 320 in first layer.
The rectified linear activation function or short-term ReLU is a piecewise linear function that outputs the input directly if it is positive, otherwise it outputs zero. The rectified linear activation function overcomes the problem of vanishing gradients, allowing models to learn faster and perform better.
Padding — "SAME": output size is the same as input size. This requires the filter window to slip outside input map, hence the need to pad."VALID": Filter window stays at valid position inside input map, so output size shrinks by filter_size - 1. No padding occurs.
Activation function — Simply put, activation is a function that is added to an artificial neural network to help the network learn complex patterns in the data. When comparing with a neuron-based model in our brains, the activation function is at the end of the day to decide what to do with the next neuron. Since the classification is between 2 classes we are going to use sigmoid activation function for last layer which returns value in the range of 0 to 1. For more than 2 classes we can use softmax activation function.
Learning Rate — while training the aim for stochastic gradient descent is to minimize loss among actual and predicted values of training set. Path to minimize loss takes several steps. Adam is an adaptive learning rate method, which means, it computes individual learning rates for different parameters.
loss function — Since it is a binary classification, we will use binary crossentropy during training for evaluation of losses. We would have gone for categorical crossentropy if there were more than 4 classes.
metrics — accuracy — Calculate how often actual labels are equal to predictions. It will measure the loss and accuracy of training and validation.
Visualize CNN model
from tensorflow.keras.utils import plot_modelplot_model(cnn,show_shapes=True, show_layer_names=True, rankdir='TB', expand_nested=True)
Defining Callback list
EarlyStopping is called to stop the epochs based on some metric(monitor) and conditions (mode, patience) . It helps to avoid overfitting the model. Over here we are telling to stop based on val_loss metric, we need it to be minimum. patience says that after a minimum val_loss is achieved then after that in next iterations if the val_loss increases in any the 3 iterations then the the training will stop at that epoch.
Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2–10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced. source
early = EarlyStopping(monitor=”val_loss”, mode=”min”, patience=3)learning_rate_reduction = ReduceLROnPlateau(monitor=’val_loss’, patience = 2, verbose=1,factor=0.3, min_lr=0.000001)callbacks_list = [ early, learning_rate_reduction]
Assigning Class Weights
It is good practice to assign class weights for each class. It emphasizes the weight of the minority class in order for the model to learn from all classes equally.
from sklearn.utils.class_weight import compute_class_weightweights = compute_class_weight('balanced', np.unique(train.classes), train.classes)cw = dict(zip( np.unique(train.classes), weights))print(cw)
{0: 1.9371534195933457, 1: 0.6739549839228296}
The parameters we are passing to model.fit are train set, epochs as 25, validation set used to calculate val_loss and val_accuracy, class weights and callback list.
cnn.fit(train,epochs=25, validation_data=valid, class_weight=cw, callbacks=callbacks_list)
Looks like the EarlyStopping stopped at 10th epoch at val_loss =14.9% and val_accuracy = 94.6%.
Let’s visualize the progress of all metrics throughout the total epochs lifetime
pd.DataFrame(cnn.history.history).plot()
The accuracy we are getting on Test dataset is of 91%
test_accu = cnn.evaluate(test)print('The testing accuracy is :',test_accu[1]*100, '%')
39/39 [==============================] — 50s 1s/step — loss: 0.3132 — accuracy: 0.9119 The testing accuracy is : 91.18589758872986 %
Let’s predict the test dataset and look at some of the performance measurement metrics in detail to evaluate our model.
preds = cnn.predict(test,verbose=1)
39/39 [==============================] — 46s 1s/step
Since the activation function of the last layer is sigmoid, the model gives prediction in the 0 to 1 range and not an exact classification as 0 or 1. So we categorise all the values in the 0.5 to 1 range as 0 and less than 0.5 as 1. Note(0 denotes a normal case and 1 denotes a case of pneumonia)
predictions = preds.copy()predictions[predictions <= 0.5] = 0predictions[predictions > 0.5] = 1
Confusion Matrix
Let’s interpret the output of the confusion matrix. The upper left (TP) denotes the number of images correctly predicted as normal cases and the bottom right (TN) denotes the correctly predicted number of images as cases of pneumonia. As Pneumonia case, the upper right denotes the number of incorrectly predicted images but were actually normal cases and the lower left denotes the number of incorrectly predicted Normal case images but were actually Pneumonia case.
?? Still Confused with Confusion matrix ??
The easy way to interpret the confusion matrix for binary or multiclass classification is to see if we get maximum values in diagonal cells from left to right and minimum value in the rest of the cells.
from sklearn.metrics import classification_report,confusion_matrixcm = pd.DataFrame(data=confusion_matrix(test.classes, predictions, labels=[0, 1]),index=["Actual Normal", "Actual Pneumonia"],columns=["Predicted Normal", "Predicted Pneumonia"])import seaborn as snssns.heatmap(cm,annot=True,fmt="d")
Classification Report
Precision = TruePositives / (TruePositives + FalsePositives)
Recall = TruePositives / (TruePositives + FalseNegatives)
F1 = (2 * Precision * Recall) / (Precision + Recall)
print(classification_report(y_true=test.classes,y_pred=predictions,target_names =['NORMAL','PNEUMONIA']))
Let’s visualize some of the predicted images with percentage %
test.reset()x=np.concatenate([test.next()[0] for i in range(test.__len__())])y=np.concatenate([test.next()[1] for i in range(test.__len__())])print(x.shape)print(y.shape)#this little code above extracts the images from test Data iterator without shuffling the sequence# x contains image array and y has labels dic = {0:'NORMAL', 1:'PNEUMONIA'}plt.figure(figsize=(20,20))for i in range(0+228, 9+228): plt.subplot(3, 3, (i-228)+1) if preds[i, 0] >= 0.5: out = ('{:.2%} probability of being Pneumonia case'.format(preds[i][0])) else: out = ('{:.2%} probability of being Normal case'.format(1-preds[i][0]))plt.title(out+"\n Actual case : "+ dic.get(y[i])) plt.imshow(np.squeeze(x[i])) plt.axis('off')plt.show()
This code block gives a percentage prediction of the individual image that can be loaded directly from your drive by specifying its path.
We have to re-create all the data preprocessing steps over here after importing the image as we had done previously to feed the test set into the model to get prediction. For pre-processing we need to import tensorflow.keras.preprocessing.image class.
Import image and define dimensions as (500,500) and color channel as grayscale.Convert image to array, rescale it by dividing it 255 and expand dimension by axis = 0 as our model takes 4 dimensions as seen earlier.Finally let’s predict the case!
Import image and define dimensions as (500,500) and color channel as grayscale.
Convert image to array, rescale it by dividing it 255 and expand dimension by axis = 0 as our model takes 4 dimensions as seen earlier.
Finally let’s predict the case!
Let’s do some field testing on our model with my X-ray
# Testing with my own Chest X-Rayhardik_path = '/content/drive/My Drive/unsegregated /IMG_20201023_204205928~2.jpg'from tensorflow.keras.preprocessing import imagehardik_img = image.load_img(hardik_path, target_size=(500, 500),color_mode='grayscale')# Preprocessing the imagepp_hardik_img = image.img_to_array(hardik_img)pp_hardik_img = pp_hardik_img/255pp_hardik_img = np.expand_dims(pp_hardik_img, axis=0)#predicthardik_preds= cnn.predict(pp_hardik_img)#printplt.figure(figsize=(6,6))plt.axis('off')if hardik_preds>= 0.5: out = ('I am {:.2%} percent confirmed that this is a Pneumonia case'.format(hardik_preds[0][0])) else: out = ('I am {:.2%} percent confirmed that this is a Normal case'.format(1-hardik_preds[0][0]))plt.title("Hardik's Chest X-Ray\n"+out) plt.imshow(np.squeeze(pp_hardik_img))plt.show()
Phew. Everything seems to be normal with my Chest X-Ray. Now it’s your turn to diagnose your chest X-Ray.
Thank you for sticking with me on this long journey we’ve just saved ₹ 46.6 Lakhs x 4 years of radiologist ‘s degree and now we’re able to classify X-Rays.
Link to my Colab Notebook for this project : colab.research.google.com
My LinkedIn Profile : https://www.linkedin.com/in/hardik-deshmukh/
My Other Medium Articles : https://medium.com/@smarthardik10
My GitHub : https://github.com/smarthardik10
App deployed on streamlit : | [
{
"code": null,
"e": 302,
"s": 171,
"text": "The web application has been deployed to streamlit share : https://share.streamlit.io/smarthardik10/xray-classifier/main/webapp.py"
},
{
"code": null,
"e": 342,
"s": 302,
"text": "The DatasetInitializePreparing the Data"
},
{
"... |
Const member functions in C++ | The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided.
A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
Here is the syntax of const member function in C++ language,
datatype function_name const();
Here is an example of const member function in C++,
Live Demo
#include<iostream>
using namespace std;
class Demo {
int val;
public:
Demo(int x = 0) {
val = x;
}
int getValue() const {
return val;
}
};
int main() {
const Demo d(28);
Demo d1(8);
cout << "The value using object d : " << d.getValue();
cout << "\nThe value using object d1 : " << d1.getValue();
return 0;
}
The value using object d : 28
The value using object d1 : 8 | [
{
"code": null,
"e": 1300,
"s": 1062,
"text": "The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided."
},
{
"... |
1's complement notation | This is one of the methods of representing signed integers in the computer. In this method, the most significant digit (MSD) takes on extra meaning.
If the MSD is a 0, we can evaluate the number just as we would interpret any normal unsigned integer.
If the MSD is a 1, this indicates that the number is negative.
The other bits indicate the magnitude (absolute value) of the number.
If the number is negative, then the other bits signify the 1's complement of the magnitude of the number.
Some signed decimal numbers and their equivalent in 1's complement notations are shown below, assuming a word size of 4 bits.
From the above table, it is obvious that if the word size is n bits, the range of numbers that can be represented is from -(2n-1- 1) to+(2n-1 -1). A table of word size and the range of 1's complement numbers that can be represented is shown.
Add the numbers (+5) and (-3) using a computer. The numbers are assumed to be represented using 4-bit 1's complement notation.
1110 <- carry generated during addition 0101 <- (+5) First Number + 1100 <-(-3) Second Number 0001 <- (+1) Sum
1110 <- carry generated during addition
0101 <- (+5) First Number
+ 1100 <-(-3) Second Number
0001 <- (+1) Sum
The computer instead of giving the correct answer of +2 = 0010, has given the wrong answer of +1 = 0001! However, to get the correct answer the computer will have to simply add to the result the final carry that is generated, as shown in the following.
0001 + 1 0010 = (+2) Result
0001
+ 1
0010 = (+2) Result
Add the numbers (-4) and (+2) using a computer. The numbers are assumed to be represented using 4-bit 1's complement notation.
0010 <- carry generated during addition 1011 <- (-4) First Number + 0010 <-(+2) Second Number 1101 <- (-2) Sum
0010 <- carry generated during addition
1011 <- (-4) First Number
+ 0010 <-(+2) Second Number
1101 <- (-2) Sum
After the addition of the final array, the result remains as 1101. This is -2, which is the correct answer. In 1 101 the MSB is a 1. It means the number is negative. Then, the remaining bits do not provide the magnitude directly. To solve this problem, just consider 1's complement of 1 101. 1'scomplement of 1 101 is 0 010, which is +2. Thus, 1 101, which is 1'scomplement of 0 010 is −2.
1's complement notation is not very simple to understand because it is very much different from the conventional way of representing signed numbers.
1's complement notation is not very simple to understand because it is very much different from the conventional way of representing signed numbers.
The other disadvantage is that there are two notations for 0 (0000 and 1111), which is very inconvenient when the computer wants to test for a 0 result.
The other disadvantage is that there are two notations for 0 (0000 and 1111), which is very inconvenient when the computer wants to test for a 0 result.
It is quite convenient for the computer to perform arithmetic. To get the correct answer after addition, the result of addition and final carry has to be added up.
It is quite convenient for the computer to perform arithmetic. To get the correct answer after addition, the result of addition and final carry has to be added up.
Hence, 1's complement notation is also generally not used to represent signed numbers inside a computer, so the concept of 2’s complement has come. | [
{
"code": null,
"e": 1211,
"s": 1062,
"text": "This is one of the methods of representing signed integers in the computer. In this method, the most significant digit (MSD) takes on extra meaning."
},
{
"code": null,
"e": 1313,
"s": 1211,
"text": "If the MSD is a 0, we can evaluat... |
How to generate prime twins using Python? | Twin primes are pairs of primes which differ by two. The first twin primes are {3,5}, {5,7}, {11,13} and {17,19}. You can generate prime twins in python by running a for loop and checking for primality of the numbers as you do so.
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def generate_twins(start, end):
for i in range(start, end):
j = i + 2
if(is_prime(i) and is_prime(j)):
print("{:d} and {:d}".format(i, j))
generate_twins(2, 100)
This will give the output −
3 and 5
5 and 7
11 and 13
17 and 19
29 and 31
41 and 43
59 and 61
71 and 73 | [
{
"code": null,
"e": 1294,
"s": 1062,
"text": "Twin primes are pairs of primes which differ by two. The first twin primes are {3,5}, {5,7}, {11,13} and {17,19}. You can generate prime twins in python by running a for loop and checking for primality of the numbers as you do so. "
},
{
"code":... |
Breaking Down Geocoding in R: A Complete Guide | by Oleksandr Titorchuk | Towards Data Science | If you ever wondered how to build maps similar to the ones you constantly see in your apps, it’s probably a good place to start. In this tutorial we will cover how to find a place based on its description or coordinates and how to build a simple map based on that information.
Please note that this article assumes some prior knowledge of R language: data structures, operators, conditional statements, functions etc. All the code from this tutorial can be found on GitHub.
So, let’s get started!
Geocoding is a process of converting an address or a name of a place into its coordinates. Reverse geocoding performs just an opposite task: returns an address or a description of a place based on its coordinates.
That’s all, as simple as that. So, by using geocoding you must be able to say that the Eiffel Tower in Paris, France can be found at (48.858568, 2.294513) latitude, longitude coordinates. And that by entering (41.403770, 2.174379) on your map app, you will end up at the Sagrada Familia Roman Catholic church in Barcelona, Spain. You can verify it yourself — just type in this information on Google Maps.
When it comes to free geocoding tools available online, one of the options is specialized websites. For example, mentioned above Google Maps. After a bit of search, you can find others.
All of these are perfectly fine instruments if you need to find only a few addresses. But imagine there are hundreds of them? And what about thousands? This task rapidly becomes quite a headache.
For bulk requests API is a much more suitable option. And probably the most obvious choice here is Google Maps API . To be able to use Google services, you need to create the account on the Google Cloud Platform and get your API key. Google provides a detailed instruction on how to do it on their website.
Another option is to use a public API from the OpenStreetMap called Nominatim. OpenStreetMap is a collaborative project whose aim is to create a free maps service for the public. As its website says:
OpenStreetMap is built by a community of mappers that contribute and maintain data about roads, trails, cafes, railway stations, and much more, all over the world.
Nominatim is basically a tool to power the search on the OpenStreetMap website. Unlike Google Maps, Nominatim does not require you to register any account and get an API key. But if you want to use its services in an application, you need to provide an email address, so your app’s activity can be tracked and restrained if needed — OSM servers’ capacity has its limits.
You might be wondering why I am telling you about the Nominatim API in the first place if Google offers similar capabilities. And your first guess will probably be the cost — unlike OpenStreetMap Foundation, Google is a private company, which takes charges for its services. And it is true, but only partially.
Firstly, if you register on the Google Cloud Platform now, you are getting a 12-month free trial with $300 credit on your account to learn about its features. Secondly, even after that Google offers a limited access to some of its most commonly used services for free as part of the Always Free package. And if your sole purpose is learning, the limits available under that package are more than enough. To learn more about Google Maps API Pricing, visit Google’s help page.
So, what’s the issue then you would ask me? It is Google Maps Platform Terms of Service, which among other things state that:
3.2.4 Restrictions Against Misusing the Services.(a) No Scraping. Customer will not extract, export, or otherwise scrape Google Maps Content for use outside the Services.(c) No Creating Content From Google Maps Content.(e) No Use With Non-Google Maps.
I am not a legal guy and don’t know how Google treats the use of its services for non-commercial purposes. But I haven’t seen on these Terms of Service any clause stating that above restrictions apply only to commercial use. So, please be mindful of these limitations before you decide to use Google Maps API in your app.
Unlike Google Maps, OpenStreetMap data is licensed under the Open Data Commons Open Database License (ODbL). Below is, as authors themselves put it, a human-readable summary of ODbL 1.0:
You are free:* To Share: To copy, distribute and use the database.* To Create: To produce works from the database.* To Adapt: To modify, transform and build upon the database.
As long as you:* Attribute: Give reference to the original database.* Share-Alike: Distribute a database adapted from the original one under the same license.* Keep open: Give access to the adapted database to the public.
A full-length license, in case you want to have a look, is available on the Open Data Commons website.
Having said all of that, let’s now move on to the coding!
Let’s firstly install and load all the packages which will be used in this tutorial, so not to worry about it later. The purpose of each package will be described in the corresponding part of the article. Please also note that we are using software version R 3.6.2 for Windows.
# install packagesinstall.packages("ggmap")install.packages("tmaptools")install.packages("RCurl")install.packages("jsonlite")install.packages("tidyverse")install.packages("leaflet")# load packageslibrary(ggmap)library(tmaptools)library(RCurl)library(jsonlite)library(tidyverse)library(leaflet)
The R community created a few packages, which can be used for accessing Google Maps and Nominatim APIs. Let’s have a look on them.
The first package is called ggmap and it allows you to connect to the Google Maps API. Before you can start using this package, you need to provide R with your API key.
# replace "api_key" with your API keyregister_google(key = api_key)
Let’s now use geocode function from this package on the sample of twelve London pubs to demonstrate how it works. The function accepts as its output argument either:
latlon — latitude and longitude;
latlona — all of the above plus address;
more — all of the above plus place’s type and geographical boundaries;
all — all of the above plus some additional information.
Each option corresponds to the type of information generated. Generally, we don’t need more information than more option provides.
Let’s have a look on our results. As you see we have a pub’s name, its coordinates, type of the place, precision of the result (rooftop means that Google was able to find the place down to a specific building) and its address.
Now, let’s use the coordinates we just found to reverse geocode the places they belong to.
The revgeocode function allows to do that. It requires two arguments: location — a numeric vector of longitude/latitude and output — either address or all. Option all for output returns much more information than we need, so let’s stick to the address.
This time we will store our results in a list rather than a data frame. Each element of this list will contain another list with information about the pub’s name, coordinates and address.
That’s all for the ggmap. Let’s now move on to the next package.
The tmaptools is a package that offers a set of tools for reading and processing of a spatial data. It facilitates the capabilities of another R package called tmap, which was built for visualizing thematic maps. Many of the tmaptools functions rely on the Nominatim API.
Now let’s try to get from tmaptools the same sort of information we extracted by using ggmap. I had to modify a bit some search requests because Nominatim was not able to find the place based on it. And one of the pubs — The Glory — couldn’t be located despite all my efforts. So, be aware that the quality of data and its completeness might vary among different services providers.
We included in the final table only coordinates and the full address. Here is how it looks like.
Now, it’s time for reverse geocoding. In our output we will display the very same information as in reverse geocoding request from ggmap.
So, that’s the last piece of code for our discussion of R geocoding packages. And here you can finish reading this article and practice some of the techniques described above by yourself. Unless... Unless you want to find out more! If that’s the case, let’s continue!
Using packages is a very convenient and fast way to get things done. And probably for most of the tasks you would want to do, the functionality these packages provide is more than enough. However, if you need something extra, or you are interested in other API functions, or you just want to learn how to work with API in general, you need to go to Google/Nominatim help pages and do a bit of reading. Or search online for some videos/tutorials like this offering short summaries. Or even better — do both.
Having looked at the ggmap package, let’s now try to get the place’s location, address, and as a bonus, its phone number and a website, using Google Maps API directly. To accomplish this task we need the Geocoding API and the Places API.
The Geocoding API is a service that provides the capabilities of geocoding and reverse geocoding of addresses and places. You can access the Geocoding API by sending HTTP request through your web-browser and get back response in JSON or XML format. Although, in our case we will be sending this request from R.
The Geocoding API requests take the following format.
# formathttps://maps.googleapis.com/maps/api/geocode/outputFormat?parameters# geocoding examplehttps://maps.googleapis.com/maps/api/geocode/json?address=The+Churchill+Arms,+Notting+Hill&key=YOUR_API_KEY# reverse geocoding examplehttps://maps.googleapis.com/maps/api/geocode/json?latlng=51.5069117,-0.194801&key=YOUR_API_KEY
So, the web request you send consists of several parts — the API url followed by outputFormat (json or xml) and the list of parameters. outputFormat is separated from parameters by a question mark (?) and parameters itself are separated from each other by an ampersand (&).
The requests’ required parameters include:
for geocoding: address — search query in a form of address or place’s name andkey — API key;
for reverse geocoding: latlng — latitude and longitude of the place you search and key — API key.
We will not use any optional parameters in our queries.
You can read more about how to construct the API requests here and here.
It’s worth to mention that if you are building your own application, which needs real-time access to the Google Maps services, you can check Google client-side (JavaScript) or server-side (Java, Python, Go, Node.js) API.
In case you do not want to limit yourself to the place’s address and coordinates only, you can use the Places API. For example, to find a phone number and a web address of the place we need to use the Place Search to get the Place ID and use it later to retrieve this information from the Place Details.
While doing API call, make sure to provide the list of fields you want to extract. Otherwise, Google will send all of them and charge you accordingly. In our case it doesn’t matter as we will not exceed the charge-free limits but if you plan to use API for a large volume of requests you might be charged for that.
For the Place Search/Place Details API call you also need to provide the outputFormat (json or xml) followed by the list of parameters.
For the Place Search the required parameters include: input — a name, an address or a phone number (coordinates will not work); inputtype — textquery or phonenumber; key — API key.
For the Place Details the required parameters are: place_id — can be found by using the Place Search; key — API key.
For both the Place Search and Place Details we will be using optional parameter fields — a comma-separated list of additional information we want Google to return. You can read more about possible options on the corresponding help pages provided earlier. But in our case we only need fields place_id from the Place Search and formatted_phone_number plus website from the Place Details. Please remember to read information about the billing!
The format of API calls is given below.
# PLACE SEARCH# formathttps://maps.googleapis.com/maps/api/place/findplacefromtext/outputFormat?parameters# examplehttps://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=The+Churchill+Arms,+Notting+Hill&inputtype=textquery&fields=photos,formatted_address,name,place_id&key=YOUR_API_KEY# PLACE DETAILS# formathttps://maps.googleapis.com/maps/api/place/details/outputFormat?parameters# examplehttps://maps.googleapis.com/maps/api/place/details/json?place_id=ChIJGTDVMfoPdkgROs9QO9Kgmjc&fields=formatted_phone_number,website&key=YOUR_API_KEY
And again, if you consider building an actual app, it is worth to have a look at Java/Python/Go/Node.js clients for server-side applications or Places SDK for Android, Places SDK for iOS and the Places Library, Maps JavaScript API for the client-side ones.
Having said all of that, let’s now write the code itself.
Our code consists of seven functions:
a main function;
three functions for generating API calls;
three functions to extract data from JSON output.
Our main function takes three arguments:
search_query — search request (address or place) ;
fields — information to extract (coordinates, address, contacts or all);
key — API key for Google Maps.
The first and the last of them are required, while the second one is optional with default coordinates.
These arguments can be of below types:
search_query — string, character vector, list of characters, one-dimensional matrix or data frame with string data;
fields — string, character vector, list of characters;
key — string.
Depending on the value of fields the function returns a data frame with:
coordinates — latitude and longitude;
address — full address and city;
contacts — phone number and website;
all — all of the above.
Let’s now have a look at each of the function’s components in detail.
The API call function is pretty straightforward once you get acquainted with the information I provided earlier.
It works in three steps:
1. Transforms the search query into a list.2. Percent-encodes the search query.3. Constructs the API call string.
The first step is needed because it’s always easier to deal with a common data structure (a list in our case). For percent-encoding we use URLencode function from the RCurl package. If you don’t know what it is, visit this page with detailed explanation.
Google can return data in two formats — JSON and XML. In our examples we use JSON output. This output needs to be converted into R objects, so we can easily manipulate the data it contains. Once it’s done, our task comes down to picking up from the formatted list only the elements we need.
Raw JSON output and its formatted version look like this.
So, how does our function work? Firstly, fromJSON function from the jsonlite package is used to transform JSON output into R list. After that our function checks whether the API call was successful (status = "OK"), and if yes, it extracts from the list only the elements we need to construct the final data frame. It’s a bit tricky to retrieve a city name, as firstly we need to find out under what sequence number it is stored inside the address_components. For contacts it’s also important to replace all NULL, which appear if Google has no information about the phone number or the website, with NA, so we get no error while generating the final data frame.
We have already provided the description of our main function. Let’s now just explain how it works.
Firstly, the function gets coordinates and address from the Google Maps. It checks if user actually wants this information (i.e. coordinates and/or address are present in the fields argument) and if yes, it calls url_google_geocoding function to construct the API call and getURL function from the RCurl package to actually make it.
After we receive response from Google, we need to transform it from JSON format into R list by using get_geodata_from_json_google function. And once it’s done, the result is stored in the geodata_df data frame.
Later, the very same procedure is repeated for contacts (i.e. phone number and website). And that’s all.
Here is the code.
Now, we can finally call our function and check results.
# replace "api_key" with your API keypubs_google <- geocode_google(pubs, "all", api_key)# check resultspubs_google
Below is pretty much the same function but for reverse geocoding. This time it returns only the address based on the place’s coordinates. I do not give here any detailed explanations as by this time you are well-equipped to understand the code on your own.
Apart from the key argument, the main function needs coordinates as an input, which can be either:
a vector with latitude and longitude (a single request);
a list of latitude/longitude vectors;
a matrix with two columns — latitude and longitude;
a data frame with two columns — latitude and longitude.
The function accepts as coordinates both numeric and string values.
Please note that Google might return a couple of results per each our call but we are using only the first one — results[[1]] — which corresponds to the best match in Google’s opinion.
Also be careful with hard-coding references to the elements you want to extract from the R list. For example, in our case the 5th element $address_components[[5]]$long_name might refer either to a city — London ($address_components$types = "postal_town"), level 2 administrative area — Greater London ($address_components$types = "administrative_area_level_2") or level 1 administrative area — England ($address_components$types = "administrative_area_level_1"). So, in this case we have to loop through the R list to find the types of information we need and extract the corresponding long_name.
Below are the results of running this function on the sample of London pubs whose coordinates we got earlier from the same API.
# extract coordinates from pubs_googlepubs_google_crd <- pubs_google[ , c("lat", "lng")]# replace "api_key" with your API keypubs_rev_google <- rev_geocode_google(pubs_google_crd, api_key)# check resultspubs_rev_google <- cbind(pubs_df, pubs_rev_google)pubs_rev_google
Now let’s turn our attention to the OSM’s Nominatim API.
The Nominatim search API allows you to look for a specific location based on its description or address. It supports both structured and free-text requests. The search query may also contain special phrases, which correspond to the specific OpenStreetMap tags. In our case this special phrase is a “pub”.
The reverse geocoding API generates an address from a place’s latitude and longitude.
The formats of API calls are presented below.
# geocoding formathttps://nominatim.openstreetmap.org/search/<query>?<params># geocoding examplehttps://nominatim.openstreetmap.org/search/The%20Churchill%20Arms,%20Notting%20Hill?format=json&polygon=1&addressdetails=1# reverse geocoding formathttps://nominatim.openstreetmap.org/reverse?<query># reverse geocoding examplehttps://nominatim.openstreetmap.org/reverse?format=json&lat=51.5068722&lon=-0.1948221&zoom=18&addressdetails=1
Some parameters are common for both geocoding and reverse geocoding calls:
format = [html | xml | json | jsonv2 | geojson | geocodejson] — output format;
addressdetails = [0|1] — include breakdown of address into elements;
extratags = [0|1] — additional information (wiki page, opening hours etc.);
accept-language — in what language to display the search results (English = en);
email — unless you provide an email address, which allows to track your activity, you will not be able to use the API in your app (error message would appear).
Some parameters are peculiar for each API.
Search:
query — free text or address;
countrycodes — limit the search by ISO 3166-1 alpha-2 country codes (the UK = gb);
limit — limit the number of returned results.
Reverse:
query = lat, lon — in WGS 84 format;
namedetails = [0|1] — include a list of alternative names in the results;
zoom = [0–18] — level of detail required for the address (default is 18, i.e. a specific building).
The query, format and email are required parameters, while the rest are optional. We will not be using namedetails parameter in our function and will not change the default value of zoom parameter — I provided them just for your reference.
One important aspect here is the usage of tags, which point out to a specific piece of information provided by OpenStreeMap mappers. Some of these tags have duplicates (like email and phone and website vs similar tags in contact namespace), so different people might label the same sort of information with different tags and you need to account for that in your app.
There are also a few requirements, which you must respect to be able to use Nominatim service:
restriction on the number of requests sent by the same website/app — one request per second per app;
bulk geocoding of large amounts of data is discouraged but smaller one-time tasks (our case) are allowed;
search results must be cached, so not to send the same request more than once.
The function below replicates the one we have built for Google Maps API, so we will not be describing it in detail.
The only significant difference is that we added two additional optional arguments: country, which corresponds to the countrycodes parameter of API call and is used to restrict your search to some counties only (by default it is not used) and language that corresponds to the accept-language parameter and allows you to choose the language in which to display results (default is English). Both arguments need to be provided in the format of a string: country as a comma-delimited list of codes (e.g. “gb,dr,fr”) and language as a single value (e.g. “es”).
Let’s see the results from running this function.
# replace "email" with your email addresspubs_nominatim <- geocode_nominatim(pubs_m, country = "gb", fields = "all", email = email)# let's now see the resultspubs_nominatim[, c(1:4)]pubs_nominatim[, c(1, 5:10)]pubs_nominatim[, c(1, 11:13)]pubs_nominatim[, c(1, 14:17)]
Similarly, the reverse geocoding function below to a large extent resembles the one we have built for the Google Maps API.
Here are the results from running this function on the sample of twelve London pubs.
# extract coordinates from geocoding resultspubs_nominatim_crd <- pubs_nominatim[, c("lat", "lng")]# replace "email" with your email addresspubs_rev_nominatim <- rev_geocode_nominatim(pubs_nominatim_crd, email = email)pubs_rev_nominatim <- cbind(pubs_m_df, pubs_rev_nominatim)# let's now see the resultspubs_rev_nominatim[, 1:4]pubs_rev_nominatim[, c(1, 5:11)]
The common truth is that a genuine interest in the subject can only be drawn when training material is complemented with examples of practical application. I promised you that based on information we got from API we would build an interactive map and I intend to deliver on that promise.
One of the ways to easily build a map is using JavaScript Leaflet library. Leaflet is described on its website as: “[...] the leading open-source JavaScript library for mobile-friendly interactive maps.” Many big tech companies, some media and even government bodies are using it: GitHub, Facebook, Pinterest, Financial Times, The Washington Post, Data.gov, European Commission are among the few. In our case, we will rely on the leaftlet package from the RStudio, which makes it easy to integrate and control Leaflet maps in R. For the full documentation check the package’s description on CRAN.
I will not describe here all the features this great tool provides because it’s the topic for another full article. Rather let’s concentrate on the most essential ones.
So, the process of creating a map in Leaflet involves three basic steps:
Create a map widget.Add layers to your map.Display the map.
Create a map widget.
Add layers to your map.
Display the map.
Widget is essentially a backbone or a container for your map.
Layers allow you to add to the map such elements as:
tiles — essentially the “skin” of your map, which defines its appearance and a level of detail. More about tiled maps;
markers — can be used to show a particular location on a map;
pop-ups and labels — can be used to add labels to your map. For example, to show an address or a contact information associated with some location;
polygons — a specific region or area. For example, a district within a state;
legends etc.
For our map we will be using a tile from OpenStreetMap (the default one for Leaflet) and plot the pubs’ location based on the coordinates we extracted from Nominatim. Additionally, we will add to the markers pop-ups with information about the pub’s name, address and contact details. As Nominatim did not return full details about each pub, I searched this information on my own. We are not using any polygons or legends in our visualization, I added links just for your reference.
So, before we move on let’s do some data preparation.
Now we can proceed with building the map itself.
Firstly, let’s prepare the text to be displayed in the pop-up messages: pub’s name, address and phone number. Website will not be showed separately but added as a hyperlink to the pub’s name. We will use some html to render our text in the format we want. Here is one hint. Pop-up messages are displayed only when you click on the objects they are attached to. If you want to display some information when cursor is hovered over the marker, you need to use labels. However, unlike pop-ups, labels do not automatically recognize HTML syntax — you would need to use HTML function from the htmltools package to transform your message first. Once it’s done we can “draw” our map.
Leaflet functions are quite self-explanatory. The only thing that might not be familiar to you is the pipe operator %>%, which was brought in by the tidyverse packages collection. Basically, it allows you to easily chain function calls by passing an output of one function as an argument of another. More information on that here.
# text to be diplayed on pop-upswebsite <- paste0("<a href='", pubs_map$website, "'>", pubs_map$pub_name, "</a>")center <- "<div style='text-align:center'>"name <- paste0(center, "<b>", website, "</b>", "</div>")address <- paste0(center, pubs_map$address_display, "</div>")phone <- paste0(center, pubs_map$phone, "</div>")# building the mappubs_map %>% leaflet() %>% addTiles() %>% addMarkers(~lng, ~lat, popup = paste0(name, address, phone))
Let’s finally see the result.
In this tutorial we covered different methods of retrieving geocoding data using Google Maps and Nominatim APIs and showed how this data can be used to plot particular locations on a map using JavaScript Leaflet library. I hope this guide will serve you as a starting point for exploring all the different kinds of APIs and mapping tools. | [
{
"code": null,
"e": 449,
"s": 172,
"text": "If you ever wondered how to build maps similar to the ones you constantly see in your apps, it’s probably a good place to start. In this tutorial we will cover how to find a place based on its description or coordinates and how to build a simple map based... |
Deploying a Machine Learning Model as a REST API | by Nguyen Ngo | Towards Data Science | As a Python developer and data scientist, I have a desire to build web apps to showcase my work. As much as I like to design the front-end, it becomes very overwhelming to take both machine learning and app development. So, I had to find a solution that could easily integrate my machine learning models with other developers who could build a robust web app better than I can.
By building a REST API for my model, I could keep my code separate from other developers. There is a clear division of labor here which is nice for defining responsibilities and prevents me from directly blocking teammates who are not involved with the machine learning aspect of the project. Another advantage is that my model can be used by multiple developers working on different platforms, such as web or mobile.
In this article, I will build a simple Scikit-Learn model and deploy it as a REST API using Flask RESTful. This article is intended especially for data scientists who do not have an extensive computer science background.
For this example, I put together a simple Naives Bayes classifier to predict the sentiment of phrases found in movie reviews.
The data came from the Kaggle competition, Sentiment Analysis on Movie Reviews. The reviews are divided into separate sentences and sentences are further divided into separate phrases. All phrases have a sentiment score so that a model can be trained on which words lend a positive, neutral, or negative sentiment to a sentence.
The majority of phrases had a neutral rating. At first, I tried to use a multinomial Naive Bayes classifier to predict one out of the 5 possible classes. However, because the majority of the data had a rating of 2, the model did not perform very well. I decided to keep it simple because the main point of this exercise is primarily about deploying as a REST API. So, I limited the data to the extreme classes and trained the model to predict only negative or positive sentiment.
It turned out that the multinomial Naive Bayes model was very effective at predicting positive and negative sentiment. You can find a quick overview of the model training process in this Jupyter Notebook Walkthrough. After training the model in a Jupyter notebook, I transferred my code into Python scripts and created a class object for the NLP model. You can find the code in my Github repo at this link. You will also need to pickle or save your model so that you can quickly load the trained model into your API script.
Now that we have the model, let’s deploy this as a REST API.
Start a new Python script for your Flask app for the API.
The code block below contains a lot of Flask boilerplate and the code to load the classifier and vectorizer pickles.
from flask import Flaskfrom flask_restful import reqparse, abort, Api, Resourceimport pickleimport numpy as npfrom model import NLPModelapp = Flask(__name__)api = Api(app)# create new model objectmodel = NLPModel()# load trained classifierclf_path = 'lib/models/SentimentClassifier.pkl'with open(clf_path, 'rb') as f: model.clf = pickle.load(f)# load trained vectorizervec_path = 'lib/models/TFIDFVectorizer.pkl'with open(vec_path, 'rb') as f: model.vectorizer = pickle.load(f)
The parser will look through the parameters that a user sends to your API. The parameters will be in a Python dictionary or JSON object. For this example, we will be specifically looking for a key called query. The query will be a phrase that a user will want our model to make a prediction on whether the phrase is positive or negative.
# argument parsingparser = reqparse.RequestParser()parser.add_argument('query')
Resources are the main building blocks for Flask RESTful APIs. Each class can have methods that correspond to HTTP methods such as: GET, PUT, POST, and DELETE. GET will be the primary method because our objective is to serve predictions. In the get method below, we provide directions on how to handle the user’s query and how to package the JSON object that will be returned to the user.
class PredictSentiment(Resource): def get(self): # use parser and find the user's query args = parser.parse_args() user_query = args['query'] # vectorize the user's query and make a prediction uq_vectorized = model.vectorizer_transform( np.array([user_query])) prediction = model.predict(uq_vectorized) pred_proba = model.predict_proba(uq_vectorized) # Output 'Negative' or 'Positive' along with the score if prediction == 0: pred_text = 'Negative' else: pred_text = 'Positive' # round the predict proba value and set to new variable confidence = round(pred_proba[0], 3) # create JSON object output = {'prediction': pred_text, 'confidence': confidence} return output
There is a great tutorial by Flask-RESTful where they build a to-do application and demonstrate how to use the PUT, POST, and DELETE methods.
The following code will set the base url to the sentiment predictor resource. You can imagine that you might have multiple endpoints, each one pointing to a different model that would make different predictions. One example could be an endpoint, '/ratings', which would direct the user to another model that can predict movie ratings given genre, budget, and production members. You would need to create another resource object for this second model. These can just be added right after one another as shown below.
api.add_resource(PredictSentiment, '/') # example of another endpointapi.add_resource(PredictRatings, '/ratings')
Not much to say here. Set debug to False if you are deploying this API to production.
if __name__ == '__main__': app.run(debug=True)
Below are some examples of how users can access your API so that they can get predictions.
With the Requests module in a Jupyter Notebook:
url = 'http://127.0.0.1:5000/'params ={'query': 'that movie was boring'}response = requests.get(url, params)response.json()Output: {'confidence': 0.128, 'prediction': 'Negative'}
Using curl in the terminal:
$ curl -X GET http://127.0.0.1:5000/ -d query='that movie was boring'{ "prediction": "Negative", "confidence": 0.128}
Using HTTPie in the terminal:
$ http http://127.0.0.1:5000/ query=='that movie was boring'HTTP/1.0 200 OKContent-Length: 58Content-Type: application/jsonDate: Fri, 31 Aug 2018 18:49:25 GMTServer: Werkzeug/0.14.1 Python/3.6.3{ "confidence": 0.128, "prediction": "Negative"}
Now, my teammates can add sentiment prediction to their app just by making a request to this API, all without having to mix Python and JavaScript together.
Sometimes it’s helpful to see all the code in one place.
Last thing I want to include is a little overview of the file structure for this simple API.
sentiment-clf/├── README.md├── app.py # Flask REST API script├── build_model.py # script to build and pickle the classifier├── model.py # script for the classifier class object├── util.py # helper functions├── requirements.txt└── lib/ ├── data/ # data from Kaggle │ ├── sampleSubmission.csv │ ├── test.tsv │ └── train.tsv └── models/ # pickled models for import into API script ├── SentimentClassifier.pkl └── TFIDFVectorizer.pkl
Once you have built your model and REST API and finished testing locally, you can deploy your API just as you would any Flask app to the many hosting services on the web. By deploying on the web, users everywhere can make requests to your URL to get predictions. Guides for deployment are included in the Flask docs.
This was only a very simple example of building a Flask REST API for a sentiment classifier. The same process can be applied to other machine learning or deep learning models once you have trained and saved them.
In addition to deploying models as REST APIs, I am also using REST APIs to manage database queries for data that I have collected by scraping from the web. This lets me collaborate with a full-stack developer without having to manage the code for their React application. If a mobile developer wants to build an app, then they would only have to become familiar with the API endpoints.
If you have any feedback or critiques, please feel free to share them with me. If this walkthrough helped you, please like 👏 the article. Cheers! 🍻 | [
{
"code": null,
"e": 550,
"s": 172,
"text": "As a Python developer and data scientist, I have a desire to build web apps to showcase my work. As much as I like to design the front-end, it becomes very overwhelming to take both machine learning and app development. So, I had to find a solution that c... |
Python | Test if all elements are present in list - GeeksforGeeks | 27 Sep, 2019
Sometimes, while working with Python list, we have a problem in which we need to check for a particular list of values and want to be sure if a target list contains all the given values. This has it’s application in web development domain when required some type of filtering. Let’s discuss a way in which this task can be performed.
Method : Using list comprehension + all()This task can be performed using the inbuilt functionality of all(). The all() can be fed with list comprehension logic to check if element of test list is present in target list and rest is done by all().
# Python3 code to demonstrate working of# Test if all elements are present in list# Using list comprehension + all() # initializing listtarget_list = [6, 4, 8, 9, 10] # initializing test list test_list = [4, 6, 9] # printing listsprint("The target list : " + str(target_list))print("The test list : " + str(test_list)) # Test if all elements are present in list# Using list comprehension + all()res = all(ele in target_list for ele in test_list) # Printing resultprint("Does every element of test_list is in target_list ? : " + str(res))
The target list : [6, 4, 8, 9, 10]
The test list : [4, 6, 9]
Does every element of test_list is in target_list ? : True
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 24235,
"s": 23901,
"text": "Sometimes, while working with Python list, we have a problem in which we need to check for a particular list of values and want to be sure if a target list contain... |
Make your Pandas apply functions faster using Parallel Processing | by Rahul Agarwal | Towards Data Science | Parallelization is awesome.
We data scientists have got laptops with quad-core, octa-core, turbo-boost. We work with servers with even more cores and computing power.
But do we really utilize the raw power we have at hand?
Instead, we wait for time taking processes to finish. Sometimes for hours, when urgent deliverables are at hand.
Can we do better? Can we get better?
In this series of posts named ‘Python Shorts,’ I will explain some simple constructs provided by Python, some essential tips and some use cases I come up with regularly in my Data Science work.
This post is about using the computing power we have at hand and applying it to the data structure we use most.
We have got a huge pandas data frame, and we want to apply a complex function to it which takes a lot of time.
For this post, I will use data from the Quora Insincere Question Classification on Kaggle, and we need to create some numerical features like length, the number of punctuations, etc. on it.
The competition was a Kernel-based competition and the code needed to run in 2 hours. So every minute was essential, and there was too much time going in preprocessing.
Can we use parallelization to get extra performance out of our code?
Yes, we can.
Let me first start with defining the function I want to use to create our features. add_features is the toy function we wish to apply to our data.
We can use parallelized apply using the below function.
def parallelize_dataframe(df, func, n_cores=4): df_split = np.array_split(df, n_cores) pool = Pool(n_cores) df = pd.concat(pool.map(func, df_split)) pool.close() pool.join() return df
What does it do? It breaks the dataframe into n_cores parts, and spawns n_cores processes which apply the function to all the pieces.
Once it applies the function to all the split dataframes, it just concatenates the split dataframe and returns the full dataframe to us.
It is pretty simple to use.
train = parallelize_dataframe(train_df, add_features)
To check the performance of this parallelize function, I ran %%timeit magic on this function in my Jupyter notebook in a Kaggle Kernel.
vs. just using the function as it is:
As you can see I gained some performance just by using the parallelize function. And it was using a kaggle kernel which has only got 2 CPUs.
In the actual competition, there was a lot of computation involved, and the add_features function I was using was much more involved. And this parallelize function helped me immensely to reduce processing time and get a Silver medal.
Here is the kernel with the full code.
Parallelization is not a silver bullet; it is buckshot. It won’t solve all your problems, and you would still have to work on optimizing your functions, but it is a great tool to have in your arsenal.
Time never comes back, and sometimes we have a shortage of it. At these times we should be able to use parallelization easily.
Parallelization is not a silver bullet it is a buckshot
Also if you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out.
I am going to be writing more beginner friendly posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. | [
{
"code": null,
"e": 199,
"s": 171,
"text": "Parallelization is awesome."
},
{
"code": null,
"e": 338,
"s": 199,
"text": "We data scientists have got laptops with quad-core, octa-core, turbo-boost. We work with servers with even more cores and computing power."
},
{
"code... |
How to extract correlation coefficient value from correlation test in R? | To perform the correlation test in R, we need to use cor.test function with two variables and it returns so many values such as test statistic value, degrees of freedom, the p-value, the confidence interval, and the correlation coefficient value. If we want to extract the correlation coefficient value from the correlation test output then estimate function could be used as shown in below examples.
Live Demo
x1<-rnorm(20,5,2)
y1<-rnorm(20,5,1)
cor.test(x1,y1)
Pearson's product-moment correlation
data: x1 and y1
t = -0.13423, df = 18, p-value = 0.8947
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.4675990 0.4167308
sample estimates:
cor
-0.03162132
cor.test(x1,y1)$estimate cor -0.08194057
Live Demo
x2<-runif(5000,2,5)
y2<-runif(5000,2,10)
cor.test(x2,y2)
Pearson's product-moment correlation
data: x2 and y2
t = -1.4823, df = 4998, p-value = 0.1383
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.048653479 0.006760764
sample estimates:
cor
-0.02096246
cor.test(x2,y2)$estimate cor 0.01301688
Live Demo
x3<-runif(50,2,5)
y3<-runif(50,2,10)
cor.test(x3,y3)
Pearson's product-moment correlation
data: x3 and y3
t = -0.80709, df = 48, p-value = 0.4236
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.3817626 0.1680496
sample estimates:
cor
-0.1157106
cor.test(x3,y3)$estimate cor 0.1031475
Live Demo
x4<-rexp(500,2.1)
y4<-rexp(500,5.75)
cor.test(y4,y4)
Pearson's product-moment correlation
data: y4 and y4
t = Inf, df = 498, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
1 1
sample estimates:
cor
1
cor.test(y4,y4)$estimate cor 1
Live Demo
x5<-rpois(100000,2)
y5<-rpois(100000,5)
cor.test(y5,y5)
Pearson's product-moment correlation
data: y5 and y5
t = 1.5006e+10, df = 99998, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
1 1
sample estimates:
cor
1
cor.test(y5,y5)$estimate cor 1 | [
{
"code": null,
"e": 1463,
"s": 1062,
"text": "To perform the correlation test in R, we need to use cor.test function with two variables and it returns so many values such as test statistic value, degrees of freedom, the p-value, the confidence interval, and the correlation coefficient value. If we ... |
The 5 Packages You Should Know for Text Analysis with R | by Céline Van den Rul | Towards Data Science | install.packages("quanteda")library(quanteda)
Quanteda is the go-to package for quantitative text analysis. Developed by Kenneth Benoit and other contributors, this package is a must for any data scientist doing text analysis.
Why? Because this package allows you to do A LOT. This ranges from the basics in natural language processing — lexical diversity, text-preprocessing, constructing a corpus, token objects, document-feature matrix) — to more advanced statistical analysis such as wordscores or wordfish, document classification (e.g. Naive Bayes) and topic modelling.
A useful tutorial of the package is the one developed by Kohei Watanabe and Stefan Müller (link).
install.packages("text2vec")library(text2vec)
Text2vec is an extremely useful package if you’re building machine learning algorithms based on text data. This package allows you to construct a document-term matrix (dtm) or term co-occurence matrix (tcm) from documents. As such, you vectorize text by creating a map from words or n-grams to a vector space. Based on this, you can then fit a model to that dtm or tcm. This ranges from topic modelling (LDA, LSA), word embeddings (GloVe), collocations, similarity searches and more.
The package is inspired by Gensim, a famous python library for natural language processing. You can find a useful tutorial of the package here.
install.packages("tidytext")library(tidytext)
Tidytext is an essential package for data wrangling and visualisation. One of its benefits is that it works very well in tandem with other tidy tools in R such as dplyr or tidyr. In fact, it was built for that purpose. Recognising cleaning data always requires a big amount of effort and that many of these methods aren’t easily applicable to text, Silge & Robinson (2016) developed tidytext to make text mining tasks easier, more effective and consistent with tools already in wide use.
As a result, this package provides commands that allow you to convert text to and from tidy formats. The possibilities for analysis and visualisation are numerous: from sentiment analysis to tf-idf statistics, n-grams or topic modelling. The package particularly stands out for the visualization of the output.
You can find a useful tutorial of the package here.
install.packages("stringr")library(stringr)
As a data scientist, you’ve mostly already worked with strings. They play a big role in many data cleaning and preparation tasks. Part of the tidyverse, an ecosystem of packages (that also includes ggplot and dplyr), the stringr package provides a cohesive set of functions that allow you to easily work with strings.
When it comes to text analysis, stringr is a particularly handy package to work with regular expressions as it provides a few useful pattern matching functions. Other functions include character manipulation (manipulating individual characters within the strings in character vectors) and whitespace tools (add, remove, manipulate whitespace).
The CRAN — R project has a useful tutorial on the package (link).
install.packages("spacyr")library(spacyr)spacy_install()spacy_initialize()
Most of you may know the spaCy package in Python. Well, spacyr provides a convenient wrapper of that package in R, making it easy to access the powerful functionality of spaCy in a simple format. In fact, it’s a pretty incredible package if you think about it, allowing R to harness the power of Python. To access these Python functionalities, spacyr opens a connection by being initialized within your R session.
This package is essential for more advanced natural language processing models — e.g. preparing text for deep learning — and other useful functionalities such as speech tagging, tokenization, parsing etc. In addition, it also works well in combination with the quanteda and tidytext packages.
You can find a useful tutorial to the package here.
I regularly write articles about Data Science and Natural Language Processing. Follow me on Twitter or Medium to check out more articles like these or simply to keep updated about the next ones. Thanks for reading! | [
{
"code": null,
"e": 217,
"s": 171,
"text": "install.packages(\"quanteda\")library(quanteda)"
},
{
"code": null,
"e": 398,
"s": 217,
"text": "Quanteda is the go-to package for quantitative text analysis. Developed by Kenneth Benoit and other contributors, this package is a must f... |
C# ToTuple() Method | Let’s say you have a ValueTuple and would like to convert it to a tuple, then use the ToTuple() method.
With C#, we can easily convert a ValueTuple to a Tuple using ToTuple() method.
Note − Add System.ValueTuple package to run ValueTuple program.
Let’s see how to add it −
Go to your project
Right click on the project in the solution explorer
Select “Manage NuGet Packages”
You will reach the NuGet Package Manager.
Now, click the Browse tab and find “ValueTuple”
Finally, add System.ValueTuple package
Let us see an example to implement ToTuple() method.
using System;
class Program {
static void Main() {
var val = (1, 2, 3);
//Add System.ValueTuple package to run this program
// ValueTuple
Console.WriteLine(“ValueTuple: ” val);
// Tuple
Tuple<int, int, int> myTuple = val.ToTuple();
Console.WriteLine(“Tuple: ”+myTuple);
}
}
ValueTuple: (1, 2, 3)
Tuple: (1, 2, 3) | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "Let’s say you have a ValueTuple and would like to convert it to a tuple, then use the ToTuple() method."
},
{
"code": null,
"e": 1245,
"s": 1166,
"text": "With C#, we can easily convert a ValueTuple to a Tuple using ToTuple() method.... |
C Program for Minimum number of jumps to reach the end | We are given, an array of non-negative integers denoting the maximum number of
steps that can be made forward from that element. The pointer is initially positioned at the first index [0 index] of the array. Your goal is to reach the last
index of the array in the minimum number of steps. If it is not possible to reach the
end of the array then print the maximum integer.
naive approach is to begin from initial{the primary} component and recursively call for all the components accessible from the first element. The minimum range of jumps to reach the end from first is calculated using the minimum range of jumps required to achieve end from the elements accessible from first.
minJumps(start, end) = Min ( minJumps(k, end) )
for all k accessible from the start
Here we’ll use the top-down approach of dynamic programming. We’ll use Hashmap to store the subproblem results and whenever we create a solution, first check if the subproblem is already resolved, if yes then use it.
Input: { 1, 2, 4, 1, 2, 2, 1, 1, 3, 8 }
Output: Minimum number of steps = 6 {1-->2-->4-->1-->3-->8}
The first element is 1, so it can only go to 2. The second element is
2, so can make at most 2 steps eg to 4 or 1. It goes to 4 from where it reaches 1 and
so on.
The complexity of dynamic programming approach to find the minimum number
of jumps to reach the end of an array is O(n^2) with space complexity of O(n)
Live Demo
#include<stdio.h>
#include<limits.h>
int min_steps (int arr[], int n){
int steps[n];
int i, j;
if (n == 0 || arr[0] == 0)
return INT_MAX;
steps[0] = 0;
for (i = 1; i < n; i++){
steps[i] = INT_MAX;
for (j = 0; j < i; j++){
if (i <= j + arr[j] && steps[j] != INT_MAX){
steps[i] = (steps[i] < (steps[j] + 1)) ? steps[i] : steps[j] + 1;
break;
}
}
}
return steps[n - 1];
}
int main (){
int arr[100];
int n;
printf ("Enter size of the array:");
scanf ("%d", &n);
printf ("Enter elements in the array:");
for (int i = 0; i < n; i++){
scanf ("%d", &arr[i]);
}
printf ("Minimum number of steps : %d", min_steps (arr, n));
return 0;
}
Enter size of array : 7
Enter elements in the array :2 1 1 5 2 1 1
Minimum number of steps : 3 | [
{
"code": null,
"e": 1436,
"s": 1062,
"text": "We are given, an array of non-negative integers denoting the maximum number of\nsteps that can be made forward from that element. The pointer is initially positioned at the first index [0 index] of the array. Your goal is to reach the last\nindex of the... |
ASP.NET - File Uploading | ASP.NET has two controls that allow users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it, or ignore it. The following controls allow the file uploading:
HtmlInputFile - an HTML server control
HtmlInputFile - an HTML server control
FileUpload - and ASP.NET web control
FileUpload - and ASP.NET web control
Both controls allow file uploading, but the FileUpload control automatically sets the encoding of the form, whereas the HtmlInputFile does not do so.
In this tutorial, we use the FileUpload control. The FileUpload control allows the user to browse for and select the file to be uploaded, providing a browse button and a text box for entering the filename.
Once, the user has entered the filename in the text box by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk.
The basic syntax of FileUpload is:
<asp:FileUpload ID= "Uploader" runat = "server" />
The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those, the FileUpload class has the following read-only properties:
The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following frequently used properties:
The following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type, and file length.
In the design view, the form looks as follows:
The content file code is as given:
<body>
<form id="form1" runat="server">
<div>
<h3> File Upload:</h3>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="btnsave" runat="server" onclick="btnsave_Click" Text="Save" style="width:85px" />
<br /><br />
<asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>
The code behind the save button is as given:
protected void btnsave_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
if (FileUpload1.HasFile)
{
try
{
sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);
//saving the file
FileUpload1.SaveAs("<c:\\SaveDirectory>" + FileUpload1.FileName);
//Showing the file information
sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);
}catch (Exception ex)
{
sb.Append("<br/> Error <br/>");
sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
}
}
else
{
lblmessage.Text = sb.ToString();
}
}
Note the following:
The StringBuilder class is derived from System.IO namespace, so it needs to be included.
The StringBuilder class is derived from System.IO namespace, so it needs to be included.
The try and catch blocks are used for catching errors, and display the error message.
The try and catch blocks are used for catching errors, and display the error message.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2573,
"s": 2347,
"text": "ASP.NET has two controls that allow users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it, or ignore it. The following controls allow the file uploading:"
},
{
"code": null,... |
MongoDB query to find documents whose array contains a string that is a substring of a specific word | For such evaluations, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo90.insertOne(
... {"words": ["john", "jace"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2c1ada79799acab037af56")
}
> db.demo90.insertOne(
... {"words": ["sam", "adam"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2c1adb79799acab037af57")
}
Display all documents from a collection with the help of find() method −
> db.demo90.find();
This will produce the following output −
{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }
{ "_id" : ObjectId("5e2c1adb79799acab037af57"), "words" : [ "sam", "adam" ] }
Following is the query to find documents whose array contains a string that is a substring of specific word −
> db.demo90.aggregate([ { $match: { $expr: { $anyElementTrue: { $map: { input: "$words", as: "j", in: { $ne: [ -1, { $indexOfBytes: [ "john", "$$j" ] } ] } } } } } } ]);
This will produce the following output −
{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] } | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "For such evaluations, use aggregate() in MongoDB. Let us create a collection with documents −"
},
{
"code": null,
"e": 1459,
"s": 1156,
"text": "> db.demo90.insertOne(\n... {\"words\": [\"john\", \"jace\"]\n... }\n... );\n{\n \"ack... |
Appending data to a MySQL field that already has data in it? | You can append data to a MySQL database field with the help of in-built CONCAT() function.
The syntax is as follows −
update yourTableName set yourColumnName = CONCAT(yourColumnName,’AppendValue’);
To understand the above concept, let us create a table. The query to create a table −
mysql> create table AppendingDataDemo
−> (
−> FirstNameAndLastName varchar(200)
−> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into AppendingDataDemo values('John');
Query OK, 1 row affected (0.27 sec)
mysql> insert into AppendingDataDemo values('Bob');
Query OK, 1 row affected (0.20 sec)
mysql> insert into AppendingDataDemo values('Carol');
Query OK, 1 row affected (0.30 sec)
Display all records with the help of select statement −
mysql> select *from AppendingDataDemo;
The following is the output −
+----------------------+
| FirstNameAndLastName |
+----------------------+
| John |
| Bob |
| Carol |
+----------------------+
3 rows in set (0.00 sec)
Here is the query to append the data ”Taylor” to the data already in the column. Therefore, the data will get appended.
The query is as follows −
mysql> update AppendingDataDemo set FirstNameAndLastName = concat(FirstNameAndLastName,' Taylor');
Query OK, 3 rows affected (0.10 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Now you can check with select statement that data has been appended or not. The query is as follows −
mysql> select *from AppendingDataDemo;
The following is the output −
+----------------------+
| FirstNameAndLastName |
+----------------------+
| John Taylor |
| Bob Taylor |
| Carol Taylor |
+----------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "You can append data to a MySQL database field with the help of in-built CONCAT() function."
},
{
"code": null,
"e": 1180,
"s": 1153,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1260,
"s": 1180,
"t... |
Program for Area Of Square in C++ | We are given with a side of a rectangle and our task is to print the area of the square from that side.
Square is 2-D plain figure which have 4 sides and forms 4 angles of 90degree each and all the sides are of equal shape. In other words we can say that the square is a form of rectangle with equal sides.
Given below is representation of a square −
The Area of square is Side x Side
Input: 6
Output: 36
As the side is 6 so the output is 6*6=36
Input: 12
Output: 144
START
Step 1-> Declare a function int area(int side)
In function area
Declare a variable area and set it as side * side
Return area
End
Step 2 -> Declare a function int main()
In main Function
Declare a variable side and Set a Value
Call function area(side)
End
STOP
#include <iostream>
using namespace std;
//funcion to calculate area of square
int area(int side){
int area = side * side;
return area;
}
// Driver Code
int main(){
int side = 40;
cout <<"area of square is :"<<area(side);
return 0;
}
area of square is :1600 | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "We are given with a side of a rectangle and our task is to print the area of the square from that side."
},
{
"code": null,
"e": 1369,
"s": 1166,
"text": "Square is 2-D plain figure which have 4 sides and forms 4 angles of 90degree e... |
Python 3 - dictionary fromkeys() Method | The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Following is the syntax for fromkeys() method −
dict.fromkeys(seq[, value]))
seq − This is the list of values which would be used for dictionary keys preparation.
seq − This is the list of values which would be used for dictionary keys preparation.
value − This is optional, if provided then value would be set to this value
value − This is optional, if provided then value would be set to this value
This method returns the list.
The following example shows the usage of fromkeys() method.
#!/usr/bin/python3
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict))
When we run above program, it produces the following result −
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
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": 2431,
"s": 2340,
"text": "The method fromkeys() creates a new dictionary with keys from seq and values set to value."
},
{
"code": null,
"e": 2479,
"s": 2431,
"text": "Following is the syntax for fromkeys() method −"
},
{
"code": null,
"e": 2509,
... |
Java Examples - Find an object in Array | How to find an object or a string in an Array?
Following example uses Contains method to search a String in the Array.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
System.out.println("Array elements of array1"+objArray);
System.out.println("Array elements of array2"+objArray2);
System.out.println("Array 1 contains String common2?? "
+objArray.contains("common1"));
System.out.println("Array 2 contains Array1?? "
+objArray2.contains(objArray) );
}
}
The above code sample will produce the following result.
Array elements of array1[common1, common2]
Array elements of array2[common1, common2, notcommon, notcommon1]
Array 1 contains String common2?? true
Array 2 contains Array1?? false
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2115,
"s": 2068,
"text": "How to find an object or a string in an Array?"
},
{
"code": null,
"e": 2187,
"s": 2115,
"text": "Following example uses Contains method to search a String in the Array."
},
{
"code": null,
"e": 2909,
"s": 2187,
"... |
Example and usage of JOINS in DB2 | Problem: How will you find the ORDER_ID, TRANSACTION_ID and TRANSACTION_STATUS from ORDERS and TRANSACTIONS DB2 table using joins?
We can find ORDER_ID, TRANSACTION_ID and TRANSACTION_STATUS from ORDERS and TRANSACTIONS table using the INNER JOIN query.
For example, if we have below 2 ORDERS table.
We can use an inner join query as below.
SELECT ORDER_ID, TRANSACTION_ID, TRANSACTION_STATUS FROM ORDERS INNER JOIN TRANSACTIONS ON
ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID
The above query will return the result below. | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Problem: How will you find the ORDER_ID, TRANSACTION_ID and TRANSACTION_STATUS from ORDERS and TRANSACTIONS DB2 table using joins?"
},
{
"code": null,
"e": 1316,
"s": 1193,
"text": "We can find ORDER_ID, TRANSACTION_ID and TRANSACTIO... |
gzip.decompress(s) in Python - GeeksforGeeks | 26 Mar, 2020
With the help of gzip.decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip.decompress(s) method.
Syntax : gzip.decompress(string)Return : Return decompressed string.
Example #1 :In this example we can see that by using gzip.decompress(s) method, we are able to decompress the compressed string in the byte format of string by using this method.
# import gzip and decompressimport gzips = b'This is GFG author, and final year student.'s = gzip.compress(s) # using gzip.decompress(s) methodt = gzip.decompress(s)print(t)
Output :
b’This is GFG author, and final year student.’
Example #2 :
# import gzip and compressimport gzips = b'GeeksForGeeks@12345678's = gzip.compress(s) # using gzip.decompress(s) methodt = gzip.decompress(s)print(t)
Output :
b’GeeksForGeeks@12345678′
Python-gzip
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 24386,
"s": 24358,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24536,
"s": 24386,
"text": "With the help of gzip.decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip.decompress(s) method."
},
{
... |
How to create a frequency table in data frame format in R? | To create a frequency table in R, we can simply use table function but the output of table function returns a horizontal table. If we want to read the table in data frame format then we would need to read the table as a data frame using as.data.frame function. For example, if we have a table called T then to convert it into a data frame format we can use the command as.data.frame(T).
Live Demo
> x1<-rpois(200,2)
> x1
[1] 2 0 2 3 2 3 1 2 1 4 0 0 4 4 1 3 1 2 1 3 2 3 2 1 4 1 4 1 1 1 2 2 0 2 1 1 1
[38] 1 5 1 1 2 3 0 5 3 3 2 0 1 2 1 3 2 1 5 3 2 2 2 3 3 0 3 0 3 1 3 3 4 0 3 3 0
[75] 2 3 0 2 2 1 3 1 4 0 1 1 5 1 3 2 0 2 4 1 1 2 2 1 3 0 2 3 3 1 4 1 4 4 1 3 5
[112] 0 0 2 1 0 1 0 3 3 4 6 3 3 0 2 0 2 1 3 1 1 1 1 2 4 1 0 1 3 2 2 0 2 3 2 4 4
[149] 1 2 0 5 3 3 3 1 4 5 5 1 3 1 2 4 4 5 0 3 3 1 2 1 1 0 3 3 5 1 1 6 1 2 3 6 1
[186] 2 0 1 4 1 1 1 2 3 5 1 1 1 0 4
> table_x1<-table(x1)
> table_x1
x1
0 1 2 3 4 5 6
27 58 39 42 20 11 3
> df1<-as.data.frame(table_x1)
> df1
x1 Freq
1 0 27
2 1 58
3 2 39
4 3 42
5 4 20
6 5 11
7 6 3
Live Demo
> x2<-rpois(200,10)
> x2
[1] 8 8 6 7 10 14 9 9 6 11 13 13 12 16 6 12 10 11 7 14 10 13 11 16 8
[26] 12 10 11 8 14 9 8 8 7 5 10 13 6 8 9 18 13 13 11 13 9 4 10 11 13
[51] 7 8 6 8 14 11 15 12 9 12 17 4 10 8 14 6 10 7 10 9 11 9 8 6 8
[76] 12 10 7 11 11 13 6 13 11 13 7 18 14 17 15 14 9 9 10 12 10 16 5 11 9
[101] 9 14 10 6 9 7 4 7 6 5 14 16 9 10 8 16 16 12 6 9 12 5 8 5 12
[126] 11 6 6 5 17 11 13 12 9 11 12 13 14 7 9 15 4 13 12 15 10 10 8 10 14
[151] 11 17 11 13 8 3 12 11 12 9 8 12 3 11 7 8 11 10 4 15 7 9 6 12 11
[176] 8 10 10 19 12 16 8 9 10 7 6 9 14 7 17 13 7 10 20 7 10 16 7 3 9
> table_x2<-table(x2)
> table_x2
x2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
3 5 6 15 17 20 22 23 21 18 16 12 5 8 5 2 1 1
> df2<-as.data.frame(table_x2)
> df2
x2 Freq
1 3 3
2 4 5
3 5 6
4 6 15
5 7 17
6 8 20
7 9 22
8 10 23
9 11 21
10 12 18
11 13 16
12 14 12
13 15 5
14 16 8
15 17 5
16 18 2
17 19 1
18 20 1
Live Demo
> x3<-rpois(200,8)
> x3
[1] 7 11 9 11 10 8 6 13 7 7 9 4 6 8 11 9 11 4 12 4 4 7 9 7 3
[26] 7 3 9 6 7 4 6 7 5 8 8 13 4 2 10 8 2 12 4 6 3 9 4 8 9
[51] 5 5 5 8 9 13 8 9 8 6 7 13 1 7 11 5 4 7 11 13 9 9 8 5 12
[76] 8 7 9 12 6 7 8 11 9 17 5 8 6 8 8 8 4 12 10 10 9 14 7 8 6
[101] 9 12 8 8 5 7 8 8 8 9 6 10 4 15 8 9 7 5 8 9 14 8 11 9 5
[126] 6 6 8 12 15 7 7 9 14 10 8 6 7 9 5 8 5 14 10 16 12 7 11 12 16
[151] 8 9 4 8 14 8 11 7 7 5 5 3 9 11 9 13 5 5 9 8 7 9 6 5 12
[176] 11 7 5 13 10 10 10 7 7 11 7 11 8 6 10 7 7 5 8 3 5 11 3 13 16
> table_x3<-table(x3)
> table_x3
x3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 2 6 12 20 15 29 34 26 11 15 10 8 5 2 3 1
> df3<-as.data.frame(table_x3)
> df3
x3 Freq
1 1 1
2 2 2
3 3 6
4 4 12
5 5 20
6 6 15
7 7 29
8 8 34
9 9 26
10 10 11
11 11 15
12 12 10
13 13 8
14 14 5
15 15 2
16 16 3
17 17 1
Live Demo
> x4<-rpois(200,5)
> x4
[1] 5 4 7 8 3 4 2 7 3 2 2 6 5 6 10 6 3 5 6 5 2 3 3 5 3
[26] 1 8 1 10 1 7 4 8 7 1 4 4 5 3 5 6 2 6 8 7 2 5 6 4 8
[51] 4 5 5 7 4 6 2 3 6 6 3 5 6 7 3 6 5 6 7 8 2 3 6 1 7
[76] 8 8 5 4 6 4 3 2 4 3 6 6 2 6 9 3 3 2 5 4 8 3 2 4 6
[101] 5 6 5 5 12 7 4 4 5 5 8 5 4 1 5 1 4 5 6 4 3 3 5 6 1
[126] 5 2 5 1 8 8 3 5 3 3 5 8 3 1 6 5 5 9 6 9 6 3 9 3 4
[151] 8 4 4 5 6 7 9 6 8 6 4 2 3 7 8 8 2 5 7 5 7 5 5 10 4
[176] 4 5 6 6 3 10 7 5 6 3 6 5 3 5 5 3 2 10 6 2 6 5 6 9 4
> table_x4<-table(x4)
> table_x4
x4
1 2 3 4 5 6 7 8 9 10 12
10 17 29 25 40 35 15 17 6 5 1
> df4<-as.data.frame(table_x4)
> df4
x4 Freq
1 1 10
2 2 17
3 3 29
4 4 25
5 5 40
6 6 35
7 7 15
8 8 17
9 9 6
10 10 5
11 12 1 | [
{
"code": null,
"e": 1449,
"s": 1062,
"text": "To create a frequency table in R, we can simply use table function but the output of table function returns a horizontal table. If we want to read the table in data frame format then we would need to read the table as a data frame using as.data.frame fu... |
K-Means Clustering Explained: Algorithm And Sklearn Implementation | by Marius Borcan | Towards Data Science | K-Means clustering is one of the most powerful clustering algorithms in the Data Science and Machine Learning world. It is very simple, yet it delivers wonderful results. And because clustering is a very important step for understanding a dataset, in this article we are going to discuss what is clustering, why do we need it and what is k-means clustering going to help us with in data science.
What is Clustering
What is Unsupervised Machine Learning
Clustering applications
K-Means Clustering explained
K-Means Clustering Algorithm
K-Means Clustering Implementation using Scikit-Learn and Python
Clustering is the task of grouping data into two or more groups based on the properties of the data, and more exactly based on certain patterns which are more or less obvious in the data. The goal is to find those patterns in the data that help us be sure that, given a certain item in our dataset, we will be able to correctly place the item in a correct group, so that it is similar to other items in that group, but different from items in other groups.
That means the clustering actually consists of two parts: one is to identify the groups and the other one is to try as much as possible to place every item in the correct group.
The ideal result for a clustering algorithm is that two items in the same group are as similar to each other, while two items from different groups are as different as possible.
A real-world example would be customer segmentation. As a business selling various type of products/services, it would be very difficult to find the perfect business strategy for each and every customer. But we can be smart about it and try to group our customers into a few subgroups, understand what those customers all have in common and adapt our business strategy for every group. Coming up with the wrong business strategy to a customer would mean perhaps losing that customer, so it’s important that we’ve achieved a good clustering of our market.
Unsupervised Machine Learning is a type of Machine Learning Algorithm that tries to infer patterns in the data without any prior knowledge. The opposite is Supervised Machine Learning, where we have a training set and the algorithm will try to find the patterns in the data by matching inputs to predefined outputs.
The reason I am writing about this is because clustering an Unsupervised Machine Learning Task. When applying a clustering algorithm, we don’t know the categories a priori(although we can set the number of categories that we want to be identified).
The categories will emerge from the algorithm analyzing the data. Because of that, we may call clustering an exploratory machine learning task, because we only know the number of categories, but not their properties. Then we can try playing around with different numbers of categories and see if our data is better clustered or not.
And then we have to understand our clusters, which may actually be the most different task. Let’s reuse the example with customer segmentation. Let’s say we have run a clustering algorithm and we get our customers clustered into 3 groups. But what are those groups? Why has the algorithm decided that these customers fit into this group, and those customers fit into that group? This is the part where you need very skilled data scientists along with people who understand your business very well. They will look at the data, try to analyze a few items in each category and try to guess a few criteria. Then they will extrapolate from there once they find a valid pattern.
What happens when we get a new customer? We have to put this customer into one of the clusters we already have, so we can run the data about this customer through our algorithm and the algorithm will fit our customer into one of our clusters. Also, in the future, after we acquire a large number of new customers, we might need to rebuild our clusters — maybe new clusters will appear or old clusters will disappear.
What are some common clustering applications? Before we fall in love with clustering algorithms, we need to understand when we can use them and when not.
The most common use case is the one we’ve already discussed: customer/market segmentation. Companies run these types of analysis all the time so they can understand their customers and markets and tailor their business strategies, services and products for a better fit.
Another common use case is represented by information extraction tasks. In information extraction tasks we often need to find relations between entities, words, documents and so on. Now, if your intuition tells you we have a higher chance of finding relations between items which are more similar to each other, then you’re right, because clustering our data points might help us figure out where to look for relations. (Note: if you want to read more about information extraction, you can also try this article: Python NLP Tutorial: Information Extraction and Knowledge Graphs).
Another very popular use cases is to use clustering for image segmentation. Image segmentation is the task of looking at an image and trying to identify different items in that image. We can use clustering to analyze the pixels of the image and to identify which item in the image contains which pixel.
The K-Means clustering algorithm is an iterative clustering algorithm which tries to asssign data points to exactly one cluster of the K number of clusters we predefine.
As with any other clustering algorithm, it tries to make the items in one cluster as similar as possible, while also making the clusters as different from each other as possible. It does so by making sure that the sum of squared distance between the data points in a cluster and the centroid of that cluster is minimum. The centroid of the cluster is the mean value of all the values in the cluster. You also get from this paragraph where the name K-Means comes from.
In more technical terms, we try to make the data into one cluster as homogenuous as possible, while making the cluster as heterogenuous as possible. The K number is the number of clusters we try to obtain. We can play around with K until we are satisfied with our results.
The K-Means Clustering algorithm works with a few simple steps.
Assign the K number of clustersShuffle the data and randomly assign each data point to one of the K clusters and assign initial random centroids.Calculate the squared sum between each data point and all centroids.Reassign each data point to the closest centroid based on the computation for step 3.Reassign the centroid by calculating the mean value for every clusterRepeat steps 3, 4, 5 until we no longer have to change anything in the clusters
Assign the K number of clusters
Shuffle the data and randomly assign each data point to one of the K clusters and assign initial random centroids.
Calculate the squared sum between each data point and all centroids.
Reassign each data point to the closest centroid based on the computation for step 3.
Reassign the centroid by calculating the mean value for every cluster
Repeat steps 3, 4, 5 until we no longer have to change anything in the clusters
The time needed to run the K-Means Clustering algorithm depends on the size of the dataset, the K number we define and the patterns in the data.
We are going to use the Sckikit-Learn Python library to run a K-Means Clustering algorithm on a small dataset.
The data consists of 3 texts about London, Paris and Berlin. We are going to extract the summary sections of the Wikipedia articles about these 3 cities and run them throught our clustering algorithm.
We will then provide 3 new sentences of our own and check if they are correctly assigned to individual clusters. If that happens, then we will know our clustering algorithm worked.
First let’s install our dependencies.
# Sklearn library for our clusterpip3 install scikit-learn# We will use nltk(Natural Language Toolkit) to remove stopwords from the textpip3 install nltk# We will use the wikipedia library to download our texts from the Wikipedia pagespip3 install wikipedia
Now let's define a small class to help use gather the texts from the Wikipedia pages. We will store the text into 3 files on our local so that we don't download the texts again everytime we run the algorithm. Use class as it is right now for your first run of the algorithm and for a second run you can comment lines 8-12 and uncomment lines 13-15.
import wikipediaclass TextFetcher: def __init__(self, title): self.title = title page = wikipedia.page(title) # 8 f = open(title + ".txt", "w") # 9 f.write(page.summary) # 10 f.close() # 11 self.text = page.summary # 12 #f = open(title + ".txt", "r") #self.text = f.read() #f.close() def getText(self): return self.text
Now let’s build the dataset. We will take the text about each city and remove stopwords. Stopwords are words we usually filter out before each text processing task. They are very common words in the English language which do not bring any value, any meaning to a text. Because most of them are used everywhere, they will prevent us from clustering our texts correctly.
from text_fetcher import TextFetcherfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizefrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansimport nltkdef preprocessor(text): nltk.download('stopwords') tokens = word_tokenize(text) return (" ").join([word for word in tokens if word not in stopwords.words()])if __name__ == "__main__": textFetcher = TextFetcher("London") text1 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("Paris") text2 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("Berlin") text3 = preprocessor(textFetcher.getText()) docs = [text1, text2, text3]
It’s a known fact that computers are tipically very bad at understanding text, but they are perform way better at working with numbers. Because our dataset is made out of words, we need to transform the words into numbers.
Word embeddings or word vectorization represent a collection of techniques used to assign a word to a vector of real numbers that can be used by Machine Learning for certain purposes, one of which is text clustering.
The Scikit-Learn library contains a few word vectorizers, but for this article we are going to choose the TfidfVectorizer.
tfidf_vectorizer = TfidfVectorizer()tfidf = tfidf_vectorizer.fit_transform(docs)
Now it's time to apply our K-Means cluster algorithm. We are lucky that the Scikit-Learn has a very good implementation of the K-Means algorithm and we are going to use that. Because we know that we want to classify our texts into 3 categories(one for each city) we will define the K value to be 3.
kmeans = KMeans(n_clusters=3).fit(tfidf)print (kmeans)# Output: [0 1 2]
I know, it’s that simple! Now what does our output mean? Simply put, those 3 values are our 3 clusters.
To test them, we can now provide 3 texts about which we know for sure they should be in different clusters and see if they are assigned correctly. We have to make sure we don’t forget to also vectorize these 3 texts so that our algorithm can understand them.
test = ["This is one is about London.", "London is a beautiful city", "I love London"] results = kmeans.predict(tfidf_vectorizer.transform(test)) print (results) # Prints [0, 0, 0] test = ["This is one is about Paris.", "Paris is a beautiful city", "I love Paris"] results = kmeans.predict(tfidf_vectorizer.transform(test)) print (results) # Prints [2, 2, 2] test = ["This is one is about Berlin.", "Berlin is a beautiful city", "I love Berlin"] results = kmeans.predict(tfidf_vectorizer.transform(test)) print(results) # Prints [1, 1, 1] test = ["This is about London", "This is about Paris", "This is about Vienna"] results = kmeans.predict(tfidf_vectorizer.transform(test)) print (results) # Prints [0, 2, 1]
And it seems our clustering worked! Now let’s suppose we would get another text about which we don’t know anything. We can pass that text through our classifier and see in which category it fits. I see this as a very good and efficient text classifier.
Today we discussed the K-Means Clustering algorithm. We first went through a general overview about Clustering algorithms and Unsupervised Machine Learning techniques, then we discussed the K-Means Algorithm and we implemented it using the Scikit-Learn Python library.
This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind.
Thank you so much for reading this! Interested in more stories like this? Follow me on Twitter at @b_dmarius and I’ll post there every new article. | [
{
"code": null,
"e": 443,
"s": 47,
"text": "K-Means clustering is one of the most powerful clustering algorithms in the Data Science and Machine Learning world. It is very simple, yet it delivers wonderful results. And because clustering is a very important step for understanding a dataset, in this ... |
React Native - Images | In this chapter, we will understand how to work with images in React Native.
Let us create a new folder img inside the src folder. We will add our image (myImage.png) inside this folder.
We will show images on the home screen.
import React from 'react';
import ImagesExample from './ImagesExample.js'
const App = () => {
return (
<ImagesExample />
)
}
export default App
Local image can be accessed using the following syntax.
import React, { Component } from 'react'
import { Image } from 'react-native'
const ImagesExample = () => (
<Image source = {require('C:/Users/Tutorialspoint/Desktop/NativeReactSample/logo.png')} />
)
export default ImagesExample
React Native offers a way to optimize images for different devices using @2x, @3x suffix. The app will load only the image necessary for particular screen density.
The following will be the names of the image inside the img folder.
my-image@2x.jpg
my-image@3x.jpg
When using network images, instead of require, we need the source property. It is recommended to define the width and the height for network images.
import React from 'react';
import ImagesExample from './image_example.js'
const App = () => {
return (
<ImagesExample />
)
}
export default App
import React, { Component } from 'react'
import { View, Image } from 'react-native'
const ImagesExample = () => (
<Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
style = {{ width: 200, height: 200 }}
/>
)
export default ImagesExample
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2421,
"s": 2344,
"text": "In this chapter, we will understand how to work with images in React Native."
},
{
"code": null,
"e": 2531,
"s": 2421,
"text": "Let us create a new folder img inside the src folder. We will add our image (myImage.png) inside this fol... |
Fine-tune GPT2 for Text Generation Using Pytorch | Towards Data Science | The past few years have been especially booming in the world of NLP. This is mainly due to one of the most important breakthroughs of NLP in the modern decade — Transformers. If you haven’t read my previous article on BERT for text classification, go ahead and take a look! Another popular transformer that we will talk about today is GPT2. Developed by OpenAI, GPT2 is a large-scale transformer-based language model that is pre-trained on a large corpus of text: 8 million high-quality webpages. It results in competitive performance on multiple language tasks using only the pre-trained knowledge without explicitly training on them. GPT2 is really useful for language generation tasks as it is an autoregressive language model.
Here in today’s article, we will dive deeply into how to implement another popular transformer, GPT2, to write interesting and creative stories! Specifically, we will test the ability of GPT2 to write creative book summaries using the CMU Books Summary Dataset. We will be using the Huggingface repository for building our model and generating the texts.
The entire codebase for this article can be viewed here.
Before building the model, we need to download and preprocess the dataset first.
We are using The CMU Books Summary Dataset, which contains 16,559 books extracted from Wikipedia along with the metadata including title, author, publication date, genres, and plot summary. Download the dataset here. Here is what the dataset looks like:
For data preprocessing, we first split the entire dataset into the train, validation, and test datasets with the train-valid-test ratio: 70–20–10. We add a bos token <BOS> to the start of each summary and eos token <EOS> to the end of each summary for later training purposes. We finally save the summaries into .txt files, getting train.txt, valid.txt, test.txt.
You can get the preprocessing notebook here.
To build and train GPT2, we need to install the Huggingface library, as well as its repository.
Install Huggingface library:
pip install transformers
Clone Huggingface repo:
git clone github.com/huggingface/transformers
If you want to see visualizations of your model and hyperparameters during training, you can also choose to install tensorboard or wandb:
pip install tensorboardpip install wandb; wandb login
Before training, we should set the bos token and eos token as defined earlier in our datasets.
We should also set the pad token because we will be using LineByLineDataset, which will essentially treat each line in the dataset as distinct examples. In transformers/example/language-modeling/run-language-modelling.py, we should append the following code for the model before training:
special_tokens_dict = {'bos_token': '<BOS>', 'eos_token': '<EOS>', 'pad_token': '<PAD>'}num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)model.resize_token_embeddings(len(tokenizer))
After running this code, the special tokens will be added to the tokenizer and the model will resize its embedding to fit with the modified tokenizer.
For training, we define some parameters first and then run the language modeling script:
cd transformers/example/language-modelingN=gpu_numOUTPUT_DIR=/path/to/modelTRAIN_FILE=/path/to/dataset/train.txtVALID_FILE=/path/to/dataset/valid.txtCUDA_VISIBLE_DEVICES=$N python run_language_modeling.py \--output_dir=$OUTPUT_DIR \--model_type=gpt2 \--model_name_or_path=gpt2 \--do_train \--train_data_file=$TRAIN_FILE \--do_eval \--eval_data_file=$VALID_FILE \--per_device_train_batch_size=2 \--per_device_eval_batch_size=2 \--line_by_line \--evaluate_during_training \--learning_rate 5e-5 \--num_train_epochs=5
We set per_device_train_batch_size=2 and per_device_eval_batch_size=2 because of the GPU constraints. Feel free to use a batch size that fits your GPU. We use line_by_line, which tells our model to treat each line in our dataset as an individual example, as explained earlier. Evaluate_during_training runs evaluation on the evaluation dataset after each logging_steps, which is defaulted to 500.
In case you want to continue training from the last checkpoint, you can run:
CUDA_VISIBLE_DEVICES=$N python run_language_modeling.py \--output_dir=$OUTPUT_DIR \--model_type=gpt2 \--model_name_or_path=$OUTPUT_DIR \--do_train \--train_data_file=$TRAIN_FILE \--do_eval \--eval_data_file=$VALID_FILE \--per_device_train_batch_size=2 \--per_device_eval_batch_size=2 \--line_by_line \--evaluate_during_training \--learning_rate 5e-5 \--num_train_epochs=5 \--overwrite_output_dir
This step is optional depending on whether you want to evaluate the performance of your trained GPT2. You can do this by evaluating perplexity on the test dataset.
TEST_FILE=/path/to/dataset/test.txtCUDA_VISIBLE_DEVICES=$N python run_language_modeling.py \--output_dir=$OUTPUT_DIR \--model_type=gpt2 \--model_name_or_path=$OUTPUT_DIR \--do_eval \--eval_data_file=$TEST_FILE \--per_device_eval_batch_size=2 \--line_by_line
Here, in my case, we attained a loss of 2.46 and a perplexity of 11.70 after training for 5 epochs:
Before generating texts using our trained model, we first enable special tokens in our prompt by setting add_special_tokens=True in the transformers/examples/text-generation/run_generation.py:
encoded_prompt = tokenizer.encode(prompt_text, add_special_tokens=True, return_tensors=”pt”)
Then, we are ready to generate some text! Start generating by:
cd transformers/examples/text-generationK=k_for_top-k_sampling_decoderCUDA_VISIBLE_DEVICES=$N python run_generation.py \--model_type gpt2 \--model_name_or_path $OUTPUT_DIR \--length 300 \--prompt "<BOS>" \--stop_token "<EOS>" \--k $K \--num_return_sequences 5
We feed in the prompt “<BOS>” as the input, which represents the beginning of each example and stops the model from generating once the “<EOS>” token is generated. This way, our GPT2 will learn to generate a full example of the summary from the beginning to the end, leveraging what it learned of the bos token and eos token during training. In addition, we are using the top-k sampling decoder which has been proven to be very effective in generating irrepetitive and better texts. k=50 is a good value to start off with. Huggingface also supports other decoding methods, including greedy search, beam search, and top-p sampling decoder. For more information, look into the docstring of model.generate.
Here are a few examples of the generated texts with k=50.
The protagonist is an Englishman, William Lark, who has been sent on an adventure with the British Government on a mission to the Arctic. The novel tells the story of how his friends and family are being sold into slavery in the small Norwegian town of Shok...
A new world is awakening, and the humans of the planet Vorta must work together to save it from destruction. The New Earth is now populated by three species. The first are the humans who are a bit older, the second are the Vorta, and the third are the humans with dark blue eyes...
The novel begins in the year 2143, when a group of “dungeons”, or witches, decide to break the spell that prevents the power of the dead by consuming the souls of those who died to them. They use the bodies to help the dying, as well as to raise the dead themselves...
You can see more generated examples here.
In this article, we showed how to implement one of the most popular transformer models, GPT2, to create interesting texts. GPT2’s large-scale pre-trained dataset and architecture allows it to produce coherent and fluent pieces of writing. Although GPT2’s texts are still distinguishable from those written by humans, this is proof that creativity by machines is only going upwards from now. For more info, you can take a look at the official paper or OpenAI’s blog on GPT2.
This article only showed how to generate text that is determined by AI. If you are wondering whether it’s possible to control the text being generated (and it’s possible!), take a read at the following article I wrote 😊.
towardsdatascience.com
[1] A. Vaswani, N. Shazeer, N. Parmar, etc., Attention Is All You Need (2017), 31st Conference on Neural Information Processing Systems
[2] A. Radford, J. Wu, R. Child, etc., Language Models are Unsupervised Multitask Learners (2019), OpenAI | [
{
"code": null,
"e": 903,
"s": 172,
"text": "The past few years have been especially booming in the world of NLP. This is mainly due to one of the most important breakthroughs of NLP in the modern decade — Transformers. If you haven’t read my previous article on BERT for text classification, go ahea... |
How can I check the version of MySQL Server? | With the help of ‘mysqladmin’ program we would be able to know about the version of our MySQL server. To get the version we should have to write the following command on command line −
C:\mysql\bin>mysqladmin -u root version
mysqladmin Ver 8.42 Distrib 5.7.20, for Win64 on x86_64
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Server version 5.7.20
Protocol version 10
Connection localhost via TCP/IP
TCP port 3306
Uptime: 12 min 54 sec
Threads: 1 Questions: 5 Slow queries: 0 Opens: 105 Flush tables: 1 Open tables: 98 Queries per second avg: 0.0060 | [
{
"code": null,
"e": 1247,
"s": 1062,
"text": "With the help of ‘mysqladmin’ program we would be able to know about the version of our MySQL server. To get the version we should have to write the following command on command line −"
},
{
"code": null,
"e": 1825,
"s": 1247,
"text"... |
Basic Calculator Program Using Java - GeeksforGeeks | 17 Nov, 2020
Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input.
Example :
Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0
Approach Used:
Take two numbers using the Scanner class. The switch case branching is used to execute a particular section.
Using a switch case to evaluate respective operations.
Java
// Java program for simple calculator import java.io.*;import java.lang.*;import java.lang.Math;import java.util.Scanner;public class BasicCalculator { public static void main(String[] args) { // stores two numbers double num1, num2; // Take input from the user Scanner sc = new Scanner(System.in); System.out.println("Enter the numbers"); // take the inputs num1 = sc.nextDouble(); num2 = sc.nextDouble(); System.out.println("Enter the operator (+,-,*,/)"); char op = sc.next().charAt(0); double o = 0; switch (op) { // case to add two numbers case '+': o = num1 + num2; break; // case to subtract two numbers case '-': o = num1 - num2; break; // case to multiply two numbers case '*': o = num1 * num2; break; // case to divide two numbers case '/': o = num1 / num2; break; default: System.out.println("You enter wrong input"); break; } System.out.println("The final result:"); System.out.println(); // print the final result System.out.println(num1 + " " + op + " " + num2 + " = " + o); }}
Output:
Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0
Time Complexity: O(1)
Auxiliary Space: O(1)
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23974,
"s": 23946,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 24133,
"s": 23974,
"text": "Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input."
}... |
Java - Loop Control | There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
Java programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Like a while statement, except that it tests the condition at the end of the loop body.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their detail.
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This will produce the following result −
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,
In the following chapter, we will be learning about decision making statements in Java programming.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2606,
"s": 2377,
"text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": nu... |
AngularJS - Services | AngularJS supports the concept of Separation of Concerns using services architecture. Services are JavaScript functions, which are responsible to perform only specific tasks. This makes them individual entities which are maintainable and testable. The controllers and filters can call them on requirement basis. Services are normally injected using the dependency injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location, etc. Each service is responsible for a specific task such as the $http is used to make ajax call to get the server data, the $route is used to define the routing information, and so on. The inbuilt services are always prefixed with $ symbol.
There are two ways to create a service −
Factory
Service
In this method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
In this method, we define a service and then assign method to it. We also inject an already available service to it.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
The following example shows use of all the above mentioned directives −
<html>
<head>
<title>Angular JS Services</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService) {
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
Enter a number:
X2
Result: {{result}}
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3097,
"s": 2699,
"text": "AngularJS supports the concept of Separation of Concerns using services architecture. Services are JavaScript functions, which are responsible to perform only specific tasks. This makes them individual entities which are maintainable and testable. The c... |
10 Examples to Master Python Pathlib | by Soner Yıldırım | Towards Data Science | The pathlib module of Python makes it very easy and efficient to deal with file paths.
The os.path module can also be used to handle path name operations. The difference is that path module creates strings that represent file paths whereas pathlib creates a path object.
One important advantage of using path objects instead of a string is that we can call methods on a path object. Pathlib module provides many useful methods as we will see in the examples.
In this article, we will go through 10 examples to master how to use the pathlib module.
Let’s start with importing pathlib and create a path object.
import pathlibpathlib.Path()PosixPath('.') #relative path to the current folder
If we call the Path method with no arguments, it will create a relative path to the folder we are currently working in. The paths can be described as relative or absolute.
Relative path: The path relative to the folder we are currently working in.
Absolute path: The path that is relative to the operating system
In order to make the distinction more clear, I will also create the absolute path to the folder I’m currently working in:
PosixPath('.') #relative pathPosixPath('/home/soner/Desktop/data') #absolute path
We can call the path method by passing the folder and file names as separate strings. I’m currently running the examples on a jupyter notebook which is saved in a folder named “data”. There is a “names” folder in the “data” folder and inside the “names”, I have a file called “file1.json”.
I will create a path object that represents the relative path to this file.
p = pathlib.Path("names", "file1.json")pPosixPath('names/file1.json')
In some cases, we may need to use the absolute path instead of the relative path. The resolve method is used to convert a relative path to an absolute path.
We can call it on the path object we previously created.
p.resolve()PosixPath('/home/soner/Desktop/data/names/file1.json')
The returned path is the absolute path of file1. Another way to convert a relative path to an absolute path is through the absolute method.
p.absolute()PosixPath('/home/soner/Desktop/data/names/file1.json')
The pathlib module has a method that can be used to read the text inside the file.
p.read_text()'{\n "John": 1,\n "Jane": 2\n}'
We can see the content of file1.json but the format is not nice and clean. The json module can be used together with the pathlib to make things better.
import jsonjson.loads(p.read_text()){'John': 1, 'Jane': 2}
We can create a path that is relative to another path.
p1 = pathlib.Path("names", "file1.json")p2 = pathlib.Path("names")p_relative = p1.relative_to(p2)p_relativePosixPath('file1.json')
The p_relative is the relative path of p2 (names folder) to p1 (file1 inside the names folder). It can also be considered as an absolute path based on another path (not the operating system).
We can use the samefile method to compare if two paths represent the same files. The paths can be relative or absolute.
Consider the following two paths.
p1 = pathlib.Path("names", "file1.json")p2 = p1.resolve()
The p2 is the absolute path version of the p1. Let’s compare them using the samefile method.
p1.samefile(p2)True
We can check if a path represents a file or a directory. The methods are, not surprisingly, is_file and is_dir.
p1.is_dir()Falsep1.is_file()True
The path p1 represents a json file so is_file returns True.
The pathlib module can also be used to move files.
I have file1.json stores in the data folder.
p = pathlib.Path("names", "file1.json")
I want to move file1 into the id folder and rename it as file1-a. The rename method is used as follows.
p.rename(pathlib.Path("id", "file1-a.json"))
The file1 does not exist in data folder anymore. We can check it using the exists method.
pPosixPath('names/file1.json')p.exists()False
The pathlib module provides a way to create a new file and write text to it.
Let’s create a text to write to the path object.
p = pathlib.Path("id", "file1-a.json")d = json.loads(p.read_text())d{'John': 1, 'Jane': 2}
We can now create a path and call the write_text method on it.
text = json.dumps(d)pathlib.Path("id", "newfile.json").write_text(text)
The dumps method of json module converts the content of the json file to text. We pass this text to the write_text method and it is written in the newfile.json.
We can confirm it by reading the content of the newfile.json.
pathlib.Path("id", "newfile.json").read_text()'{"John": 1, "Jane": 2}'
The folder structure is hierarchical so the parent folder is one level above. We can call the parent or parents methods on paths.
The parent method will return the path that represents one level above.
pPosixPath('/home/soner/Desktop/data/names/file1.json')p.parentPosixPath('/home/soner/Desktop/data/names')
The parents return a sequence of all the parent folders.
list(p.parents)[PosixPath('/home/soner/Desktop/data/names'), PosixPath('/home/soner/Desktop/data'), PosixPath('/home/soner/Desktop'), PosixPath('/home/soner'), PosixPath('/home'), PosixPath('/')]
The pathlib module provides convenient and robust ways to deal with file paths. Pathlib creates the paths as objects so it is more preferred than the os.path module. The os.path creates paths as strings.
We have covered the most commonly used methods of the pathlib. However, there is more to it. If you’d like to read further, you can always visit the official documentation.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 259,
"s": 172,
"text": "The pathlib module of Python makes it very easy and efficient to deal with file paths."
},
{
"code": null,
"e": 443,
"s": 259,
"text": "The os.path module can also be used to handle path name operations. The difference is that path mod... |
Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap) - GeeksforGeeks | 23 Jun, 2021
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one is bigger/smaller.Examples:
Input : nuts[] = {'@', '#', '$', '%', '^', '&'}
bolts[] = {'$', '%', '&', '^', '@', '#'}
Output : Matched nuts and bolts are-
$ % & ^ @ #
$ % & ^ @ #
Another way of asking this problem is, given a box with locks and keys where one lock can be opened by one key in the box. We need to match the pair.
We have discussed a sorting based solution below post.Nuts & Bolts Problem (Lock & Key problem) | Set 1In this post, hashmap based approach is discussed.
Traverse the nuts array and create a hashmapTraverse the bolts array and search for it in hashmap.If it is found in the hashmap of nuts then this means bolts exist for that nut.
Traverse the nuts array and create a hashmap
Traverse the bolts array and search for it in hashmap.
If it is found in the hashmap of nuts then this means bolts exist for that nut.
C++
Java
Python3
C#
Javascript
// Hashmap based solution to solve#include <bits/stdc++.h>using namespace std; // function to match nuts and boltsvoid nutboltmatch(char nuts[], char bolts[], int n){ unordered_map<char, int> hash; // creating a hashmap for nuts for (int i = 0; i < n; i++) hash[nuts[i]] = i; // searching for nuts for each bolt in hash map for (int i = 0; i < n; i++) if (hash.find(bolts[i]) != hash.end()) nuts[i] = bolts[i]; // print the result cout << "matched nuts and bolts are-" << endl; for (int i = 0; i < n; i++) cout << nuts[i] << " "; cout << endl; for (int i = 0; i < n; i++) cout << bolts[i] << " ";} // Driver codeint main(){ char nuts[] = {'@', '#', '$', '%', '^', '&'}; char bolts[] = {'$', '%', '&', '^', '@', '#'}; int n = sizeof(nuts) / sizeof(nuts[0]); nutboltmatch(nuts, bolts, n); return 0;}
// Hashmap based solution to solveimport java.util.HashMap;class GFG{ // function to match nuts and bolts static void nutboltmatch(char nuts[], char bolts[], int n) { HashMap<Character, Integer> hash = new HashMap<>(); // creating a hashmap for nuts for (int i = 0; i < n; i++) hash.put(nuts[i], i); // searching for nuts for each bolt in hash map for (int i = 0; i < n; i++) if (hash.containsKey(bolts[i])) nuts[i] = bolts[i]; // print the result System.out.println("matched nuts and bolts are-"); for (int i = 0; i < n; i++) System.out.print(nuts[i] + " "); System.out.println(); for (int i = 0; i < n; i++) System.out.print(bolts[i] + " "); } // Driver code public static void main(String[] args) { char nuts[] = { '@', '#', '$', '%', '^', '&' }; char bolts[] = { '$', '%', '&', '^', '@', '#' }; int n = nuts.length; nutboltmatch(nuts, bolts, n); }} // This code is contributed by sanjeev2552
# Python3 program to implement# above approach# Hashmap based solution to# solve # Function to match nuts and# boltsdef nutboltmatch(nuts, bolts, n): hash1 = {} # creating a hashmap # for nuts for i in range(n): hash1[nuts[i]] = i # searching for nuts for # each bolt in hash map for i in range(n): if (bolts[i] in hash1): nuts[i] = bolts[i] # Print the result print("matched nuts and bolts are-") for i in range(n): print(nuts[i], end = " ") print() for i in range(n): print(bolts[i], end = " ") # Driver codeif __name__ == "__main__": nuts = ['@', '#', '$', '%', '^', '&'] bolts = ['$', '%', '&', '^', '@', '#'] n = len(nuts) nutboltmatch(nuts, bolts, n) # This code is contributed by Chitranayal
// Hashmap based solution to solveusing System;using System.Collections.Generic; public class GFG{ // function to match nuts and bolts static void nutboltmatch(char[] nuts, char[] bolts, int n) { Dictionary<char,int> hash = new Dictionary<char,int>(); // creating a hashmap for nuts for (int i = 0; i < n; i++) { hash.Add(nuts[i], i); } // searching for nuts for each bolt in hash map for (int i = 0; i < n; i++) if (hash.ContainsKey(bolts[i])) nuts[i] = bolts[i]; // print the result Console.WriteLine("matched nuts and bolts are-"); for (int i = 0; i < n; i++) Console.Write(nuts[i] + " "); Console.WriteLine(); for (int i = 0; i < n; i++) Console.Write(bolts[i] + " "); } // Driver code static public void Main () { char[] nuts = { '@', '#', '$', '%', '^', '&' }; char[] bolts = { '$', '%', '&', '^', '@', '#' }; int n = nuts.Length; nutboltmatch(nuts, bolts, n); }} // This code is contributed by avanitrachhadiya2155
<script> // Hashmap based solution to solve // function to match nuts and boltsfunction nutboltmatch(nuts, bolts, n) { let hash = new Map(); // creating a hashmap for nuts for (let i = 0; i < n; i++) hash.set(nuts[i], i); // searching for nuts for each bolt in hash map for (let i = 0; i < n; i++) if (hash.has(bolts[i])) nuts[i] = bolts[i]; // print the result document.write("matched nuts and bolts are-<br>"); for (let i = 0; i < n; i++) document.write(nuts[i] + " "); document.write("<br>"); for (let i = 0; i < n; i++) document.write(bolts[i] + " ");} // Driver code let nuts = ['@', '#', '$', '%', '^', '&'];let bolts = ['$', '%', '&', '^', '@', '#'];let n = nuts.length;nutboltmatch(nuts, bolts, n); </script>
Output:
matched nuts and bolts are-
$ % & ^ @ #
$ % & ^ @ #
The time complexity for this solution is O(n).This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
sanjeev2552
avanitrachhadiya2155
gfgking
Adobe
Amazon
Hike
MakeMyTrip
MAQ Software
Arrays
Hash
Amazon
Hike
MakeMyTrip
MAQ Software
Adobe
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum | [
{
"code": null,
"e": 24128,
"s": 24100,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 24506,
"s": 24128,
"text": "Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Const... |
Python - Tuples | A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.
#!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;
Note − an exception raised, this is because after del tup tuple does not exist anymore.
Note − an exception raised, this is because after del tup tuple does not exist anymore.
This produces the following result −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter.
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": 2568,
"s": 2327,
"text": "A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets."
},
{
... |
Biopython - Overview of BLAST | BLAST stands for Basic Local Alignment Search Tool. It finds regions of similarity between biological sequences. Biopython provides Bio.Blast module to deal with NCBI BLAST operation. You can run BLAST in either local connection or over Internet connection.
Let us understand these two connections in brief in the following section −
Biopython provides Bio.Blast.NCBIWWW module to call the online version of BLAST. To do this, we need to import the following module −
>>> from Bio.Blast import NCBIWWW
NCBIWW module provides qblast function to query the BLAST online version, https://blast.ncbi.nlm.nih.gov/Blast.cgi. qblast supports all the parameters supported by the online version.
To obtain any help about this module, use the below command and understand the features −
>>> help(NCBIWWW.qblast)
Help on function qblast in module Bio.Blast.NCBIWWW:
qblast(
program, database, sequence,
url_base = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi',
auto_format = None,
composition_based_statistics = None,
db_genetic_code = None,
endpoints = None,
entrez_query = '(none)',
expect = 10.0,
filter = None,
gapcosts = None,
genetic_code = None,
hitlist_size = 50,
i_thresh = None,
layout = None,
lcase_mask = None,
matrix_name = None,
nucl_penalty = None,
nucl_reward = None,
other_advanced = None,
perc_ident = None,
phi_pattern = None,
query_file = None,
query_believe_defline = None,
query_from = None,
query_to = None,
searchsp_eff = None,
service = None,
threshold = None,
ungapped_alignment = None,
word_size = None,
alignments = 500,
alignment_view = None,
descriptions = 500,
entrez_links_new_window = None,
expect_low = None,
expect_high = None,
format_entrez_query = None,
format_object = None,
format_type = 'XML',
ncbi_gi = None,
results_file = None,
show_overview = None,
megablast = None,
template_type = None,
template_length = None
)
BLAST search using NCBI's QBLAST server or a cloud service provider.
Supports all parameters of the qblast API for Put and Get.
Please note that BLAST on the cloud supports the NCBI-BLAST Common
URL API (http://ncbi.github.io/blast-cloud/dev/api.html).
To use this feature, please set url_base to 'http://host.my.cloud.service.provider.com/cgi-bin/blast.cgi' and
format_object = 'Alignment'. For more details, please see 8. Biopython – Overview of BLAST
https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE = BlastDocs&DOC_TYPE = CloudBlast
Some useful parameters:
- program blastn, blastp, blastx, tblastn, or tblastx (lower case)
- database Which database to search against (e.g. "nr").
- sequence The sequence to search.
- ncbi_gi TRUE/FALSE whether to give 'gi' identifier.
- descriptions Number of descriptions to show. Def 500.
- alignments Number of alignments to show. Def 500.
- expect An expect value cutoff. Def 10.0.
- matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45).
- filter "none" turns off filtering. Default no filtering
- format_type "HTML", "Text", "ASN.1", or "XML". Def. "XML".
- entrez_query Entrez query to limit Blast search
- hitlist_size Number of hits to return. Default 50
- megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only)
- service plain, psi, phi, rpsblast, megablast (lower case)
This function does no checking of the validity of the parameters
and passes the values to the server as is. More help is available at:
https://ncbi.github.io/blast-cloud/dev/api.html
Usually, the arguments of the qblast function are basically analogous to different parameters that you can set on the BLAST web page. This makes the qblast function easy to understand as well as reduces the learning curve to use it.
To understand the process of connecting and searching BLAST online version, let us do a simple sequence search (available in our local sequence file) against online BLAST server through Biopython.
Step 1 − Create a file named blast_example.fasta in the Biopython directory and give the below sequence information as input
Example of a single sequence in FASTA/Pearson format:
>sequence A ggtaagtcctctagtacaaacacccccaatattgtgatataattaaaattatattcatat
tctgttgccagaaaaaacacttttaggctatattagagccatcttctttgaagcgttgtc
>sequence B ggtaagtcctctagtacaaacacccccaatattgtgatataattaaaattatattca
tattctgttgccagaaaaaacacttttaggctatattagagccatcttctttgaagcgttgtc
Step 2 − Import the NCBIWWW module.
>>> from Bio.Blast import NCBIWWW
Step 3 − Open the sequence file, blast_example.fasta using python IO module.
>>> sequence_data = open("blast_example.fasta").read()
>>> sequence_data
'Example of a single sequence in FASTA/Pearson format:\n\n\n> sequence
A\nggtaagtcctctagtacaaacacccccaatattgtgatataattaaaatt
atattcatat\ntctgttgccagaaaaaacacttttaggctatattagagccatcttctttg aagcgttgtc\n\n'
Step 4 − Now, call the qblast function passing sequence data as main parameter. The other parameter represents the database (nt) and the internal program (blastn).
>>> result_handle = NCBIWWW.qblast("blastn", "nt", sequence_data)
>>> result_handle
<_io.StringIO object at 0x000001EC9FAA4558>
blast_results holds the result of our search. It can be saved to a file for later use and also, parsed to get the details. We will learn how to do it in the coming section.
Step 5 − The same functionality can be done using Seq object as well rather than using the whole fasta file as shown below −
>>> from Bio import SeqIO
>>> seq_record = next(SeqIO.parse(open('blast_example.fasta'),'fasta'))
>>> seq_record.id
'sequence'
>>> seq_record.seq
Seq('ggtaagtcctctagtacaaacacccccaatattgtgatataattaaaattatat...gtc',
SingleLetterAlphabet())
Now, call the qblast function passing Seq object, record.seq as main parameter.
>>> result_handle = NCBIWWW.qblast("blastn", "nt", seq_record.seq)
>>> print(result_handle)
<_io.StringIO object at 0x000001EC9FAA4558>
BLAST will assign an identifier for your sequence automatically.
Step 6 − result_handle object will have the entire result and can be saved into a file for later usage.
>>> with open('results.xml', 'w') as save_file:
>>> blast_results = result_handle.read()
>>> save_file.write(blast_results)
We will see how to parse the result file in the later section.
This section explains about how to run BLAST in local system. If you run BLAST in local system, it may be faster and also allows you to create your own database to search against sequences.
In general, running BLAST locally is not recommended due to its large size, extra effort needed to run the software, and the cost involved. Online BLAST is sufficient for basic and advanced purposes. Of course, sometime you may be required to install it locally.
Consider you are conducting frequent searches online which may require a lot of time and high network volume and if you have proprietary sequence data or IP related issues, then installing it locally is recommended.
To do this, we need to follow the below steps −
Step 1 − Download and install the latest blast binary using the given link − ftp://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/LATEST/
Step 2 − Download and unpack the latest and necessary database using the below link − ftp://ftp.ncbi.nlm.nih.gov/blast/db/
BLAST software provides lot of databases in their site. Let us download alu.n.gz file from the blast database site and unpack it into alu folder. This file is in FASTA format. To use this file in our blast application, we need to first convert the file from FASTA format into blast database format. BLAST provides makeblastdb application to do this conversion.
Use the below code snippet −
cd /path/to/alu
makeblastdb -in alu.n -parse_seqids -dbtype nucl -out alun
Running the above code will parse the input file, alu.n and create BLAST database as multiple files alun.nsq, alun.nsi, etc. Now, we can query this database to find the sequence.
We have installed the BLAST in our local server and also have sample BLAST database, alun to query against it.
Step 3 − Let us create a sample sequence file to query the database. Create a file search.fsa and put the below data into it.
>gnl|alu|Z15030_HSAL001056 (Alu-J)
AGGCTGGCACTGTGGCTCATGCTGAAATCCCAGCACGGCGGAGGACGGCGGAAGATTGCT
TGAGCCTAGGAGTTTGCGACCAGCCTGGGTGACATAGGGAGATGCCTGTCTCTACGCAAA
AGAAAAAAAAAATAGCTCTGCTGGTGGTGCATGCCTATAGTCTCAGCTATCAGGAGGCTG
GGACAGGAGGATCACTTGGGCCCGGGAGTTGAGGCTGTGGTGAGCCACGATCACACCACT
GCACTCCAGCCTGGGTGACAGAGCAAGACCCTGTCTCAAAACAAACAAATAA
>gnl|alu|D00596_HSAL003180 (Alu-Sx)
AGCCAGGTGTGGTGGCTCACGCCTGTAATCCCACCGCTTTGGGAGGCTGAGTCAGATCAC
CTGAGGTTAGGAATTTGGGACCAGCCTGGCCAACATGGCGACACCCCAGTCTCTACTAAT
AACACAAAAAATTAGCCAGGTGTGCTGGTGCATGTCTGTAATCCCAGCTACTCAGGAGGC
TGAGGCATGAGAATTGCTCACGAGGCGGAGGTTGTAGTGAGCTGAGATCGTGGCACTGTA
CTCCAGCCTGGCGACAGAGGGAGAACCCATGTCAAAAACAAAAAAAGACACCACCAAAGG
TCAAAGCATA
>gnl|alu|X55502_HSAL000745 (Alu-J)
TGCCTTCCCCATCTGTAATTCTGGCACTTGGGGAGTCCAAGGCAGGATGATCACTTATGC
CCAAGGAATTTGAGTACCAAGCCTGGGCAATATAACAAGGCCCTGTTTCTACAAAAACTT
TAAACAATTAGCCAGGTGTGGTGGTGCGTGCCTGTGTCCAGCTACTCAGGAAGCTGAGGC
AAGAGCTTGAGGCTACAGTGAGCTGTGTTCCACCATGGTGCTCCAGCCTGGGTGACAGGG
CAAGACCCTGTCAAAAGAAAGGAAGAAAGAACGGAAGGAAAGAAGGAAAGAAACAAGGAG
AG
The sequence data are gathered from the alu.n file; hence, it matches with our database.
Step 4 − BLAST software provides many applications to search the database and we use blastn. blastn application requires minimum of three arguments, db, query and out. db refers to the database against to search; query is the sequence to match and out is the file to store results. Now, run the below command to perform this simple query −
blastn -db alun -query search.fsa -out results.xml -outfmt 5
Running the above command will search and give output in the results.xml file as given below (partially data) −
<?xml version = "1.0"?>
<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN"
"http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">
<BlastOutput>
<BlastOutput_program>blastn</BlastOutput_program>
<BlastOutput_version>BLASTN 2.7.1+</BlastOutput_version>
<BlastOutput_reference>Zheng Zhang, Scott Schwartz, Lukas Wagner, and Webb
Miller (2000), "A greedy algorithm for aligning DNA sequences", J
Comput Biol 2000; 7(1-2):203-14.
</BlastOutput_reference>
<BlastOutput_db>alun</BlastOutput_db>
<BlastOutput_query-ID>Query_1</BlastOutput_query-ID>
<BlastOutput_query-def>gnl|alu|Z15030_HSAL001056 (Alu-J)</BlastOutput_query-def>
<BlastOutput_query-len>292</BlastOutput_query-len>
<BlastOutput_param>
<Parameters>
<Parameters_expect>10</Parameters_expect>
<Parameters_sc-match>1</Parameters_sc-match>
<Parameters_sc-mismatch>-2</Parameters_sc-mismatch>
<Parameters_gap-open>0</Parameters_gap-open>
<Parameters_gap-extend>0</Parameters_gap-extend>
<Parameters_filter>L;m;</Parameters_filter>
</Parameters>
</BlastOutput_param>
<BlastOutput_iterations>
<Iteration>
<Iteration_iter-num>1</Iteration_iter-num><Iteration_query-ID>Query_1</Iteration_query-ID>
<Iteration_query-def>gnl|alu|Z15030_HSAL001056 (Alu-J)</Iteration_query-def>
<Iteration_query-len>292</Iteration_query-len>
<Iteration_hits>
<Hit>
<Hit_num>1</Hit_num>
<Hit_id>gnl|alu|Z15030_HSAL001056</Hit_id>
<Hit_def>(Alu-J)</Hit_def>
<Hit_accession>Z15030_HSAL001056</Hit_accession>
<Hit_len>292</Hit_len>
<Hit_hsps>
<Hsp>
<Hsp_num>1</Hsp_num>
<Hsp_bit-score>540.342</Hsp_bit-score>
<Hsp_score>292</Hsp_score>
<Hsp_evalue>4.55414e-156</Hsp_evalue>
<Hsp_query-from>1</Hsp_query-from>
<Hsp_query-to>292</Hsp_query-to>
<Hsp_hit-from>1</Hsp_hit-from>
<Hsp_hit-to>292</Hsp_hit-to>
<Hsp_query-frame>1</Hsp_query-frame>
<Hsp_hit-frame>1</Hsp_hit-frame>
<Hsp_identity>292</Hsp_identity>
<Hsp_positive>292</Hsp_positive>
<Hsp_gaps>0</Hsp_gaps>
<Hsp_align-len>292</Hsp_align-len>
<Hsp_qseq>
AGGCTGGCACTGTGGCTCATGCTGAAATCCCAGCACGGCGGAGGACGGCGGAAGATTGCTTGAGCCTAGGAGTTTG
CGACCAGCCTGGGTGACATAGGGAGATGCCTGTCTCTACGCAAAAGAAAAAAAAAATAGCTCTGCTGGTGGTGCATG
CCTATAGTCTCAGCTATCAGGAGGCTGGGACAGGAGGATCACTTGGGCCCGGGAGTTGAGGCTGTGGTGAGCC
ACGATCACACCACTGCACTCCAGCCTGGGTGACAGAGCAAGACCCTGTCTCAAAACAAACAAATAA
</Hsp_qseq>
<Hsp_hseq>
AGGCTGGCACTGTGGCTCATGCTGAAATCCCAGCACGGCGGAGGACGGCGGAAGATTGCTTGAGCCTAGGA
GTTTGCGACCAGCCTGGGTGACATAGGGAGATGCCTGTCTCTACGCAAAAGAAAAAAAAAATAGCTCTGCT
GGTGGTGCATGCCTATAGTCTCAGCTATCAGGAGGCTGGGACAGGAGGATCACTTGGGCCCGGGAGTTGAGG
CTGTGGTGAGCCACGATCACACCACTGCACTCCAGCCTGGGTGACAGAGCAAGACCCTGTCTCAAAACAAAC
AAATAA
</Hsp_hseq>
<Hsp_midline>
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||
</Hsp_midline>
</Hsp>
</Hit_hsps>
</Hit>
.........................
.........................
.........................
</Iteration_hits>
<Iteration_stat>
<Statistics>
<Statistics_db-num>327</Statistics_db-num>
<Statistics_db-len>80506</Statistics_db-len>
<Statistics_hsp-lenv16</Statistics_hsp-len>
<Statistics_eff-space>21528364</Statistics_eff-space>
<Statistics_kappa>0.46</Statistics_kappa>
<Statistics_lambda>1.28</Statistics_lambda>
<Statistics_entropy>0.85</Statistics_entropy>
</Statistics>
</Iteration_stat>
</Iteration>
</BlastOutput_iterations>
</BlastOutput>
The above command can be run inside the python using the below code −
>>> from Bio.Blast.Applications import NcbiblastnCommandline
>>> blastn_cline = NcbiblastnCommandline(query = "search.fasta", db = "alun",
outfmt = 5, out = "results.xml")
>>> stdout, stderr = blastn_cline()
Here, the first one is a handle to the blast output and second one is the possible error output generated by the blast command.
Since we have provided the output file as command line argument (out = “results.xml”) and sets the output format as XML (outfmt = 5), the output file will be saved in the current working directory.
Generally, BLAST output is parsed as XML format using the NCBIXML module. To do this, we need to import the following module −
>>> from Bio.Blast import NCBIXML
Now, open the file directly using python open method and use NCBIXML parse method as given below −
>>> E_VALUE_THRESH = 1e-20
>>> for record in NCBIXML.parse(open("results.xml")):
>>> if record.alignments:
>>> print("\n")
>>> print("query: %s" % record.query[:100])
>>> for align in record.alignments:
>>> for hsp in align.hsps:
>>> if hsp.expect < E_VALUE_THRESH:
>>> print("match: %s " % align.title[:100])
This will produce an output as follows −
query: gnl|alu|Z15030_HSAL001056 (Alu-J)
match: gnl|alu|Z15030_HSAL001056 (Alu-J)
match: gnl|alu|L12964_HSAL003860 (Alu-J)
match: gnl|alu|L13042_HSAL003863 (Alu-FLA?)
match: gnl|alu|M86249_HSAL001462 (Alu-FLA?)
match: gnl|alu|M29484_HSAL002265 (Alu-J)
query: gnl|alu|D00596_HSAL003180 (Alu-Sx)
match: gnl|alu|D00596_HSAL003180 (Alu-Sx)
match: gnl|alu|J03071_HSAL001860 (Alu-J)
match: gnl|alu|X72409_HSAL005025 (Alu-Sx)
query: gnl|alu|X55502_HSAL000745 (Alu-J)
match: gnl|alu|X55502_HSAL000745 (Alu-J)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2364,
"s": 2106,
"text": "BLAST stands for Basic Local Alignment Search Tool. It finds regions of similarity between biological sequences. Biopython provides Bio.Blast module to deal with NCBI BLAST operation. You can run BLAST in either local connection or over Internet connect... |
How to Retrieve Image from Firebase in Realtime in Android? - GeeksforGeeks | 29 Dec, 2020
When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get directly into our app. But what if we want to change that image and instead of that image we want to insert the new one then for doing this we have to do change in our code but here our solution comes we can get that image in realtime in our app using realtime database then we can change that image from firebase and in realtime, our app image will also change we don’t have to do changes in our code. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to firebase
In the android studio, go to the Tools option in the topmost bar then click on the firebase option then click the connect to firebase button. Refer to know how to connect the app to firebase.
Step 3: Add dependency to build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.google.firebase:firebase-database:19.6.0’
implementation ‘com.squareup.picasso:picasso:2.71828’
Now sync the project from the top right corner option of Sync now.
Step 4: Add Internet permission in AndroidManifest.xml file
Navigate to the AndroidManifest.xml file and add the below permission for getting internet permission in the app.
<uses-permission android:name=”android.permission.INTERNET”/>
Step 5: Add image on firebase storage and copy the link of that image
In firebase go to the storage option then click on Get Started button
After that click on the Upload file option to insert an image on firebase storage.
After that click on the image inserted then the image details come in the right section then click on the access token and copy the image URL.
Step 6: Add that image URL to the Realtime database
Go to the Realtime database option then click on the create database button.
After clicking on the getting started button select the option locked mode for database security rule. After that click on the + option to create a child node for the database.
After that name, that child node and insert the image URL in the value section then click on the Add button.
Then go to the rule section because we created this database in locked mode but we have to read the database in our app. In the rule section go to the read section row and change that from false to true.
Step 7: Working with the activity_main.xml and MainActivity.java file
Go to the activity_main.xml and MainActivity.java file and refer to the following code. Below is the code for activity.main.xml and MainActivity.java file.
XML
Java
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!-- we are using ImageView for displaying image--> <ImageView android:id="@+id/rImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" /> </LinearLayout>
import android.os.Bundle;import android.widget.ImageView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener;import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { // Initializing the ImageView ImageView rImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getting ImageView by its id rImage = findViewById(R.id.rImage); // we will get the default FirebaseDatabase instance FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); // we will get a DatabaseReference for the database root node DatabaseReference databaseReference = firebaseDatabase.getReference(); // Here "image" is the child node value we are getting // child node data in the getImage variable DatabaseReference getImage = databaseReference.child("image"); // Adding listener for a single change // in the data at this location. // this listener will triggered once // with the value of the data at the location getImage.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // getting a DataSnapshot for the location at the specified // relative path and getting in the link variable String link = dataSnapshot.getValue(String.class); // loading that data into rImage // variable which is ImageView Picasso.get().load(link).into(rImage); } // this will called when any problem // occurs in getting data @Override public void onCancelled(@NonNull DatabaseError databaseError) { // we are showing that error message in toast Toast.makeText(MainActivity.this, "Error Loading Image", Toast.LENGTH_SHORT).show(); } }); }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Flutter - Custom Bottom Navigation Bar
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 25565,
"s": 25537,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 26325,
"s": 25565,
"text": "When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will beco... |
Geolocation watchPosition() API | The watchPosition method retrieves periodic updates about the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.
The location information is returned in a Position object. Each update returns a new Position object.
Here is the syntax of this method −
watchPosition(showLocation, ErrorHandler, options);
Here is the detail of parameters −
showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information.
showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information.
ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information.
ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information.
options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information.
options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information.
The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.
<!DOCTYPE HTML>
<head>
<html>
<script type = "text/javascript">
var watchID;
var geoLoc;
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
} else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
} else {
alert("Sorry, browser does not support geolocation!");
}
}
</script>
</head>
<body>
<form>
<input type = "button" onclick = "getLocationUpdate();" value = "Watch Update"/>
</form>
</body>
</html>
This will produce following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2825,
"s": 2608,
"text": "The watchPosition method retrieves periodic updates about the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed."
},
{
"code": null,
"e":... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.