title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
ddrescue - Unix, Linux Command
|
ddrescue - Data recovery tool, save data from a crashed partition.
ddrescue [options] infile outfile [logfile]
GNU ddrescue is a data recovery tool. It copies data from one file or block device (hard disc, cdrom, etc) to another, trying hard to rescue data in case of read errors. The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, read the log, run it in reverse mode, etc. If you use the logfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also you can interrupt the rescue at any time and resume it later at the same point.
ddrescue does not write zeros to the output when it finds bad sectors in the input, and does not truncate the output file if not asked to. So, every time you run it on the same output file, it tries to fill in the gaps without wiping out the data already rescued. Automatic merging of backups: If you have two or more damaged copies of a file, cdrom, etc, and run ddrescue on all of them, one at a time, with the same output file, you will probably obtain a complete and error-free file. This is so because the probability of having damaged areas at the same places on different input files is very low. Using the logfile, only the needed blocks are read from the second and successive copies.
ddrescue recommends lzip for compression of backups, because of its reliability and data recovery capabilities, including error-checked merging of backup copies. The combination ddrescue + lziprecover is the best option for recovering data from multiple damaged copies. Recordable CD and DVD media keep their data only for a finite time (typically for many years). After that time, data loss develops slowly with read errors growing from the outer media region towards the inside. Just make two (or more) copies of every important CD/DVD you burn so that you can later recover them with ddrescue. The logfile is periodically saved to disc. So in case of a crash you can resume the rescue with little recopying.
Also, the same logfile can be used for multiple commands that copy different areas of the file, and for multiple recovery attempts over different subsets. ddrescue also features a "fill mode" able to selectively overwrite parts of the output file, which has a number of interesting uses like wiping data, marking bad areas or even, in some cases, "repair" damaged sectors. ddrescue written by Antonio Diaz Diaz, download from the GNU web site. Installs as /usr/bin/ddrescue
To copy /dev/sda (damaged \device\harddisk0) to another drive /dev/sdb (empty \device\harddisk1).
# ddrescue /dev/sda /dev/sdb
To recover the partition data run fsck, for example if /home (user data) is on /dev/sda2, run fsck on partition /dev/sdb2:
# fsck /dev/sdb2
This avoids touching the damaged /dev/sda, if the procedure fails you can send the original disk to a professional data recovery service. Lastly mount the partition somewhere and see if you can access the data:
# mount /dev/sdb2 /mnt/data
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10644,
"s": 10577,
"text": "ddrescue - Data recovery tool, save data from a crashed partition."
},
{
"code": null,
"e": 10688,
"s": 10644,
"text": "ddrescue [options] infile outfile [logfile]"
},
{
"code": null,
"e": 11218,
"s": 10688,
"text": "GNU ddrescue is a data recovery tool. It copies data from one file or block device (hard disc, cdrom, etc) to another, trying hard to rescue data in case of read errors. The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, read the log, run it in reverse mode, etc. If you use the logfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also you can interrupt the rescue at any time and resume it later at the same point."
},
{
"code": null,
"e": 11912,
"s": 11218,
"text": "ddrescue does not write zeros to the output when it finds bad sectors in the input, and does not truncate the output file if not asked to. So, every time you run it on the same output file, it tries to fill in the gaps without wiping out the data already rescued. Automatic merging of backups: If you have two or more damaged copies of a file, cdrom, etc, and run ddrescue on all of them, one at a time, with the same output file, you will probably obtain a complete and error-free file. This is so because the probability of having damaged areas at the same places on different input files is very low. Using the logfile, only the needed blocks are read from the second and successive copies."
},
{
"code": null,
"e": 12623,
"s": 11912,
"text": "ddrescue recommends lzip for compression of backups, because of its reliability and data recovery capabilities, including error-checked merging of backup copies. The combination ddrescue + lziprecover is the best option for recovering data from multiple damaged copies. Recordable CD and DVD media keep their data only for a finite time (typically for many years). After that time, data loss develops slowly with read errors growing from the outer media region towards the inside. Just make two (or more) copies of every important CD/DVD you burn so that you can later recover them with ddrescue. The logfile is periodically saved to disc. So in case of a crash you can resume the rescue with little recopying."
},
{
"code": null,
"e": 13097,
"s": 12623,
"text": "Also, the same logfile can be used for multiple commands that copy different areas of the file, and for multiple recovery attempts over different subsets. ddrescue also features a \"fill mode\" able to selectively overwrite parts of the output file, which has a number of interesting uses like wiping data, marking bad areas or even, in some cases, \"repair\" damaged sectors. ddrescue written by Antonio Diaz Diaz, download from the GNU web site. Installs as /usr/bin/ddrescue"
},
{
"code": null,
"e": 13195,
"s": 13097,
"text": "To copy /dev/sda (damaged \\device\\harddisk0) to another drive /dev/sdb (empty \\device\\harddisk1)."
},
{
"code": null,
"e": 13225,
"s": 13195,
"text": "# ddrescue /dev/sda /dev/sdb\n"
},
{
"code": null,
"e": 13348,
"s": 13225,
"text": "To recover the partition data run fsck, for example if /home (user data) is on /dev/sda2, run fsck on partition /dev/sdb2:"
},
{
"code": null,
"e": 13366,
"s": 13348,
"text": "# fsck /dev/sdb2\n"
},
{
"code": null,
"e": 13577,
"s": 13366,
"text": "This avoids touching the damaged /dev/sda, if the procedure fails you can send the original disk to a professional data recovery service. Lastly mount the partition somewhere and see if you can access the data:"
},
{
"code": null,
"e": 13606,
"s": 13577,
"text": "# mount /dev/sdb2 /mnt/data\n"
},
{
"code": null,
"e": 13641,
"s": 13606,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 13669,
"s": 13641,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13703,
"s": 13669,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13720,
"s": 13703,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 13753,
"s": 13720,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13764,
"s": 13753,
"text": " Pradeep D"
},
{
"code": null,
"e": 13799,
"s": 13764,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13815,
"s": 13799,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 13848,
"s": 13815,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13860,
"s": 13848,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 13892,
"s": 13860,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13900,
"s": 13892,
"text": " Uplatz"
},
{
"code": null,
"e": 13907,
"s": 13900,
"text": " Print"
},
{
"code": null,
"e": 13918,
"s": 13907,
"text": " Add Notes"
}
] |
Create multiple regression lines in a single plot using ggplot2 in R.
|
To create multiple regression lines in a single plot using ggplot2, we can use geom_jitter function along with geom_smooth function. The geom_smooth function will help us to different regression line with different colors and geom_jitter will differentiate the points.
Check out the below Example to understand how it can be done.
Following snippet creates a sample data frame −
x1<-rpois(20,1)
y1<-rpois(20,5)
x2<-rpois(20,2)
y2<-rpois(20,8)
x3<-rpois(20,2)
y3<-rpois(20,4)
df<-data.frame(x1,y1,x2,y2,x3,y3)
df
The following dataframe is created
x1 y1 x2 y2 x3 y3
1 2 2 0 6 1 6
2 3 4 0 9 1 7
3 2 4 3 7 2 3
4 0 12 2 11 0 1
5 0 2 0 6 1 1
6 1 7 2 7 1 3
7 0 4 0 4 1 5
8 0 3 2 5 0 1
9 1 4 3 3 0 9
10 0 2 0 8 3 5
11 0 7 4 11 2 4
12 0 4 3 8 2 1
13 0 6 0 6 2 4
14 1 6 1 9 2 2
15 2 3 1 9 6 2
16 1 3 1 10 5 2
17 0 5 1 8 2 6
18 1 2 4 7 2 4
19 0 5 2 11 0 7
20 2 8 4 8 2 4
To load the ggplot2 package and create regression lines for multiple models in single plot on the above created data frame, add the following code to the above snippet −
x1<-rpois(20,1)
y1<-rpois(20,5)
x2<-rpois(20,2)
y2<-rpois(20,8)
x3<-rpois(20,2)
y3<-rpois(20,4)
df<-data.frame(x1,y1,x2,y2,x3,y3)
library(ggplot2)
ggplot(df)+geom_jitter(aes(x1,y1),colour="red")+geom_smooth(aes(x1,y1,col="red"
),method="lm",se=FALSE)+
+
geom_jitter(aes(x2,y2),colour="green")+geom_smooth(aes(x2,y2,col="green"),metho
d="lm",se=FALSE)+
+
geom_jitter(aes(x3,y3),colour="blue")+geom_smooth(aes(x3,y3,col="blue"),method=
"lm",se=FALSE)
`geom_smooth()` using formula 'y ~ x'
`geom_smooth()` using formula 'y ~ x'
`geom_smooth()` using formula 'y ~ x'
If you execute all the above given snippets as a single program, it generates the following Output −
|
[
{
"code": null,
"e": 1331,
"s": 1062,
"text": "To create multiple regression lines in a single plot using ggplot2, we can use geom_jitter function along with geom_smooth function. The geom_smooth function will help us to different regression line with different colors and geom_jitter will differentiate the points."
},
{
"code": null,
"e": 1393,
"s": 1331,
"text": "Check out the below Example to understand how it can be done."
},
{
"code": null,
"e": 1441,
"s": 1393,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1574,
"s": 1441,
"text": "x1<-rpois(20,1)\ny1<-rpois(20,5)\nx2<-rpois(20,2)\ny2<-rpois(20,8)\nx3<-rpois(20,2)\ny3<-rpois(20,4)\ndf<-data.frame(x1,y1,x2,y2,x3,y3)\ndf"
},
{
"code": null,
"e": 1609,
"s": 1574,
"text": "The following dataframe is created"
},
{
"code": null,
"e": 2009,
"s": 1609,
"text": " x1 y1 x2 y2 x3 y3\n 1 2 2 0 6 1 6\n 2 3 4 0 9 1 7\n 3 2 4 3 7 2 3\n 4 0 12 2 11 0 1\n 5 0 2 0 6 1 1\n 6 1 7 2 7 1 3\n 7 0 4 0 4 1 5\n 8 0 3 2 5 0 1\n 9 1 4 3 3 0 9\n10 0 2 0 8 3 5\n11 0 7 4 11 2 4\n12 0 4 3 8 2 1\n13 0 6 0 6 2 4\n14 1 6 1 9 2 2\n15 2 3 1 9 6 2\n16 1 3 1 10 5 2\n17 0 5 1 8 2 6\n18 1 2 4 7 2 4\n19 0 5 2 11 0 7\n20 2 8 4 8 2 4"
},
{
"code": null,
"e": 2179,
"s": 2009,
"text": "To load the ggplot2 package and create regression lines for multiple models in single plot on the above created data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 2743,
"s": 2179,
"text": "x1<-rpois(20,1)\ny1<-rpois(20,5)\nx2<-rpois(20,2)\ny2<-rpois(20,8)\nx3<-rpois(20,2)\ny3<-rpois(20,4)\ndf<-data.frame(x1,y1,x2,y2,x3,y3)\nlibrary(ggplot2)\n\nggplot(df)+geom_jitter(aes(x1,y1),colour=\"red\")+geom_smooth(aes(x1,y1,col=\"red\"\n),method=\"lm\",se=FALSE)+\n+\ngeom_jitter(aes(x2,y2),colour=\"green\")+geom_smooth(aes(x2,y2,col=\"green\"),metho\nd=\"lm\",se=FALSE)+\n+\ngeom_jitter(aes(x3,y3),colour=\"blue\")+geom_smooth(aes(x3,y3,col=\"blue\"),method=\n\"lm\",se=FALSE)\n`geom_smooth()` using formula 'y ~ x'\n`geom_smooth()` using formula 'y ~ x'\n`geom_smooth()` using formula 'y ~ x'"
},
{
"code": null,
"e": 2844,
"s": 2743,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
}
] |
The Best Weapon Combinations for The Legend of Zelda BOTW | by Vijini Mallawaarachchi | Towards Data Science
|
Recently, I came across an article titled Which PUBG Weapon Combination Should You Pick? by Meredith Wan that I found very interesting. This article gave me the idea to write about selecting weapon combinations for one of my favourite games, The Legend of Zelda: Breath Of The Wild using Python and Pareto optimisation. So, let’s get started.
Disclaimer: This article is based on my analysis of a public dataset available on BOTW weapons which may not be complete with all the information and is only intended for adaptation, learning and understanding of concepts of Pareto optimisation. This is not a part of any official research and results may contradict with real-world applications and different personal opinions.
The weapons found in Zelda BOTW have 2 important features which I have considered for this article. They are durability and strength. I have defined these terms with some research and my own experience playing Zelda BOTW.
Durability refers to the number of times you can use the weapon, i.e. the number of times you can hit/shoot an enemy with the weapon. After that, the weapon breaks. The higher the durability, the more number of times you can use the weapon.
Strength (or Attack Power) is the amount of damage you can do to an enemy with one hit. When you hit an enemy, this amount will be lost from the enemy’s health. The higher the strength, the more damage you can do to enemies.
When I was searching for a dataset of the weapons found in Zelda BOTW, I came across a Reddit thread titled A complete database + search for BotW where they provide a link to an amazing database of all the weapons, shields, bows, armour, materials and food items. You can download the dataset in .csv format.
For our analysis, we will need the following imports.
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom itertools import combinations
I have loaded the data into a pandas dataframe using the code given below.
dataframe = pd.read_csv(“Zelda-data.csv”)
You can see there are many unnecessary columns and unspecified values. I had to do a bit of preprocessing to clean the dataset. First of all, I removed all the unnecessary columns and retained the columns name, class, subclass, durability and strength.
columns_to_remove = ["image", "tags", "range", "arrows", "defense", "selling_price", "bonus_set", "upgrade_1", "upgrade_2", "upgrade_3", "upgrade_4", "armor_upgrade", "where_to_find", "notes", "defense_upgrade_lvl1", "defense_upgrade_lvl2", "defense_upgrade_lvl3", "defense_upgrade_lvl4", "bonus", "description"]for col in columns_to_remove: dataframe = dataframe.drop(col, axis=1)
The Master Sword is one of the most powerful weapons found in Zelda BOTW. Its durability is infinite as it never breaks. So we will see that the durability of the Master Sword is not specified. So I added a value larger than the maximum value present in the dataset for its durability. The maximum value available was 80 and I have used 200 for its durability as tests (according to a link found here) have shown that on the fully powered up version the Master Sword has nearly 200 strikes before needing to recharge.
I replaced the unspecified values with 0 or “None” accordingly. Furthermore, I removed all the types of arrows from the dataset as they did not have any durability or strength values specified.
I removed the Bow of Light from the dataset as this weapon becomes available only after defeating Calamity Ganon and when you come to defeat Ganon’s final form, Dark Beat Ganon.
Now, I separately store weapons, shields and bows as follows.
weapons = dataframe[dataframe["class"] == "Weapon"]shileds = dataframe[dataframe["class"] == "Shield"]bows = dataframe[dataframe["class"] == "Bow"]
Before getting into details of the analysis, I will introduce some terms and concepts that we will be using for our analysis.
Correlation is a technique that is used to show how strongly two variables are related to each other. We denote this in a correlation matrix which denotes the correlation coefficients between pairs of variables.
We will be using the correlation matrix for durability and strength of weapons and their combinations to see how they are related.
weapons = dataframe[dataframe["class"] == "Weapon"]fig, ax = plt.subplots(1,1, figsize=(10,5))my_cols = ['durability', 'strength']all_cor = sns.heatmap(weapons[my_cols].corr(), fmt=".3f", annot=True)
The following figures denote the correlation matrix for durability and strength of weapons, shields and bows.
You can see that there is a perfect positive correlation for durability and strength individually as expected. We can also see that bows show a stronger linear relationship between durability and strength as the correlation value is closer to 1 than for shields and bows. Weapons show the weakest linear relationship between durability and strength.
According to Wikipedia,
Multi-objective optimization (also known as multi-objective programming, vector optimization, multicriteria optimization, multiattribute optimization or Pareto optimization) is an area of multiple criteria decision making that is concerned with mathematical optimization problems involving more than one objective function to be optimized simultaneously.
In multi-objective optimization, we have multiple objectives (for example, durability and strength in our case) which we have to maximise and determine different optimal combinations. We get a Pareto-efficient (or Pareto-optimal) solution when this solution is not dominated by any other feasible solutions. In simpler terms, this solution cannot be modified to make one objective better off without making at least one objective worse off. There can be more than one Pareto-efficient solution and this set of Pareto-efficient solutions is defined as the Pareto frontier.
In this article, I will be using a Pareto-based approach to determine the best weapon combinations where our objective function is a vector that consists of durability and strength values of weapons as [durability, strength]. Let’s see what are the best Pareto-efficient combinations of weapons we can obtain for Zelda BOTW.
At a given instance, Link can equip one weapon and one shield. Let us see what optimum combinations we can have. After preprocessing, we have 127 weapons and 33 shields. We will get 4191 combinations of weapons and shields. For each combination, I have considered the mean durability and mean strength.
weapons_shields = pd.concat([weapons, shields], ignore_index=True)df2 = weapons_shields.set_index("name", drop = False)my_data = []my_combinations = list(combinations(df2.index,2))valid_combinations = []for comb in my_combinations: if df2.loc[comb[0],"class"] != df2.loc[comb[1],"class"]: valid_combinations.append(comb) data_line = [] data_line.append(np.mean([df2.loc[comb[0],"durability"], df2.loc[comb[1],"durability"]])) data_line.append(np.mean([df2.loc[comb[0],"strength"], df2.loc[comb[1],"strength"]])) my_data.append(data_line) my_combinations = pd.DataFrame(my_data, columns = ['durability', 'strength'], index=valid_combinations)
I won’t be drawing the heatmap to show the different combinations of weapons with their durability and strength as there is a huge set of combinations. Instead, I will plot a correlation matrix showing the mean durability and mean strength of combinations as shown below.
Let’s see how our Pareto frontier looks like.
You can see that Pareto-efficient combinations are as follows,
Master Sword + Hylian ShieldBoulder Breaker + Hylian ShieldSavage Lynel Crusher + Hylian Shield
Master Sword + Hylian Shield
Boulder Breaker + Hylian Shield
Savage Lynel Crusher + Hylian Shield
We cannot say that one of these combinations is better in terms of both strength and durability. However, if I want my weapons to last longer, then I will use the combination Master Sword + Hylian Shield. On the other hand, if I want to do more damage to enemies, then I will use the combination Savage Lynel Crusher + Hylian Shield.
At a given instance, Link can equip one weapon, one shield and one bow. Let us see what optimum combinations we can have. After preprocessing, we have 127 weapons, 33 shields and 25 bows. We will get 104,775 combinations of weapons and shields.
Similar to weapon+shield combinations, I will plot a correlation matrix showing the mean durability and mean strength of weapon+shield+bow combinations as shown below.
Let’s see how our Pareto frontier looks like.
You can see that Pareto-efficient combinations are as follows,
Master Sword + Hylian Shield + Ancient BowMaster Sword + Hylian Shield + Royal Guard’s BowBoulder Breaker + Hylian Shield + Ancient BowSavage Lynel Crusher + Hylian Shield + Ancient BowSavage Lynel Crusher + Hylian Shield + Royal Guard’s Bow
Master Sword + Hylian Shield + Ancient Bow
Master Sword + Hylian Shield + Royal Guard’s Bow
Boulder Breaker + Hylian Shield + Ancient Bow
Savage Lynel Crusher + Hylian Shield + Ancient Bow
Savage Lynel Crusher + Hylian Shield + Royal Guard’s Bow
Note that we have the 3 weapon+shiled combinations that we found before within these combinations as well. Additionally, we have Ancient Bow and Royal Guard’s Bow within the combinations.
Similar to weapon+shiled combinations, we cannot say that one of these combinations is better in terms of both strength and durability. However, if I want my weapons to last longer, then I will use the combination Master Sword + Hylian Shield + Ancient Bow. On the other hand, if I want to do more damage to enemies, then I will use the combination Savage Lynel Crusher + Hylian Shield + Royal Guard’s Bow. The choice is totally up to you!
You might have already figured out these combinations while playing the game. However, I was curious whether the most powerful weapons would be found by the Pareto-based analysis, and of course, it actually did!
One thing to note is during this analysis, that I have not considered the fact that the Master Sword may run out of energy and take some time to recharge. In that sense, the Master Sword has its limits. Moreover, I have not considered facts such as attack speed, boost in attack speeds after eating certain meals, whether the weapon can be used together with a shield, armour set bonuses and amiibo upgrades in this analysis. These factors can affect the optimal weapon combinations when considering the rate of damage the combination can do.
Special thank goes to Meredith Wan for sharing her analysis code which was very helpful for me to analyse the BOTW dataset.
You can find the Jupyter notebook with the code from here.
Hope you all found this article interesting and I would love to hear your thoughts. Don’t forget to share these weapon combinations with your BOTW friends.
Cheers!
[1] Y. Jin and B. Sendhoff, “Pareto-Based Multiobjective Machine Learning: An Overview and Case Studies,” in IEEE Transactions on Systems, Man, and Cybernetics, Part C (Applications and Reviews), vol. 38, no. 3, pp. 397–415, May 2008, doi: 10.1109/TSMCC.2008.919172.
[2] Multi-objective optimization — Wikipedia (https://en.wikipedia.org/wiki/Multi-objective_optimization)
[3] Pareto front — Python for healthcare modelling and data science (https://pythonhealthcare.org/tag/pareto-front/)
|
[
{
"code": null,
"e": 515,
"s": 172,
"text": "Recently, I came across an article titled Which PUBG Weapon Combination Should You Pick? by Meredith Wan that I found very interesting. This article gave me the idea to write about selecting weapon combinations for one of my favourite games, The Legend of Zelda: Breath Of The Wild using Python and Pareto optimisation. So, let’s get started."
},
{
"code": null,
"e": 894,
"s": 515,
"text": "Disclaimer: This article is based on my analysis of a public dataset available on BOTW weapons which may not be complete with all the information and is only intended for adaptation, learning and understanding of concepts of Pareto optimisation. This is not a part of any official research and results may contradict with real-world applications and different personal opinions."
},
{
"code": null,
"e": 1116,
"s": 894,
"text": "The weapons found in Zelda BOTW have 2 important features which I have considered for this article. They are durability and strength. I have defined these terms with some research and my own experience playing Zelda BOTW."
},
{
"code": null,
"e": 1357,
"s": 1116,
"text": "Durability refers to the number of times you can use the weapon, i.e. the number of times you can hit/shoot an enemy with the weapon. After that, the weapon breaks. The higher the durability, the more number of times you can use the weapon."
},
{
"code": null,
"e": 1582,
"s": 1357,
"text": "Strength (or Attack Power) is the amount of damage you can do to an enemy with one hit. When you hit an enemy, this amount will be lost from the enemy’s health. The higher the strength, the more damage you can do to enemies."
},
{
"code": null,
"e": 1891,
"s": 1582,
"text": "When I was searching for a dataset of the weapons found in Zelda BOTW, I came across a Reddit thread titled A complete database + search for BotW where they provide a link to an amazing database of all the weapons, shields, bows, armour, materials and food items. You can download the dataset in .csv format."
},
{
"code": null,
"e": 1945,
"s": 1891,
"text": "For our analysis, we will need the following imports."
},
{
"code": null,
"e": 2069,
"s": 1945,
"text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom itertools import combinations"
},
{
"code": null,
"e": 2144,
"s": 2069,
"text": "I have loaded the data into a pandas dataframe using the code given below."
},
{
"code": null,
"e": 2186,
"s": 2144,
"text": "dataframe = pd.read_csv(“Zelda-data.csv”)"
},
{
"code": null,
"e": 2439,
"s": 2186,
"text": "You can see there are many unnecessary columns and unspecified values. I had to do a bit of preprocessing to clean the dataset. First of all, I removed all the unnecessary columns and retained the columns name, class, subclass, durability and strength."
},
{
"code": null,
"e": 2824,
"s": 2439,
"text": "columns_to_remove = [\"image\", \"tags\", \"range\", \"arrows\", \"defense\", \"selling_price\", \"bonus_set\", \"upgrade_1\", \"upgrade_2\", \"upgrade_3\", \"upgrade_4\", \"armor_upgrade\", \"where_to_find\", \"notes\", \"defense_upgrade_lvl1\", \"defense_upgrade_lvl2\", \"defense_upgrade_lvl3\", \"defense_upgrade_lvl4\", \"bonus\", \"description\"]for col in columns_to_remove: dataframe = dataframe.drop(col, axis=1)"
},
{
"code": null,
"e": 3342,
"s": 2824,
"text": "The Master Sword is one of the most powerful weapons found in Zelda BOTW. Its durability is infinite as it never breaks. So we will see that the durability of the Master Sword is not specified. So I added a value larger than the maximum value present in the dataset for its durability. The maximum value available was 80 and I have used 200 for its durability as tests (according to a link found here) have shown that on the fully powered up version the Master Sword has nearly 200 strikes before needing to recharge."
},
{
"code": null,
"e": 3536,
"s": 3342,
"text": "I replaced the unspecified values with 0 or “None” accordingly. Furthermore, I removed all the types of arrows from the dataset as they did not have any durability or strength values specified."
},
{
"code": null,
"e": 3714,
"s": 3536,
"text": "I removed the Bow of Light from the dataset as this weapon becomes available only after defeating Calamity Ganon and when you come to defeat Ganon’s final form, Dark Beat Ganon."
},
{
"code": null,
"e": 3776,
"s": 3714,
"text": "Now, I separately store weapons, shields and bows as follows."
},
{
"code": null,
"e": 3924,
"s": 3776,
"text": "weapons = dataframe[dataframe[\"class\"] == \"Weapon\"]shileds = dataframe[dataframe[\"class\"] == \"Shield\"]bows = dataframe[dataframe[\"class\"] == \"Bow\"]"
},
{
"code": null,
"e": 4050,
"s": 3924,
"text": "Before getting into details of the analysis, I will introduce some terms and concepts that we will be using for our analysis."
},
{
"code": null,
"e": 4262,
"s": 4050,
"text": "Correlation is a technique that is used to show how strongly two variables are related to each other. We denote this in a correlation matrix which denotes the correlation coefficients between pairs of variables."
},
{
"code": null,
"e": 4393,
"s": 4262,
"text": "We will be using the correlation matrix for durability and strength of weapons and their combinations to see how they are related."
},
{
"code": null,
"e": 4593,
"s": 4393,
"text": "weapons = dataframe[dataframe[\"class\"] == \"Weapon\"]fig, ax = plt.subplots(1,1, figsize=(10,5))my_cols = ['durability', 'strength']all_cor = sns.heatmap(weapons[my_cols].corr(), fmt=\".3f\", annot=True)"
},
{
"code": null,
"e": 4703,
"s": 4593,
"text": "The following figures denote the correlation matrix for durability and strength of weapons, shields and bows."
},
{
"code": null,
"e": 5053,
"s": 4703,
"text": "You can see that there is a perfect positive correlation for durability and strength individually as expected. We can also see that bows show a stronger linear relationship between durability and strength as the correlation value is closer to 1 than for shields and bows. Weapons show the weakest linear relationship between durability and strength."
},
{
"code": null,
"e": 5077,
"s": 5053,
"text": "According to Wikipedia,"
},
{
"code": null,
"e": 5432,
"s": 5077,
"text": "Multi-objective optimization (also known as multi-objective programming, vector optimization, multicriteria optimization, multiattribute optimization or Pareto optimization) is an area of multiple criteria decision making that is concerned with mathematical optimization problems involving more than one objective function to be optimized simultaneously."
},
{
"code": null,
"e": 6004,
"s": 5432,
"text": "In multi-objective optimization, we have multiple objectives (for example, durability and strength in our case) which we have to maximise and determine different optimal combinations. We get a Pareto-efficient (or Pareto-optimal) solution when this solution is not dominated by any other feasible solutions. In simpler terms, this solution cannot be modified to make one objective better off without making at least one objective worse off. There can be more than one Pareto-efficient solution and this set of Pareto-efficient solutions is defined as the Pareto frontier."
},
{
"code": null,
"e": 6329,
"s": 6004,
"text": "In this article, I will be using a Pareto-based approach to determine the best weapon combinations where our objective function is a vector that consists of durability and strength values of weapons as [durability, strength]. Let’s see what are the best Pareto-efficient combinations of weapons we can obtain for Zelda BOTW."
},
{
"code": null,
"e": 6632,
"s": 6329,
"text": "At a given instance, Link can equip one weapon and one shield. Let us see what optimum combinations we can have. After preprocessing, we have 127 weapons and 33 shields. We will get 4191 combinations of weapons and shields. For each combination, I have considered the mean durability and mean strength."
},
{
"code": null,
"e": 7315,
"s": 6632,
"text": "weapons_shields = pd.concat([weapons, shields], ignore_index=True)df2 = weapons_shields.set_index(\"name\", drop = False)my_data = []my_combinations = list(combinations(df2.index,2))valid_combinations = []for comb in my_combinations: if df2.loc[comb[0],\"class\"] != df2.loc[comb[1],\"class\"]: valid_combinations.append(comb) data_line = [] data_line.append(np.mean([df2.loc[comb[0],\"durability\"], df2.loc[comb[1],\"durability\"]])) data_line.append(np.mean([df2.loc[comb[0],\"strength\"], df2.loc[comb[1],\"strength\"]])) my_data.append(data_line) my_combinations = pd.DataFrame(my_data, columns = ['durability', 'strength'], index=valid_combinations)"
},
{
"code": null,
"e": 7587,
"s": 7315,
"text": "I won’t be drawing the heatmap to show the different combinations of weapons with their durability and strength as there is a huge set of combinations. Instead, I will plot a correlation matrix showing the mean durability and mean strength of combinations as shown below."
},
{
"code": null,
"e": 7633,
"s": 7587,
"text": "Let’s see how our Pareto frontier looks like."
},
{
"code": null,
"e": 7696,
"s": 7633,
"text": "You can see that Pareto-efficient combinations are as follows,"
},
{
"code": null,
"e": 7792,
"s": 7696,
"text": "Master Sword + Hylian ShieldBoulder Breaker + Hylian ShieldSavage Lynel Crusher + Hylian Shield"
},
{
"code": null,
"e": 7821,
"s": 7792,
"text": "Master Sword + Hylian Shield"
},
{
"code": null,
"e": 7853,
"s": 7821,
"text": "Boulder Breaker + Hylian Shield"
},
{
"code": null,
"e": 7890,
"s": 7853,
"text": "Savage Lynel Crusher + Hylian Shield"
},
{
"code": null,
"e": 8224,
"s": 7890,
"text": "We cannot say that one of these combinations is better in terms of both strength and durability. However, if I want my weapons to last longer, then I will use the combination Master Sword + Hylian Shield. On the other hand, if I want to do more damage to enemies, then I will use the combination Savage Lynel Crusher + Hylian Shield."
},
{
"code": null,
"e": 8469,
"s": 8224,
"text": "At a given instance, Link can equip one weapon, one shield and one bow. Let us see what optimum combinations we can have. After preprocessing, we have 127 weapons, 33 shields and 25 bows. We will get 104,775 combinations of weapons and shields."
},
{
"code": null,
"e": 8637,
"s": 8469,
"text": "Similar to weapon+shield combinations, I will plot a correlation matrix showing the mean durability and mean strength of weapon+shield+bow combinations as shown below."
},
{
"code": null,
"e": 8683,
"s": 8637,
"text": "Let’s see how our Pareto frontier looks like."
},
{
"code": null,
"e": 8746,
"s": 8683,
"text": "You can see that Pareto-efficient combinations are as follows,"
},
{
"code": null,
"e": 8988,
"s": 8746,
"text": "Master Sword + Hylian Shield + Ancient BowMaster Sword + Hylian Shield + Royal Guard’s BowBoulder Breaker + Hylian Shield + Ancient BowSavage Lynel Crusher + Hylian Shield + Ancient BowSavage Lynel Crusher + Hylian Shield + Royal Guard’s Bow"
},
{
"code": null,
"e": 9031,
"s": 8988,
"text": "Master Sword + Hylian Shield + Ancient Bow"
},
{
"code": null,
"e": 9080,
"s": 9031,
"text": "Master Sword + Hylian Shield + Royal Guard’s Bow"
},
{
"code": null,
"e": 9126,
"s": 9080,
"text": "Boulder Breaker + Hylian Shield + Ancient Bow"
},
{
"code": null,
"e": 9177,
"s": 9126,
"text": "Savage Lynel Crusher + Hylian Shield + Ancient Bow"
},
{
"code": null,
"e": 9234,
"s": 9177,
"text": "Savage Lynel Crusher + Hylian Shield + Royal Guard’s Bow"
},
{
"code": null,
"e": 9422,
"s": 9234,
"text": "Note that we have the 3 weapon+shiled combinations that we found before within these combinations as well. Additionally, we have Ancient Bow and Royal Guard’s Bow within the combinations."
},
{
"code": null,
"e": 9862,
"s": 9422,
"text": "Similar to weapon+shiled combinations, we cannot say that one of these combinations is better in terms of both strength and durability. However, if I want my weapons to last longer, then I will use the combination Master Sword + Hylian Shield + Ancient Bow. On the other hand, if I want to do more damage to enemies, then I will use the combination Savage Lynel Crusher + Hylian Shield + Royal Guard’s Bow. The choice is totally up to you!"
},
{
"code": null,
"e": 10074,
"s": 9862,
"text": "You might have already figured out these combinations while playing the game. However, I was curious whether the most powerful weapons would be found by the Pareto-based analysis, and of course, it actually did!"
},
{
"code": null,
"e": 10617,
"s": 10074,
"text": "One thing to note is during this analysis, that I have not considered the fact that the Master Sword may run out of energy and take some time to recharge. In that sense, the Master Sword has its limits. Moreover, I have not considered facts such as attack speed, boost in attack speeds after eating certain meals, whether the weapon can be used together with a shield, armour set bonuses and amiibo upgrades in this analysis. These factors can affect the optimal weapon combinations when considering the rate of damage the combination can do."
},
{
"code": null,
"e": 10741,
"s": 10617,
"text": "Special thank goes to Meredith Wan for sharing her analysis code which was very helpful for me to analyse the BOTW dataset."
},
{
"code": null,
"e": 10800,
"s": 10741,
"text": "You can find the Jupyter notebook with the code from here."
},
{
"code": null,
"e": 10956,
"s": 10800,
"text": "Hope you all found this article interesting and I would love to hear your thoughts. Don’t forget to share these weapon combinations with your BOTW friends."
},
{
"code": null,
"e": 10964,
"s": 10956,
"text": "Cheers!"
},
{
"code": null,
"e": 11231,
"s": 10964,
"text": "[1] Y. Jin and B. Sendhoff, “Pareto-Based Multiobjective Machine Learning: An Overview and Case Studies,” in IEEE Transactions on Systems, Man, and Cybernetics, Part C (Applications and Reviews), vol. 38, no. 3, pp. 397–415, May 2008, doi: 10.1109/TSMCC.2008.919172."
},
{
"code": null,
"e": 11337,
"s": 11231,
"text": "[2] Multi-objective optimization — Wikipedia (https://en.wikipedia.org/wiki/Multi-objective_optimization)"
}
] |
Binary Search In JavaScript - GeeksforGeeks
|
09 Feb, 2022
Binary Search is a searching technique which works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexity.In this article, the implementation of Binary Search in Javascript is discussed using both iterative and recursive ways.Given a sorted array of numbers. The task is to search for a given element in the array using Binary search.Examples:
Input : arr[] = {1, 3, 5, 7, 8, 9}
x = 5
Output : Element found!
Input : arr[] = {1, 3, 5, 7, 8, 9}
x = 6
Output : Element not found!
Note: Assuming the array is sorted.
Recursive Approach :
BASE CONDITION: If starting index is greater than ending index return false.Compute the middle index.Compare the middle element with number x. If equal return true.If greater, call the same function with ending index = middle-1 and repeat step 1.If smaller, call the same function with starting index = middle+1 and repeat step 1.
BASE CONDITION: If starting index is greater than ending index return false.
Compute the middle index.
Compare the middle element with number x. If equal return true.
If greater, call the same function with ending index = middle-1 and repeat step 1.
If smaller, call the same function with starting index = middle+1 and repeat step 1.
Below is the implementation of Binary Search (Recursive Approach) in JavaScript:
javascript
<script>let recursiveFunction = function (arr, x, start, end) { // Base Condition if (start > end) return false; // Find the middle index let mid=Math.floor((start + end)/2); // Compare mid with given key x if (arr[mid]===x) return true; // If element at mid is greater than x, // search in the left half of mid if(arr[mid] > x) return recursiveFunction(arr, x, start, mid-1); else // If element at mid is smaller than x, // search in the right half of mid return recursiveFunction(arr, x, mid+1, end);} // Driver codelet arr = [1, 3, 5, 7, 8, 9];let x = 5; if (recursiveFunction(arr, x, 0, arr.length-1)) document.write("Element found!<br>");else document.write("Element not found!<br>"); x = 6; if (recursiveFunction(arr, x, 0, arr.length-1)) document.write("Element found!<br>");else document.write("Element not found!<br>");</script>
Output:
Element found!
Element not found!
Time Complexity: O(logN)Auxiliary Space: O(1) Iterative Approach : In this iterative approach, instead of recursion, we use a while loop, and the loop runs until it hits the base condition, i.e. start becomes greater than end.Below is the implementation of Binary Search (Iterative Approach) in JavaScript:
javascript
<script>// Iterative function to implement Binary Searchlet iterativeFunction = function (arr, x) { let start=0, end=arr.length-1; // Iterate while start not meets end while (start<=end){ // Find the mid index let mid=Math.floor((start + end)/2); // If element is present at mid, return True if (arr[mid]===x) return true; // Else look in left or right half accordingly else if (arr[mid] < x) start = mid + 1; else end = mid - 1; } return false;} // Driver codelet arr = [1, 3, 5, 7, 8, 9];let x = 5; if (iterativeFunction(arr, x, 0, arr.length-1)) document.write("Element found!<br>");else document.write("Element not found!<br>"); x = 6; if (iterativeFunction(arr, x, 0, arr.length-1)) document.write("Element found!<br>");else document.write("Element not found!<br>");</script>
Output:
Element found!
Element not found!
Time Complexity: O(logN).Auxiliary Space: O(1)
nidhi_biet
pankajsharmagfg
peterhauke
Binary Search
Technical Scripter 2018
Algorithms
Divide and Conquer
JavaScript
Searching
Technical Scripter
Searching
Divide and Conquer
Binary Search
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
K means Clustering - Introduction
Program for SSTF disk scheduling algorithm
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi
|
[
{
"code": null,
"e": 24690,
"s": 24662,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 25211,
"s": 24690,
"text": "Binary Search is a searching technique which works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexity.In this article, the implementation of Binary Search in Javascript is discussed using both iterative and recursive ways.Given a sorted array of numbers. The task is to search for a given element in the array using Binary search.Examples: "
},
{
"code": null,
"e": 25362,
"s": 25211,
"text": "Input : arr[] = {1, 3, 5, 7, 8, 9}\n x = 5\nOutput : Element found!\n\nInput : arr[] = {1, 3, 5, 7, 8, 9}\n x = 6\nOutput : Element not found!"
},
{
"code": null,
"e": 25399,
"s": 25362,
"text": "Note: Assuming the array is sorted. "
},
{
"code": null,
"e": 25422,
"s": 25399,
"text": "Recursive Approach : "
},
{
"code": null,
"e": 25753,
"s": 25422,
"text": "BASE CONDITION: If starting index is greater than ending index return false.Compute the middle index.Compare the middle element with number x. If equal return true.If greater, call the same function with ending index = middle-1 and repeat step 1.If smaller, call the same function with starting index = middle+1 and repeat step 1."
},
{
"code": null,
"e": 25830,
"s": 25753,
"text": "BASE CONDITION: If starting index is greater than ending index return false."
},
{
"code": null,
"e": 25856,
"s": 25830,
"text": "Compute the middle index."
},
{
"code": null,
"e": 25920,
"s": 25856,
"text": "Compare the middle element with number x. If equal return true."
},
{
"code": null,
"e": 26003,
"s": 25920,
"text": "If greater, call the same function with ending index = middle-1 and repeat step 1."
},
{
"code": null,
"e": 26088,
"s": 26003,
"text": "If smaller, call the same function with starting index = middle+1 and repeat step 1."
},
{
"code": null,
"e": 26171,
"s": 26088,
"text": "Below is the implementation of Binary Search (Recursive Approach) in JavaScript: "
},
{
"code": null,
"e": 26182,
"s": 26171,
"text": "javascript"
},
{
"code": "<script>let recursiveFunction = function (arr, x, start, end) { // Base Condition if (start > end) return false; // Find the middle index let mid=Math.floor((start + end)/2); // Compare mid with given key x if (arr[mid]===x) return true; // If element at mid is greater than x, // search in the left half of mid if(arr[mid] > x) return recursiveFunction(arr, x, start, mid-1); else // If element at mid is smaller than x, // search in the right half of mid return recursiveFunction(arr, x, mid+1, end);} // Driver codelet arr = [1, 3, 5, 7, 8, 9];let x = 5; if (recursiveFunction(arr, x, 0, arr.length-1)) document.write(\"Element found!<br>\");else document.write(\"Element not found!<br>\"); x = 6; if (recursiveFunction(arr, x, 0, arr.length-1)) document.write(\"Element found!<br>\");else document.write(\"Element not found!<br>\");</script> ",
"e": 27145,
"s": 26182,
"text": null
},
{
"code": null,
"e": 27155,
"s": 27145,
"text": "Output: "
},
{
"code": null,
"e": 27189,
"s": 27155,
"text": "Element found!\nElement not found!"
},
{
"code": null,
"e": 27498,
"s": 27189,
"text": "Time Complexity: O(logN)Auxiliary Space: O(1) Iterative Approach : In this iterative approach, instead of recursion, we use a while loop, and the loop runs until it hits the base condition, i.e. start becomes greater than end.Below is the implementation of Binary Search (Iterative Approach) in JavaScript: "
},
{
"code": null,
"e": 27509,
"s": 27498,
"text": "javascript"
},
{
"code": "<script>// Iterative function to implement Binary Searchlet iterativeFunction = function (arr, x) { let start=0, end=arr.length-1; // Iterate while start not meets end while (start<=end){ // Find the mid index let mid=Math.floor((start + end)/2); // If element is present at mid, return True if (arr[mid]===x) return true; // Else look in left or right half accordingly else if (arr[mid] < x) start = mid + 1; else end = mid - 1; } return false;} // Driver codelet arr = [1, 3, 5, 7, 8, 9];let x = 5; if (iterativeFunction(arr, x, 0, arr.length-1)) document.write(\"Element found!<br>\");else document.write(\"Element not found!<br>\"); x = 6; if (iterativeFunction(arr, x, 0, arr.length-1)) document.write(\"Element found!<br>\");else document.write(\"Element not found!<br>\");</script> ",
"e": 28442,
"s": 27509,
"text": null
},
{
"code": null,
"e": 28452,
"s": 28442,
"text": "Output: "
},
{
"code": null,
"e": 28486,
"s": 28452,
"text": "Element found!\nElement not found!"
},
{
"code": null,
"e": 28535,
"s": 28486,
"text": "Time Complexity: O(logN).Auxiliary Space: O(1) "
},
{
"code": null,
"e": 28546,
"s": 28535,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28562,
"s": 28546,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 28573,
"s": 28562,
"text": "peterhauke"
},
{
"code": null,
"e": 28587,
"s": 28573,
"text": "Binary Search"
},
{
"code": null,
"e": 28611,
"s": 28587,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 28622,
"s": 28611,
"text": "Algorithms"
},
{
"code": null,
"e": 28641,
"s": 28622,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 28652,
"s": 28641,
"text": "JavaScript"
},
{
"code": null,
"e": 28662,
"s": 28652,
"text": "Searching"
},
{
"code": null,
"e": 28681,
"s": 28662,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28691,
"s": 28681,
"text": "Searching"
},
{
"code": null,
"e": 28710,
"s": 28691,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 28724,
"s": 28710,
"text": "Binary Search"
},
{
"code": null,
"e": 28735,
"s": 28724,
"text": "Algorithms"
},
{
"code": null,
"e": 28833,
"s": 28735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28842,
"s": 28833,
"text": "Comments"
},
{
"code": null,
"e": 28855,
"s": 28842,
"text": "Old Comments"
},
{
"code": null,
"e": 28880,
"s": 28855,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 28909,
"s": 28880,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 28952,
"s": 28909,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 28986,
"s": 28952,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 29029,
"s": 28986,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 29040,
"s": 29029,
"text": "Merge Sort"
},
{
"code": null,
"e": 29050,
"s": 29040,
"text": "QuickSort"
},
{
"code": null,
"e": 29064,
"s": 29050,
"text": "Binary Search"
},
{
"code": null,
"e": 29132,
"s": 29064,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
Abundant Number in C ?
|
An abundant Number (also known as excessive number) is a number in the number theory which itself is smaller than the sum of all its proper divisors. For example,12 is an abundant Number : divisors 1,2,3,4,6 , sum =16 >12.
The difference between the sum of divisors and the number is called abundance. For above example abundance = 4 => 16 - 12 .
To check for abundant number we will find all the factors of the number and add them up. This sum compared with the number show that if the number is abundant or not.
#include >stdio.h>
#include <math.h>
int main(){
int n = 56, sum = 0;
for (int i=1; i<=sqrt(n); i++){
if (n%i==0){
if (n/i == i)
sum = sum + i;
{
sum = sum + i;
sum = sum + (n / i);
}
}
}
sum = sum - n;
if(sum > n){
printf("The number is abundant number");
}
else
printf("The number is not abundant number");
return 0;
}
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "An abundant Number (also known as excessive number) is a number in the number theory which itself is smaller than the sum of all its proper divisors. For example,12 is an abundant Number : divisors 1,2,3,4,6 , sum =16 >12."
},
{
"code": null,
"e": 1409,
"s": 1285,
"text": "The difference between the sum of divisors and the number is called abundance. For above example abundance = 4 => 16 - 12 ."
},
{
"code": null,
"e": 1576,
"s": 1409,
"text": "To check for abundant number we will find all the factors of the number and add them up. This sum compared with the number show that if the number is abundant or not."
},
{
"code": null,
"e": 1993,
"s": 1576,
"text": "#include >stdio.h>\n#include <math.h>\nint main(){\n int n = 56, sum = 0;\n for (int i=1; i<=sqrt(n); i++){\n if (n%i==0){\n if (n/i == i)\n sum = sum + i;\n {\n sum = sum + i;\n sum = sum + (n / i);\n }\n }\n }\n sum = sum - n;\n if(sum > n){\n printf(\"The number is abundant number\");\n }\n else\n printf(\"The number is not abundant number\");\n return 0;\n}"
}
] |
V measure: an homogeneous and complete clustering | by Filippo Valle | Towards Data Science
|
Clustering is a Machine Learning technique that involves the grouping of data points. Given a set of data points, we can use a clustering algorithm to classify each data sample into a specific group (cluster).
Clustering is a method of unsupervised learning and is a common technique for statistical data analysis used in many fields. The hope of the data scientist is that samples in the same cluster have similar properties, features or behaviour. For instance, one could run clustering on cancers’ samples, and the hope is that samples in the same group belong to the same cancer subtype [2].
Once the clustering is run one has to evaluate qualitatively the goodness of the output. First of all, to verify that groups are actually meaningful, and moreover having a score can be the proxy to evaluate different models and choose the best one.
There are many different scores out there, each one with its pros and cons.
scikit-learn.org
One of these measures is the so-called V-measure (or Normalised Mutual Information) score. One of the advantages of this measure is that it can be factorised into two easily to visualise metrics.
This score can be interpretated as an average of other two measures: homogeneity and completeness.
Homogeneity measures how much the sample in a cluster are similar. It is defined using the Shannon’s entropy.
Given H(C|K) formula.
It is easy to understand why this is the case. If one looks at the term H(C|K) it contains nck / nk which represents the ratio between the number of samples labelled c in cluster k and the total number of samples in cluster k.
When all samples in cluster k have the same label c, the homogeneity equals 1.
Note that there is a sum over c and k, it doesn’t matter which is the cluster that contains a particular label, it is sufficient that there is at least one. This is useful when running unsupervised methods whose output has nothing to do with the labels.
Here an example of homogeneous clustering. All three clusters contains only one color (feature), in other words all the samples in the same cluster share their label.
Anyway this situation is not optimal since orange samples are split into different clusters . In this example, a feature is not complete.
Completeness although measures how much similar samples are put together by the clustering algorithm.
It is easy to understand why this is the case. If one looks at the term H(K|C) it contains nck / nc which represents the ratio between the number of samples labelled c in cluster k and the total number of samples labelled c.
When all samples of kind c have been assigned to the same cluster k, the completeness equals 1.
Here an example of a complete clustering. Each color is present only in one group. In this case all points with the same property have been classified together. Note that complete doesn’t imply homogeneous, in fact in each cluster there are multiple colors.
Now we have understood this two metrics it is clear that an optimal algorithm would be able to obtain a partition which is both homogeneous and complete. In this case, all samples with a particular color are put together in a cluster and that cluster contains only them. If the algorithms was unsupervised it should be clear that with this output it has learnt correctly the features.
Otherwise, the worst clustering possible is one which is neither homogeneous or complete. In this case each cluster contains multiple labels and each label is assigned to multiple clusters. In the case both the measures are zero.
Finally to obtain a measure of the goodness of our clustering algorithm we can consider the harmonic average between homogeneity and completeness and obtain the V-measure or Normalised Mutual Information (NMI) [1].
This score is a measure between 0–1 that actually quantifies the goodness of the clustering partition. In fact, it requires that both homogeneity h and completeness c are maximised (NMI is 1 when both h and c are 1). Moreover if the clustering doesn’t satisfy any of the two conditions NMI will be zero.
There are many measures of this kind, but thank to its factorisation in the two measures homogeneity and completeness, its interpretability is clear and intuitive.
So, now you have performed a clustering and want to estimate NMI. Sci-kit learn has it implemented so it is really easy to estimate it.
scikit-learn.org
Here a simple example. From this example it is also clear that the score doesn’t depend on the labels’ names, as discussed before it is the same for every label permutation.
from sklearn.metrics.cluster import v_measure_score>>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1])1.0>>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0])1.0
Hirschberg, J.B.; Rosenberg, A. V-Measure: A conditional entropy-based external cluster evaluation. (2007), Proceedings of EMNLP.Valle, F.; Osella, M.; Caselle, M. A Topic Modeling Analysis of TCGA Breast and Lung Cancer Transcriptomic Data. (2020) Cancers
Hirschberg, J.B.; Rosenberg, A. V-Measure: A conditional entropy-based external cluster evaluation. (2007), Proceedings of EMNLP.
Valle, F.; Osella, M.; Caselle, M. A Topic Modeling Analysis of TCGA Breast and Lung Cancer Transcriptomic Data. (2020) Cancers
Some rights reserved
|
[
{
"code": null,
"e": 381,
"s": 171,
"text": "Clustering is a Machine Learning technique that involves the grouping of data points. Given a set of data points, we can use a clustering algorithm to classify each data sample into a specific group (cluster)."
},
{
"code": null,
"e": 767,
"s": 381,
"text": "Clustering is a method of unsupervised learning and is a common technique for statistical data analysis used in many fields. The hope of the data scientist is that samples in the same cluster have similar properties, features or behaviour. For instance, one could run clustering on cancers’ samples, and the hope is that samples in the same group belong to the same cancer subtype [2]."
},
{
"code": null,
"e": 1016,
"s": 767,
"text": "Once the clustering is run one has to evaluate qualitatively the goodness of the output. First of all, to verify that groups are actually meaningful, and moreover having a score can be the proxy to evaluate different models and choose the best one."
},
{
"code": null,
"e": 1092,
"s": 1016,
"text": "There are many different scores out there, each one with its pros and cons."
},
{
"code": null,
"e": 1109,
"s": 1092,
"text": "scikit-learn.org"
},
{
"code": null,
"e": 1305,
"s": 1109,
"text": "One of these measures is the so-called V-measure (or Normalised Mutual Information) score. One of the advantages of this measure is that it can be factorised into two easily to visualise metrics."
},
{
"code": null,
"e": 1404,
"s": 1305,
"text": "This score can be interpretated as an average of other two measures: homogeneity and completeness."
},
{
"code": null,
"e": 1514,
"s": 1404,
"text": "Homogeneity measures how much the sample in a cluster are similar. It is defined using the Shannon’s entropy."
},
{
"code": null,
"e": 1536,
"s": 1514,
"text": "Given H(C|K) formula."
},
{
"code": null,
"e": 1763,
"s": 1536,
"text": "It is easy to understand why this is the case. If one looks at the term H(C|K) it contains nck / nk which represents the ratio between the number of samples labelled c in cluster k and the total number of samples in cluster k."
},
{
"code": null,
"e": 1842,
"s": 1763,
"text": "When all samples in cluster k have the same label c, the homogeneity equals 1."
},
{
"code": null,
"e": 2096,
"s": 1842,
"text": "Note that there is a sum over c and k, it doesn’t matter which is the cluster that contains a particular label, it is sufficient that there is at least one. This is useful when running unsupervised methods whose output has nothing to do with the labels."
},
{
"code": null,
"e": 2263,
"s": 2096,
"text": "Here an example of homogeneous clustering. All three clusters contains only one color (feature), in other words all the samples in the same cluster share their label."
},
{
"code": null,
"e": 2401,
"s": 2263,
"text": "Anyway this situation is not optimal since orange samples are split into different clusters . In this example, a feature is not complete."
},
{
"code": null,
"e": 2503,
"s": 2401,
"text": "Completeness although measures how much similar samples are put together by the clustering algorithm."
},
{
"code": null,
"e": 2728,
"s": 2503,
"text": "It is easy to understand why this is the case. If one looks at the term H(K|C) it contains nck / nc which represents the ratio between the number of samples labelled c in cluster k and the total number of samples labelled c."
},
{
"code": null,
"e": 2824,
"s": 2728,
"text": "When all samples of kind c have been assigned to the same cluster k, the completeness equals 1."
},
{
"code": null,
"e": 3082,
"s": 2824,
"text": "Here an example of a complete clustering. Each color is present only in one group. In this case all points with the same property have been classified together. Note that complete doesn’t imply homogeneous, in fact in each cluster there are multiple colors."
},
{
"code": null,
"e": 3467,
"s": 3082,
"text": "Now we have understood this two metrics it is clear that an optimal algorithm would be able to obtain a partition which is both homogeneous and complete. In this case, all samples with a particular color are put together in a cluster and that cluster contains only them. If the algorithms was unsupervised it should be clear that with this output it has learnt correctly the features."
},
{
"code": null,
"e": 3697,
"s": 3467,
"text": "Otherwise, the worst clustering possible is one which is neither homogeneous or complete. In this case each cluster contains multiple labels and each label is assigned to multiple clusters. In the case both the measures are zero."
},
{
"code": null,
"e": 3912,
"s": 3697,
"text": "Finally to obtain a measure of the goodness of our clustering algorithm we can consider the harmonic average between homogeneity and completeness and obtain the V-measure or Normalised Mutual Information (NMI) [1]."
},
{
"code": null,
"e": 4216,
"s": 3912,
"text": "This score is a measure between 0–1 that actually quantifies the goodness of the clustering partition. In fact, it requires that both homogeneity h and completeness c are maximised (NMI is 1 when both h and c are 1). Moreover if the clustering doesn’t satisfy any of the two conditions NMI will be zero."
},
{
"code": null,
"e": 4380,
"s": 4216,
"text": "There are many measures of this kind, but thank to its factorisation in the two measures homogeneity and completeness, its interpretability is clear and intuitive."
},
{
"code": null,
"e": 4516,
"s": 4380,
"text": "So, now you have performed a clustering and want to estimate NMI. Sci-kit learn has it implemented so it is really easy to estimate it."
},
{
"code": null,
"e": 4533,
"s": 4516,
"text": "scikit-learn.org"
},
{
"code": null,
"e": 4707,
"s": 4533,
"text": "Here a simple example. From this example it is also clear that the score doesn’t depend on the labels’ names, as discussed before it is the same for every label permutation."
},
{
"code": null,
"e": 4859,
"s": 4707,
"text": "from sklearn.metrics.cluster import v_measure_score>>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1])1.0>>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0])1.0"
},
{
"code": null,
"e": 5116,
"s": 4859,
"text": "Hirschberg, J.B.; Rosenberg, A. V-Measure: A conditional entropy-based external cluster evaluation. (2007), Proceedings of EMNLP.Valle, F.; Osella, M.; Caselle, M. A Topic Modeling Analysis of TCGA Breast and Lung Cancer Transcriptomic Data. (2020) Cancers"
},
{
"code": null,
"e": 5246,
"s": 5116,
"text": "Hirschberg, J.B.; Rosenberg, A. V-Measure: A conditional entropy-based external cluster evaluation. (2007), Proceedings of EMNLP."
},
{
"code": null,
"e": 5374,
"s": 5246,
"text": "Valle, F.; Osella, M.; Caselle, M. A Topic Modeling Analysis of TCGA Breast and Lung Cancer Transcriptomic Data. (2020) Cancers"
}
] |
get_screenshot_as_file driver method - Selenium Python - GeeksforGeeks
|
02 Jul, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_screenshot_as_file driver method in Selenium. get_screenshot_as_file method saves a screenshot of the current window to a PNG image file. It returns False if there is any IOError, else returns True.
Syntax –
driver.get_screenshot_as_file("filename.png")
Example –Now one can use get_screenshot_as_file method as a driver method as below –
driver.get("https://www.geeksforgeeks.org/")
driver.get_screenshot_as_file("foo.png")
To demonstrate, get_screenshot_as_file method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get screenshot,
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get Screenshotprint(driver.get_screenshot_as_file("foo.png"))
Output –Screenshot added –
Akanksha_Rai
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 25030,
"s": 24292,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 25262,
"s": 25030,
"text": "This article revolves around get_screenshot_as_file driver method in Selenium. get_screenshot_as_file method saves a screenshot of the current window to a PNG image file. It returns False if there is any IOError, else returns True."
},
{
"code": null,
"e": 25271,
"s": 25262,
"text": "Syntax –"
},
{
"code": null,
"e": 25317,
"s": 25271,
"text": "driver.get_screenshot_as_file(\"filename.png\")"
},
{
"code": null,
"e": 25402,
"s": 25317,
"text": "Example –Now one can use get_screenshot_as_file method as a driver method as below –"
},
{
"code": null,
"e": 25489,
"s": 25402,
"text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_screenshot_as_file(\"foo.png\")\n"
},
{
"code": null,
"e": 25664,
"s": 25489,
"text": "To demonstrate, get_screenshot_as_file method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get screenshot,"
},
{
"code": null,
"e": 25674,
"s": 25664,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get Screenshotprint(driver.get_screenshot_as_file(\"foo.png\"))",
"e": 25914,
"s": 25674,
"text": null
},
{
"code": null,
"e": 25941,
"s": 25914,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 25954,
"s": 25941,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 25970,
"s": 25954,
"text": "Python-selenium"
},
{
"code": null,
"e": 25979,
"s": 25970,
"text": "selenium"
},
{
"code": null,
"e": 25986,
"s": 25979,
"text": "Python"
},
{
"code": null,
"e": 26084,
"s": 25986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26116,
"s": 26084,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26172,
"s": 26116,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26214,
"s": 26172,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26256,
"s": 26214,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26278,
"s": 26256,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26317,
"s": 26278,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26348,
"s": 26317,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26403,
"s": 26348,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26432,
"s": 26403,
"text": "Create a directory in Python"
}
] |
Program to find length of longest consecutive sequence in Python
|
Suppose we have an unsorted array of numbers, we have to find the length of the longest
sequence of consecutive elements.
So, if the input is like nums = [70, 7, 50, 4, 6, 5], then the output will be 4, as the longest
sequence of consecutive elements is [4, 5, 6, 7]. so we return its length: 4.
To solve this, we will follow these steps −
nums := all unique elements of nums
nums := all unique elements of nums
max_cnt := 0
max_cnt := 0
for each num in nums, doif num - 1 not in nums, thencnt := 0while num is present in nums, donum := num + 1cnt := cnt + 1max_cnt := maximum of max_cnt and cnt
for each num in nums, do
if num - 1 not in nums, thencnt := 0while num is present in nums, donum := num + 1cnt := cnt + 1max_cnt := maximum of max_cnt and cnt
if num - 1 not in nums, then
cnt := 0
cnt := 0
while num is present in nums, donum := num + 1cnt := cnt + 1
while num is present in nums, do
num := num + 1
num := num + 1
cnt := cnt + 1
cnt := cnt + 1
max_cnt := maximum of max_cnt and cnt
max_cnt := maximum of max_cnt and cnt
return max_cnt
return max_cnt
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
nums = set(nums)
max_cnt = 0
for num in nums:
if num - 1 not in nums:
cnt = 0
while num in nums:
num += 1
cnt += 1
max_cnt = max(max_cnt, cnt)
return max_cnt
ob = Solution()
nums = [70, 7, 50, 4, 6, 5]
print(ob.solve(nums))
[70, 7, 50, 4, 6, 5]
4
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "Suppose we have an unsorted array of numbers, we have to find the length of the longest\nsequence of consecutive elements."
},
{
"code": null,
"e": 1358,
"s": 1184,
"text": "So, if the input is like nums = [70, 7, 50, 4, 6, 5], then the output will be 4, as the longest\nsequence of consecutive elements is [4, 5, 6, 7]. so we return its length: 4."
},
{
"code": null,
"e": 1402,
"s": 1358,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1438,
"s": 1402,
"text": "nums := all unique elements of nums"
},
{
"code": null,
"e": 1474,
"s": 1438,
"text": "nums := all unique elements of nums"
},
{
"code": null,
"e": 1487,
"s": 1474,
"text": "max_cnt := 0"
},
{
"code": null,
"e": 1500,
"s": 1487,
"text": "max_cnt := 0"
},
{
"code": null,
"e": 1658,
"s": 1500,
"text": "for each num in nums, doif num - 1 not in nums, thencnt := 0while num is present in nums, donum := num + 1cnt := cnt + 1max_cnt := maximum of max_cnt and cnt"
},
{
"code": null,
"e": 1683,
"s": 1658,
"text": "for each num in nums, do"
},
{
"code": null,
"e": 1817,
"s": 1683,
"text": "if num - 1 not in nums, thencnt := 0while num is present in nums, donum := num + 1cnt := cnt + 1max_cnt := maximum of max_cnt and cnt"
},
{
"code": null,
"e": 1846,
"s": 1817,
"text": "if num - 1 not in nums, then"
},
{
"code": null,
"e": 1855,
"s": 1846,
"text": "cnt := 0"
},
{
"code": null,
"e": 1864,
"s": 1855,
"text": "cnt := 0"
},
{
"code": null,
"e": 1925,
"s": 1864,
"text": "while num is present in nums, donum := num + 1cnt := cnt + 1"
},
{
"code": null,
"e": 1958,
"s": 1925,
"text": "while num is present in nums, do"
},
{
"code": null,
"e": 1973,
"s": 1958,
"text": "num := num + 1"
},
{
"code": null,
"e": 1988,
"s": 1973,
"text": "num := num + 1"
},
{
"code": null,
"e": 2003,
"s": 1988,
"text": "cnt := cnt + 1"
},
{
"code": null,
"e": 2018,
"s": 2003,
"text": "cnt := cnt + 1"
},
{
"code": null,
"e": 2056,
"s": 2018,
"text": "max_cnt := maximum of max_cnt and cnt"
},
{
"code": null,
"e": 2094,
"s": 2056,
"text": "max_cnt := maximum of max_cnt and cnt"
},
{
"code": null,
"e": 2109,
"s": 2094,
"text": "return max_cnt"
},
{
"code": null,
"e": 2124,
"s": 2109,
"text": "return max_cnt"
},
{
"code": null,
"e": 2194,
"s": 2124,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2205,
"s": 2194,
"text": " Live Demo"
},
{
"code": null,
"e": 2570,
"s": 2205,
"text": "class Solution:\n def solve(self, nums):\n nums = set(nums)\n max_cnt = 0\n for num in nums:\n if num - 1 not in nums:\n cnt = 0\n while num in nums:\n num += 1\n cnt += 1\n max_cnt = max(max_cnt, cnt)\n return max_cnt\nob = Solution()\nnums = [70, 7, 50, 4, 6, 5]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 2591,
"s": 2570,
"text": "[70, 7, 50, 4, 6, 5]"
},
{
"code": null,
"e": 2593,
"s": 2591,
"text": "4"
}
] |
Python SQLite - Insert Data
|
You can add new rows to an existing table of SQLite using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names).
Following is the recommended syntax of the INSERT statement −
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Where, column1, column2, column3,.. are the names of the columns of a table and value1, value2, value3,... are the values you need to insert into the table.
Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below −
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>
Following PostgreSQL statement inserts a row in the above created table.
sqlite> insert into CRICKETERS
(First_Name, Last_Name, Age, Place_Of_Birth, Country) values
('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
sqlite>
While inserting records using the INSERT INTO statement, if you skip any columns names, this record will be inserted leaving empty spaces at columns which you have skipped.
sqlite> insert into CRICKETERS
(First_Name, Last_Name, Country) values
('Jonathan', 'Trott', 'SouthAfrica');
sqlite>
You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table.
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>
After inserting the records into a table you can verify its contents using the SELECT statement as shown below −
sqlite> select * from cricketers;
Shikhar | Dhawan | 33 | Delhi | India
Jonathan | Trott | | | SouthAfrica
Kumara | Sangakkara | 41 | Matale | Srilanka
Virat | Kohli | 30 | Delhi | India
Rohit | Sharma | 32 | Nagpur | India
sqlite>
To add records to an existing table in SQLite database −
Import sqlite3 package.
Import sqlite3 package.
Create a connection object using the connect() method by passing the name of the database as a parameter to it.
Create a connection object using the connect() method by passing the name of the database as a parameter to it.
The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object.
The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object.
Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it.
Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it.
Following python example inserts records into to a table named EMPLOYEE −
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Preparing SQL queries to INSERT a record into the database.
cursor.execute('''INSERT INTO EMPLOYEE(
FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES
('Ramya', 'Rama Priya', 27, 'F', 9000)''')
cursor.execute('''INSERT INTO EMPLOYEE(
FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES
('Vinay', 'Battacharya', 20, 'M', 6000)''')
cursor.execute('''INSERT INTO EMPLOYEE(
FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES
('Sharukh', 'Sheik', 25, 'M', 8300)''')
cursor.execute('''INSERT INTO EMPLOYEE(
FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES
('Sarmista', 'Sharma', 26, 'F', 10000)''')
cursor.execute('''INSERT INTO EMPLOYEE(
FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES
('Tripthi', 'Mishra', 24, 'F', 6000)''')
# Commit your changes in the database
conn.commit()
print("Records inserted........")
# Closing the connection
conn.close()
Records inserted........
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": 3404,
"s": 3205,
"text": "You can add new rows to an existing table of SQLite using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names)."
},
{
"code": null,
"e": 3466,
"s": 3404,
"text": "Following is the recommended syntax of the INSERT statement −"
},
{
"code": null,
"e": 3572,
"s": 3466,
"text": "INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\n"
},
{
"code": null,
"e": 3729,
"s": 3572,
"text": "Where, column1, column2, column3,.. are the names of the columns of a table and value1, value2, value3,... are the values you need to insert into the table."
},
{
"code": null,
"e": 3831,
"s": 3729,
"text": "Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below −"
},
{
"code": null,
"e": 3999,
"s": 3831,
"text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>"
},
{
"code": null,
"e": 4072,
"s": 3999,
"text": "Following PostgreSQL statement inserts a row in the above created table."
},
{
"code": null,
"e": 4225,
"s": 4072,
"text": "sqlite> insert into CRICKETERS \n (First_Name, Last_Name, Age, Place_Of_Birth, Country) values\n ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite>\n"
},
{
"code": null,
"e": 4398,
"s": 4225,
"text": "While inserting records using the INSERT INTO statement, if you skip any columns names, this record will be inserted leaving empty spaces at columns which you have skipped."
},
{
"code": null,
"e": 4524,
"s": 4398,
"text": "sqlite> insert into CRICKETERS \n (First_Name, Last_Name, Country) values \n ('Jonathan', 'Trott', 'SouthAfrica');\nsqlite>\n"
},
{
"code": null,
"e": 4689,
"s": 4524,
"text": "You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table."
},
{
"code": null,
"e": 4946,
"s": 4689,
"text": "sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>"
},
{
"code": null,
"e": 5059,
"s": 4946,
"text": "After inserting the records into a table you can verify its contents using the SELECT statement as shown below −"
},
{
"code": null,
"e": 5331,
"s": 5059,
"text": "sqlite> select * from cricketers;\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | | | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\nsqlite>\n"
},
{
"code": null,
"e": 5388,
"s": 5331,
"text": "To add records to an existing table in SQLite database −"
},
{
"code": null,
"e": 5412,
"s": 5388,
"text": "Import sqlite3 package."
},
{
"code": null,
"e": 5436,
"s": 5412,
"text": "Import sqlite3 package."
},
{
"code": null,
"e": 5548,
"s": 5436,
"text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it."
},
{
"code": null,
"e": 5660,
"s": 5548,
"text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it."
},
{
"code": null,
"e": 5847,
"s": 5660,
"text": "The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object."
},
{
"code": null,
"e": 6034,
"s": 5847,
"text": "The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object."
},
{
"code": null,
"e": 6143,
"s": 6034,
"text": "Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it."
},
{
"code": null,
"e": 6252,
"s": 6143,
"text": "Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it."
},
{
"code": null,
"e": 6326,
"s": 6252,
"text": "Following python example inserts records into to a table named EMPLOYEE −"
},
{
"code": null,
"e": 7356,
"s": 6326,
"text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n# Preparing SQL queries to INSERT a record into the database.\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Ramya', 'Rama Priya', 27, 'F', 9000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Vinay', 'Battacharya', 20, 'M', 6000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sharukh', 'Sheik', 25, 'M', 8300)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sarmista', 'Sharma', 26, 'F', 10000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Tripthi', 'Mishra', 24, 'F', 6000)''')\n\n# Commit your changes in the database\nconn.commit()\nprint(\"Records inserted........\")\n\n# Closing the connection\nconn.close()"
},
{
"code": null,
"e": 7382,
"s": 7356,
"text": "Records inserted........\n"
},
{
"code": null,
"e": 7419,
"s": 7382,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7435,
"s": 7419,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7468,
"s": 7435,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7487,
"s": 7468,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7522,
"s": 7487,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7544,
"s": 7522,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7578,
"s": 7544,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7606,
"s": 7578,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7641,
"s": 7606,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7655,
"s": 7641,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7688,
"s": 7655,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7705,
"s": 7688,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7712,
"s": 7705,
"text": " Print"
},
{
"code": null,
"e": 7723,
"s": 7712,
"text": " Add Notes"
}
] |
Automate Stacking In Python. How to Boost Your Performance While... | by Lukas Frei | Towards Data Science
|
Utilizing stacking (stacked generalizations) is a very hot topic when it comes to pushing your machine learning algorithm to new heights. For instance, most if not all winning Kaggle submissions nowadays make use of some form of stacking or a variation of it. First introduced in the 1992 paper Stacked Generalization by David Wolpert, their main purpose is to reduce the generalization error. According to Wolpert, they can be understood “as a more sophisticated version of cross-validation”. While Wolpert himself noted at the time that large parts of stacked generalizations are “black art”, it seems that building larger and larger stacked generalizations win over smaller stacked generalizations. However, as these models keep increasing in size, they also increase in complexity. Automating the process of building different architectures would significantly simplify this process. The remainder of this article will deal with the package vecstack I recently came across that is attempting just this.
The main idea behind the structure of a stacked generalization is to use one or more first level models, make predictions using these models and then use these predictions as features to fit one or more second level models on top. To avoid overfitting, cross-validation is usually used to predict the OOF (out-of-fold) part of the training set. There are two different variants available in this package but I’m going to describe ‘Variant A’ in this paragraph. To get the final predictions in this variant, we take the mean or mode of all of our predictions. The whole process can be visualized using this GIF from vecstacks’ documentation:
After having taken a look at the documentation, it was time to try using the package myself and see how it works. To do so, I decided to use the wine data set available on the UCI Machine Learning Repository. The problem statement for this data set is to use the 13 features, which all represent different aspects of the wine, to predict from which of three cultivars in Italy the wine was derived.
To get started, let’s first import the packages we are going to need for our project:
import pandas as pdfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.ensemble import RandomForestClassifierfrom xgboost import XGBClassifierfrom vecstack import stacking
Now we are ready to import our data and take a look at it to gain a better understanding of what it looks like:
link = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'names = ['Class', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash' ,'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline']df = pd.read_csv(link, header=None, names=names)df.sample(5)
Running the code chunk above gives us:
Note that I used .sample() instead if .head() to avoid being potentially misled by assuming the entire data set has the structure of the first five rows. Luckily, this data set does not have any missing values, so we can easily use it to test our package right away without any of the usually required data cleaning and preparation.
Following this, we are going to separate the response from the input variables and perform an 80:20 train-test-split following the example on vecstacks’ documentation.
y = df[['Class']]X = df.iloc[:,1:]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
We are getting closer to the interesting part. Remember the GIF from earlier? It is time now to define a few first level models for our stacked generalization. This step definitely deserves its own article but for purposes of simplicity, we are going to use three models: A KNN-Classifier, a Random Forest Classifier and an XGBoost Classifier.
models = [ KNeighborsClassifier(n_neighbors=5, n_jobs=-1), RandomForestClassifier(random_state=0, n_jobs=-1, n_estimators=100, max_depth=3), XGBClassifier(random_state=0, n_jobs=-1, learning_rate=0.1, n_estimators=100, max_depth=3)]
These parameters were not tuned prior to setting them as the purpose of this article is testing the package. If you were to optimize performance, you should not just copy and paste these.
Taking the next part of code from the documentation, we are essentially performing the GIF’s first part using first level models to make predictions:
S_train, S_test = stacking(models, X_train, y_train, X_test, regression=False, mode='oof_pred_bag', needs_proba=False, save_dir=None, metric=accuracy_score, n_folds=4, stratified=True, shuffle=True, random_state=0, verbose=2)
The stacking function takes several inputs:
models: the first level models we defined earlier
X_train, y_train, X_test: our data
regression: Boolean indicating whether we want to use the function for regression. In our case set to False since this is a classification
mode: using the earlier describe out-of-fold during cross-validation
needs_proba: Boolean indicating whether you need the probabilities of class labels
save_dir: save the result to directory Boolean
metric: what evaluation metric to use (we imported the accuracy_score in the beginning)
n_folds: how many folds to use for cross-validation
stratified: whether to use stratified cross-validation
shuffle: whether to shuffle the data
random_state: setting a random state for reproducibility
verbose: 2 here refers to printing all info
Doing so, we get the following output:
task: [classification]n_classes: [3]metric: [accuracy_score]mode: [oof_pred_bag]n_models: [4]model 0: [KNeighborsClassifier] fold 0: [0.72972973] fold 1: [0.61111111] fold 2: [0.62857143] fold 3: [0.76470588] ---- MEAN: [0.68352954] + [0.06517070] FULL: [0.68309859]model 1: [ExtraTreesClassifier] fold 0: [0.97297297] fold 1: [1.00000000] fold 2: [0.94285714] fold 3: [1.00000000] ---- MEAN: [0.97895753] + [0.02358296] FULL: [0.97887324]model 2: [RandomForestClassifier] fold 0: [1.00000000] fold 1: [1.00000000] fold 2: [0.94285714] fold 3: [1.00000000] ---- MEAN: [0.98571429] + [0.02474358] FULL: [0.98591549]model 3: [XGBClassifier] fold 0: [1.00000000] fold 1: [0.97222222] fold 2: [0.91428571] fold 3: [0.97058824] ---- MEAN: [0.96427404] + [0.03113768] FULL: [0.96478873]
Again, referring to the GIF, all that’s left to do now is fit the second level model(s) of our choice on our predictions to make our final predictions. In our case, we are going to use an XGBoost Classifier. This step is not significantly different from a regular fit-and-predict in sklearn except for the fact that instead of using X_train to train our model, we are using our predictions S_train.
model = XGBClassifier(random_state=0, n_jobs=-1, learning_rate=0.1, n_estimators=100, max_depth=3) model = model.fit(S_train, y_train)y_pred = model.predict(S_test)print('Final prediction score: [%.8f]' % accuracy_score(y_test, y_pred))Output: Final prediction score: [0.97222222]
Using vecstacks’ stacking automation, we’ve managed to predict the correct wine cultivar with an accuracy of approximately 97.2%! As you can see, the API does not collide with the sklearn API and could, therefore, provide a helpful tool when trying to speed up your stacking workflow.
As always, if you have any feedback or found mistakes, please don’t hesitate to reach out to me.
References:
[1] David H. Wolpert, Stacked Generalization (1992), Neural Networks
[2] Igor Ivanov, Vecstack (2016), GitHub
[3] M. Forina et al, Wine Data Set (1991), UCI Machine Learning Repository
|
[
{
"code": null,
"e": 1179,
"s": 172,
"text": "Utilizing stacking (stacked generalizations) is a very hot topic when it comes to pushing your machine learning algorithm to new heights. For instance, most if not all winning Kaggle submissions nowadays make use of some form of stacking or a variation of it. First introduced in the 1992 paper Stacked Generalization by David Wolpert, their main purpose is to reduce the generalization error. According to Wolpert, they can be understood “as a more sophisticated version of cross-validation”. While Wolpert himself noted at the time that large parts of stacked generalizations are “black art”, it seems that building larger and larger stacked generalizations win over smaller stacked generalizations. However, as these models keep increasing in size, they also increase in complexity. Automating the process of building different architectures would significantly simplify this process. The remainder of this article will deal with the package vecstack I recently came across that is attempting just this."
},
{
"code": null,
"e": 1820,
"s": 1179,
"text": "The main idea behind the structure of a stacked generalization is to use one or more first level models, make predictions using these models and then use these predictions as features to fit one or more second level models on top. To avoid overfitting, cross-validation is usually used to predict the OOF (out-of-fold) part of the training set. There are two different variants available in this package but I’m going to describe ‘Variant A’ in this paragraph. To get the final predictions in this variant, we take the mean or mode of all of our predictions. The whole process can be visualized using this GIF from vecstacks’ documentation:"
},
{
"code": null,
"e": 2219,
"s": 1820,
"text": "After having taken a look at the documentation, it was time to try using the package myself and see how it works. To do so, I decided to use the wine data set available on the UCI Machine Learning Repository. The problem statement for this data set is to use the 13 features, which all represent different aspects of the wine, to predict from which of three cultivars in Italy the wine was derived."
},
{
"code": null,
"e": 2305,
"s": 2219,
"text": "To get started, let’s first import the packages we are going to need for our project:"
},
{
"code": null,
"e": 2620,
"s": 2305,
"text": "import pandas as pdfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.ensemble import RandomForestClassifierfrom xgboost import XGBClassifierfrom vecstack import stacking"
},
{
"code": null,
"e": 2732,
"s": 2620,
"text": "Now we are ready to import our data and take a look at it to gain a better understanding of what it looks like:"
},
{
"code": null,
"e": 3128,
"s": 2732,
"text": "link = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'names = ['Class', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash' ,'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline']df = pd.read_csv(link, header=None, names=names)df.sample(5)"
},
{
"code": null,
"e": 3167,
"s": 3128,
"text": "Running the code chunk above gives us:"
},
{
"code": null,
"e": 3500,
"s": 3167,
"text": "Note that I used .sample() instead if .head() to avoid being potentially misled by assuming the entire data set has the structure of the first five rows. Luckily, this data set does not have any missing values, so we can easily use it to test our package right away without any of the usually required data cleaning and preparation."
},
{
"code": null,
"e": 3668,
"s": 3500,
"text": "Following this, we are going to separate the response from the input variables and perform an 80:20 train-test-split following the example on vecstacks’ documentation."
},
{
"code": null,
"e": 3791,
"s": 3668,
"text": "y = df[['Class']]X = df.iloc[:,1:]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)"
},
{
"code": null,
"e": 4135,
"s": 3791,
"text": "We are getting closer to the interesting part. Remember the GIF from earlier? It is time now to define a few first level models for our stacked generalization. This step definitely deserves its own article but for purposes of simplicity, we are going to use three models: A KNN-Classifier, a Random Forest Classifier and an XGBoost Classifier."
},
{
"code": null,
"e": 4461,
"s": 4135,
"text": "models = [ KNeighborsClassifier(n_neighbors=5, n_jobs=-1), RandomForestClassifier(random_state=0, n_jobs=-1, n_estimators=100, max_depth=3), XGBClassifier(random_state=0, n_jobs=-1, learning_rate=0.1, n_estimators=100, max_depth=3)]"
},
{
"code": null,
"e": 4649,
"s": 4461,
"text": "These parameters were not tuned prior to setting them as the purpose of this article is testing the package. If you were to optimize performance, you should not just copy and paste these."
},
{
"code": null,
"e": 4799,
"s": 4649,
"text": "Taking the next part of code from the documentation, we are essentially performing the GIF’s first part using first level models to make predictions:"
},
{
"code": null,
"e": 5431,
"s": 4799,
"text": "S_train, S_test = stacking(models, X_train, y_train, X_test, regression=False, mode='oof_pred_bag', needs_proba=False, save_dir=None, metric=accuracy_score, n_folds=4, stratified=True, shuffle=True, random_state=0, verbose=2)"
},
{
"code": null,
"e": 5475,
"s": 5431,
"text": "The stacking function takes several inputs:"
},
{
"code": null,
"e": 5525,
"s": 5475,
"text": "models: the first level models we defined earlier"
},
{
"code": null,
"e": 5560,
"s": 5525,
"text": "X_train, y_train, X_test: our data"
},
{
"code": null,
"e": 5699,
"s": 5560,
"text": "regression: Boolean indicating whether we want to use the function for regression. In our case set to False since this is a classification"
},
{
"code": null,
"e": 5768,
"s": 5699,
"text": "mode: using the earlier describe out-of-fold during cross-validation"
},
{
"code": null,
"e": 5851,
"s": 5768,
"text": "needs_proba: Boolean indicating whether you need the probabilities of class labels"
},
{
"code": null,
"e": 5898,
"s": 5851,
"text": "save_dir: save the result to directory Boolean"
},
{
"code": null,
"e": 5986,
"s": 5898,
"text": "metric: what evaluation metric to use (we imported the accuracy_score in the beginning)"
},
{
"code": null,
"e": 6038,
"s": 5986,
"text": "n_folds: how many folds to use for cross-validation"
},
{
"code": null,
"e": 6093,
"s": 6038,
"text": "stratified: whether to use stratified cross-validation"
},
{
"code": null,
"e": 6130,
"s": 6093,
"text": "shuffle: whether to shuffle the data"
},
{
"code": null,
"e": 6187,
"s": 6130,
"text": "random_state: setting a random state for reproducibility"
},
{
"code": null,
"e": 6231,
"s": 6187,
"text": "verbose: 2 here refers to printing all info"
},
{
"code": null,
"e": 6270,
"s": 6231,
"text": "Doing so, we get the following output:"
},
{
"code": null,
"e": 7248,
"s": 6270,
"text": "task: [classification]n_classes: [3]metric: [accuracy_score]mode: [oof_pred_bag]n_models: [4]model 0: [KNeighborsClassifier] fold 0: [0.72972973] fold 1: [0.61111111] fold 2: [0.62857143] fold 3: [0.76470588] ---- MEAN: [0.68352954] + [0.06517070] FULL: [0.68309859]model 1: [ExtraTreesClassifier] fold 0: [0.97297297] fold 1: [1.00000000] fold 2: [0.94285714] fold 3: [1.00000000] ---- MEAN: [0.97895753] + [0.02358296] FULL: [0.97887324]model 2: [RandomForestClassifier] fold 0: [1.00000000] fold 1: [1.00000000] fold 2: [0.94285714] fold 3: [1.00000000] ---- MEAN: [0.98571429] + [0.02474358] FULL: [0.98591549]model 3: [XGBClassifier] fold 0: [1.00000000] fold 1: [0.97222222] fold 2: [0.91428571] fold 3: [0.97058824] ---- MEAN: [0.96427404] + [0.03113768] FULL: [0.96478873]"
},
{
"code": null,
"e": 7647,
"s": 7248,
"text": "Again, referring to the GIF, all that’s left to do now is fit the second level model(s) of our choice on our predictions to make our final predictions. In our case, we are going to use an XGBoost Classifier. This step is not significantly different from a regular fit-and-predict in sklearn except for the fact that instead of using X_train to train our model, we are using our predictions S_train."
},
{
"code": null,
"e": 7953,
"s": 7647,
"text": "model = XGBClassifier(random_state=0, n_jobs=-1, learning_rate=0.1, n_estimators=100, max_depth=3) model = model.fit(S_train, y_train)y_pred = model.predict(S_test)print('Final prediction score: [%.8f]' % accuracy_score(y_test, y_pred))Output: Final prediction score: [0.97222222]"
},
{
"code": null,
"e": 8238,
"s": 7953,
"text": "Using vecstacks’ stacking automation, we’ve managed to predict the correct wine cultivar with an accuracy of approximately 97.2%! As you can see, the API does not collide with the sklearn API and could, therefore, provide a helpful tool when trying to speed up your stacking workflow."
},
{
"code": null,
"e": 8335,
"s": 8238,
"text": "As always, if you have any feedback or found mistakes, please don’t hesitate to reach out to me."
},
{
"code": null,
"e": 8347,
"s": 8335,
"text": "References:"
},
{
"code": null,
"e": 8416,
"s": 8347,
"text": "[1] David H. Wolpert, Stacked Generalization (1992), Neural Networks"
},
{
"code": null,
"e": 8457,
"s": 8416,
"text": "[2] Igor Ivanov, Vecstack (2016), GitHub"
}
] |
Struts 2 - Environment Setup
|
Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2.
I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track −
You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you should be inputting the following line in your C:\autoexec.bat file.
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
Alternatively, on Windows NT/2000/XP −
You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as per the given document of IDE.
You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location.
For example in C:\apache-tomcat-6.0.33 on windows, or /usr/local/apachetomcat-6.0.33 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
You can start Tomcat by executing the following commands on windows machine, or you can simply double click on startup.bat
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-6.0.33\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-6.0.33/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it should display the following result −
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat website: https://tomcat.apache.org/
Tomcat can be stopped by executing the following commands on windows machine −
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
All the examples in this tutorial are written using Eclipse IDE. I suggest that, you have the latest version of Eclipse installed in your machine.
To install Eclipse Download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location.
For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine, it should display the following result −
Now if everything is fine, then you can proceed to setup your Struts2 framemwork. Following are the simple steps to download and install Struts2 on your machine.
Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
Download the latest version of Struts2 binaries from https://struts.apache.org/download.cgi.
Download the latest version of Struts2 binaries from https://struts.apache.org/download.cgi.
At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:\struts-2.2.3 as follows.
At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:\struts-2.2.3 as follows.
Second step is to extract the zip file in any location, I downloaded & extracted struts-2.2.3-all.zip in c:\ folder on my Windows 7 machine so that I have all the jar files into C:\struts-2.2.3\lib. Make sure you set your CLASSPATH variable properly otherwise you will face problem while running your application.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2417,
"s": 2246,
"text": "Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2."
},
{
"code": null,
"e": 2595,
"s": 2417,
"text": "I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track −"
},
{
"code": null,
"e": 2992,
"s": 2595,
"text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively."
},
{
"code": null,
"e": 3133,
"s": 2992,
"text": "If you are running Windows and installed the SDK in C:\\jdk1.5.0_20, you should be inputting the following line in your C:\\autoexec.bat file."
},
{
"code": null,
"e": 3201,
"s": 3133,
"text": "set PATH = C:\\jdk1.5.0_20\\bin;%PATH%\nset JAVA_HOME = C:\\jdk1.5.0_20"
},
{
"code": null,
"e": 3240,
"s": 3201,
"text": "Alternatively, on Windows NT/2000/XP −"
},
{
"code": null,
"e": 3401,
"s": 3240,
"text": "You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button."
},
{
"code": null,
"e": 3562,
"s": 3401,
"text": "You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button."
},
{
"code": null,
"e": 3720,
"s": 3562,
"text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file."
},
{
"code": null,
"e": 3878,
"s": 3720,
"text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file."
},
{
"code": null,
"e": 4036,
"s": 3878,
"text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file."
},
{
"code": null,
"e": 4121,
"s": 4036,
"text": "setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH\nsetenv JAVA_HOME /usr/local/jdk1.5.0_20"
},
{
"code": null,
"e": 4406,
"s": 4121,
"text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as per the given document of IDE."
},
{
"code": null,
"e": 4582,
"s": 4406,
"text": "You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location."
},
{
"code": null,
"e": 4756,
"s": 4582,
"text": "For example in C:\\apache-tomcat-6.0.33 on windows, or /usr/local/apachetomcat-6.0.33 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations."
},
{
"code": null,
"e": 4879,
"s": 4756,
"text": "You can start Tomcat by executing the following commands on windows machine, or you can simply double click on startup.bat"
},
{
"code": null,
"e": 4958,
"s": 4879,
"text": "%CATALINA_HOME%\\bin\\startup.bat\n \nor\n \nC:\\apache-tomcat-6.0.33\\bin\\startup.bat"
},
{
"code": null,
"e": 5057,
"s": 4958,
"text": "Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −"
},
{
"code": null,
"e": 5141,
"s": 5057,
"text": "$CATALINA_HOME/bin/startup.sh\n \nor\n \n/usr/local/apache-tomcat-6.0.33/bin/startup.sh"
},
{
"code": null,
"e": 5342,
"s": 5141,
"text": "After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it should display the following result −"
},
{
"code": null,
"e": 5509,
"s": 5342,
"text": "Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat website: https://tomcat.apache.org/"
},
{
"code": null,
"e": 5588,
"s": 5509,
"text": "Tomcat can be stopped by executing the following commands on windows machine −"
},
{
"code": null,
"e": 5659,
"s": 5588,
"text": "%CATALINA_HOME%\\bin\\shutdown\n\nor\n\nC:\\apache-tomcat-5.5.29\\bin\\shutdown"
},
{
"code": null,
"e": 5758,
"s": 5659,
"text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −"
},
{
"code": null,
"e": 5842,
"s": 5758,
"text": "$CATALINA_HOME/bin/shutdown.sh\n\nor\n\n/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh"
},
{
"code": null,
"e": 5989,
"s": 5842,
"text": "All the examples in this tutorial are written using Eclipse IDE. I suggest that, you have the latest version of Eclipse installed in your machine."
},
{
"code": null,
"e": 6181,
"s": 5989,
"text": "To install Eclipse Download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location."
},
{
"code": null,
"e": 6425,
"s": 6181,
"text": "For example in C:\\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe"
},
{
"code": null,
"e": 6449,
"s": 6425,
"text": "%C:\\eclipse\\eclipse.exe"
},
{
"code": null,
"e": 6549,
"s": 6449,
"text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −"
},
{
"code": null,
"e": 6577,
"s": 6549,
"text": "$/usr/local/eclipse/eclipse"
},
{
"code": null,
"e": 6669,
"s": 6577,
"text": "After a successful startup, if everything is fine, it should display the following result −"
},
{
"code": null,
"e": 6831,
"s": 6669,
"text": "Now if everything is fine, then you can proceed to setup your Struts2 framemwork. Following are the simple steps to download and install Struts2 on your machine."
},
{
"code": null,
"e": 6992,
"s": 6831,
"text": "Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix."
},
{
"code": null,
"e": 7153,
"s": 6992,
"text": "Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix."
},
{
"code": null,
"e": 7246,
"s": 7153,
"text": "Download the latest version of Struts2 binaries from https://struts.apache.org/download.cgi."
},
{
"code": null,
"e": 7339,
"s": 7246,
"text": "Download the latest version of Struts2 binaries from https://struts.apache.org/download.cgi."
},
{
"code": null,
"e": 7523,
"s": 7339,
"text": "At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:\\struts-2.2.3 as follows."
},
{
"code": null,
"e": 7707,
"s": 7523,
"text": "At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:\\struts-2.2.3 as follows."
},
{
"code": null,
"e": 8021,
"s": 7707,
"text": "Second step is to extract the zip file in any location, I downloaded & extracted struts-2.2.3-all.zip in c:\\ folder on my Windows 7 machine so that I have all the jar files into C:\\struts-2.2.3\\lib. Make sure you set your CLASSPATH variable properly otherwise you will face problem while running your application."
},
{
"code": null,
"e": 8028,
"s": 8021,
"text": " Print"
},
{
"code": null,
"e": 8039,
"s": 8028,
"text": " Add Notes"
}
] |
Simple Ways to Read TSV Files in Python - GeeksforGeeks
|
23 Nov, 2021
In this article, we will discuss how to read TSV files in Python.
We will be using the same input file in all various implementation methods to see the output. Below is the input file from which we will read data.
We will read data from TSV file using pandas read_csv(). Along with the TSV file, we also pass separator as ‘\t’ for the tab character because, for tsv files, the tab character will separate each field.
Syntax :
data=pandas.read_csv('filename.tsv',sep='\t')
Example: Program Using Pandas
Python3
# Simple Way to Read TSV Files in Python using pandas# importing pandas libraryimport pandas as pd # Passing the TSV file to# read_csv() function# with tab separator# This function will# read data from fileinterviews_df = pd.read_csv('GeekforGeeks.tsv', sep='\t') # printing dataprint(interviews_df)
Output:
We use csv.reader() to convert the TSV file object to csv.reader object. And then pass the delimiter as ‘\t’ to the csv.reader. The delimiter is used to indicate the character which will be separating each field.
Syntax:
with open("filename.tsv") as file:
tsv_file = csv.reader(file, delimiter="\t")
Example: Program Using csv
Python3
# Simple Way to Read TSV Files in Python using csv# importing csv libraryimport csv # open .tsv filewith open("GeekforGeeks.tsv") as file: # Passing the TSV file to # reader() function # with tab delimiter # This function will # read data from file tsv_file = csv.reader(file, delimiter="\t") # printing data line by line for line in tsv_file: print(line)
Output:
The very simple way to read data from TSV File in Python is using split(). We can read a given TSV file and store its data into a list.
Syntax:
with open("filename.tsv") as file:
for line in file:
l=line.split('\t')
Example: Program Using split()
Python3
# Simple Way to Read TSV Files in Python using splitans = [] # open .tsv filewith open("GeekforGeeks.tsv") as f: # Read data line by line for line in f: # split data by tab # store it in list l=line.split('\t') # append list to ans ans.append(l) # print data line by linefor i in ans: print(i)
Output:
rushi_javiya
Picked
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25672,
"s": 25644,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 25738,
"s": 25672,
"text": "In this article, we will discuss how to read TSV files in Python."
},
{
"code": null,
"e": 25886,
"s": 25738,
"text": "We will be using the same input file in all various implementation methods to see the output. Below is the input file from which we will read data."
},
{
"code": null,
"e": 26091,
"s": 25886,
"text": " We will read data from TSV file using pandas read_csv(). Along with the TSV file, we also pass separator as ‘\\t’ for the tab character because, for tsv files, the tab character will separate each field. "
},
{
"code": null,
"e": 26100,
"s": 26091,
"text": "Syntax :"
},
{
"code": null,
"e": 26146,
"s": 26100,
"text": "data=pandas.read_csv('filename.tsv',sep='\\t')"
},
{
"code": null,
"e": 26176,
"s": 26146,
"text": "Example: Program Using Pandas"
},
{
"code": null,
"e": 26184,
"s": 26176,
"text": "Python3"
},
{
"code": "# Simple Way to Read TSV Files in Python using pandas# importing pandas libraryimport pandas as pd # Passing the TSV file to# read_csv() function# with tab separator# This function will# read data from fileinterviews_df = pd.read_csv('GeekforGeeks.tsv', sep='\\t') # printing dataprint(interviews_df)",
"e": 26484,
"s": 26184,
"text": null
},
{
"code": null,
"e": 26492,
"s": 26484,
"text": "Output:"
},
{
"code": null,
"e": 26706,
"s": 26492,
"text": " We use csv.reader() to convert the TSV file object to csv.reader object. And then pass the delimiter as ‘\\t’ to the csv.reader. The delimiter is used to indicate the character which will be separating each field."
},
{
"code": null,
"e": 26714,
"s": 26706,
"text": "Syntax:"
},
{
"code": null,
"e": 26797,
"s": 26714,
"text": "with open(\"filename.tsv\") as file:\n tsv_file = csv.reader(file, delimiter=\"\\t\")"
},
{
"code": null,
"e": 26824,
"s": 26797,
"text": "Example: Program Using csv"
},
{
"code": null,
"e": 26832,
"s": 26824,
"text": "Python3"
},
{
"code": "# Simple Way to Read TSV Files in Python using csv# importing csv libraryimport csv # open .tsv filewith open(\"GeekforGeeks.tsv\") as file: # Passing the TSV file to # reader() function # with tab delimiter # This function will # read data from file tsv_file = csv.reader(file, delimiter=\"\\t\") # printing data line by line for line in tsv_file: print(line)",
"e": 27232,
"s": 26832,
"text": null
},
{
"code": null,
"e": 27240,
"s": 27232,
"text": "Output:"
},
{
"code": null,
"e": 27376,
"s": 27240,
"text": "The very simple way to read data from TSV File in Python is using split(). We can read a given TSV file and store its data into a list."
},
{
"code": null,
"e": 27385,
"s": 27376,
"text": "Syntax: "
},
{
"code": null,
"e": 27463,
"s": 27385,
"text": "with open(\"filename.tsv\") as file:\n for line in file:\n l=line.split('\\t')"
},
{
"code": null,
"e": 27495,
"s": 27463,
"text": "Example: Program Using split() "
},
{
"code": null,
"e": 27503,
"s": 27495,
"text": "Python3"
},
{
"code": "# Simple Way to Read TSV Files in Python using splitans = [] # open .tsv filewith open(\"GeekforGeeks.tsv\") as f: # Read data line by line for line in f: # split data by tab # store it in list l=line.split('\\t') # append list to ans ans.append(l) # print data line by linefor i in ans: print(i)",
"e": 27830,
"s": 27503,
"text": null
},
{
"code": null,
"e": 27838,
"s": 27830,
"text": "Output:"
},
{
"code": null,
"e": 27851,
"s": 27838,
"text": "rushi_javiya"
},
{
"code": null,
"e": 27858,
"s": 27851,
"text": "Picked"
},
{
"code": null,
"e": 27879,
"s": 27858,
"text": "python-file-handling"
},
{
"code": null,
"e": 27886,
"s": 27879,
"text": "Python"
},
{
"code": null,
"e": 27984,
"s": 27886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28016,
"s": 27984,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28058,
"s": 28016,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28100,
"s": 28058,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28156,
"s": 28100,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28183,
"s": 28156,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28214,
"s": 28183,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28250,
"s": 28214,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28279,
"s": 28250,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28301,
"s": 28279,
"text": "Defaultdict in Python"
}
] |
Local File Inclusion (LFI) - GeeksforGeeks
|
23 Oct, 2019
A File Inclusion Vulnerability is a type of Vulnerability commonly found in PHP based websites and it is used to affect the web applications. This issue generally occurs when an application is trying to get some information from a particular server where the inputs for getting a particular file location are not treated as a trusted source.
It generally refers to an inclusion attack where an attacker can supply a valid input to get a response from a web server. In response, an attacker will be able to judge whether the input which he supplied is valid or not. If it is valid, then whatever/whichever file an attacker wants to see they can easily access it.
Below example illustrates the working procedure of an LFI vulnerability:
<?php // The Page we wish to display$file = $_GET['page']; ?>
Local File Inclusion Work: Let us understand the working of Local File Inclusion via the following example:
In the above example "$file = $_GET['page'];" $file is just a file/code for indicating that the PHP code is going to return a ‘file’ in response. The $_GET is one of the sets of instruction which will get a particular file or webpage from a web server i.e. it will request for a file. The ['page'] is an argument that will define what type of pages will be displayed in response.
Where Local LFI found ?Basically this the location
http://vulnerable_host/preview.php?file=abc.html
This is the place where an attacker can perform the LFI attack on web applications. The script can be included here in the URL that is containing various parameters upon which the attack will be performed. It is possible to include arbitrary files on the server. The affected URL by the attacker would be something like this:
http://vulnerable_host/preview.php?document=../../../../etc/passwd
Identifying Vulnerabilities within Web Application: Identifying LFI Vulnerability within the web application is easy as it is going to include a file from a web server and return it to the attacker.For example “/fi/?page=include.php” LFI would be possible in such an application if the above example or something related to such example is existing in the web application.
A Pentester would attempt to get benefit from this sort of misconfiguration i.e. he can exploit this vulnerability by manipulating the parameters.For Example “/fi/?page=include.php” this will execute successfully only if the index.php” file exists in the same directory. If not, we have to add “../” ahead of “index.php” .
Imagine this “index.php” is located in the "/var/www/html" folder and “include.php” is located in "/var/www/dvwa/vulnerabilities/lfi/" folder and you can see the responses of files from this folder location only. Now to execute a file located in another directory, we have to change our directory in URL. For example "/fi/?page=../../../index.php".
There are three kinds of scenarios possible in LFI attack:
Including Files to be Parsed by the Language’s Interpreter
Including Files that are Printed to a Page
Including Files that are Served as Downloads
Impacts of an Local File Inclusion Vulnerability: An attacker would be able to get access to the following by exploiting LFI Vulnerability:
Information Disclosure of files stored in Web Server
Passwords/Database Access
Log Files
Complete System Compromise
Remediation File Inclusion(LFI) Vulnerability:
One should not allow the file path that could be modified directly either it should be hardcoded or to be selected via hardcoded path list.
One must make sure that the required should have dynamic path concatenation i.e must contain (a-z) (0-9) instead of (/, /% etc)
There should be specific limit the API so that only inclusion from directories under it work so that Directory Traversal attack could not take place in this situation
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Top 10 Angular Libraries For Web Developers
A Freshers Guide To Programming
ML | Underfitting and Overfitting
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n23 Oct, 2019"
},
{
"code": null,
"e": 25248,
"s": 24906,
"text": "A File Inclusion Vulnerability is a type of Vulnerability commonly found in PHP based websites and it is used to affect the web applications. This issue generally occurs when an application is trying to get some information from a particular server where the inputs for getting a particular file location are not treated as a trusted source."
},
{
"code": null,
"e": 25568,
"s": 25248,
"text": "It generally refers to an inclusion attack where an attacker can supply a valid input to get a response from a web server. In response, an attacker will be able to judge whether the input which he supplied is valid or not. If it is valid, then whatever/whichever file an attacker wants to see they can easily access it."
},
{
"code": null,
"e": 25641,
"s": 25568,
"text": "Below example illustrates the working procedure of an LFI vulnerability:"
},
{
"code": "<?php // The Page we wish to display$file = $_GET['page']; ?>",
"e": 25704,
"s": 25641,
"text": null
},
{
"code": null,
"e": 25812,
"s": 25704,
"text": "Local File Inclusion Work: Let us understand the working of Local File Inclusion via the following example:"
},
{
"code": null,
"e": 26192,
"s": 25812,
"text": "In the above example \"$file = $_GET['page'];\" $file is just a file/code for indicating that the PHP code is going to return a ‘file’ in response. The $_GET is one of the sets of instruction which will get a particular file or webpage from a web server i.e. it will request for a file. The ['page'] is an argument that will define what type of pages will be displayed in response."
},
{
"code": null,
"e": 26243,
"s": 26192,
"text": "Where Local LFI found ?Basically this the location"
},
{
"code": null,
"e": 26292,
"s": 26243,
"text": "http://vulnerable_host/preview.php?file=abc.html"
},
{
"code": null,
"e": 26618,
"s": 26292,
"text": "This is the place where an attacker can perform the LFI attack on web applications. The script can be included here in the URL that is containing various parameters upon which the attack will be performed. It is possible to include arbitrary files on the server. The affected URL by the attacker would be something like this:"
},
{
"code": null,
"e": 26685,
"s": 26618,
"text": "http://vulnerable_host/preview.php?document=../../../../etc/passwd"
},
{
"code": null,
"e": 27058,
"s": 26685,
"text": "Identifying Vulnerabilities within Web Application: Identifying LFI Vulnerability within the web application is easy as it is going to include a file from a web server and return it to the attacker.For example “/fi/?page=include.php” LFI would be possible in such an application if the above example or something related to such example is existing in the web application."
},
{
"code": null,
"e": 27381,
"s": 27058,
"text": "A Pentester would attempt to get benefit from this sort of misconfiguration i.e. he can exploit this vulnerability by manipulating the parameters.For Example “/fi/?page=include.php” this will execute successfully only if the index.php” file exists in the same directory. If not, we have to add “../” ahead of “index.php” ."
},
{
"code": null,
"e": 27730,
"s": 27381,
"text": "Imagine this “index.php” is located in the \"/var/www/html\" folder and “include.php” is located in \"/var/www/dvwa/vulnerabilities/lfi/\" folder and you can see the responses of files from this folder location only. Now to execute a file located in another directory, we have to change our directory in URL. For example \"/fi/?page=../../../index.php\"."
},
{
"code": null,
"e": 27789,
"s": 27730,
"text": "There are three kinds of scenarios possible in LFI attack:"
},
{
"code": null,
"e": 27848,
"s": 27789,
"text": "Including Files to be Parsed by the Language’s Interpreter"
},
{
"code": null,
"e": 27891,
"s": 27848,
"text": "Including Files that are Printed to a Page"
},
{
"code": null,
"e": 27936,
"s": 27891,
"text": "Including Files that are Served as Downloads"
},
{
"code": null,
"e": 28076,
"s": 27936,
"text": "Impacts of an Local File Inclusion Vulnerability: An attacker would be able to get access to the following by exploiting LFI Vulnerability:"
},
{
"code": null,
"e": 28129,
"s": 28076,
"text": "Information Disclosure of files stored in Web Server"
},
{
"code": null,
"e": 28155,
"s": 28129,
"text": "Passwords/Database Access"
},
{
"code": null,
"e": 28165,
"s": 28155,
"text": "Log Files"
},
{
"code": null,
"e": 28192,
"s": 28165,
"text": "Complete System Compromise"
},
{
"code": null,
"e": 28239,
"s": 28192,
"text": "Remediation File Inclusion(LFI) Vulnerability:"
},
{
"code": null,
"e": 28379,
"s": 28239,
"text": "One should not allow the file path that could be modified directly either it should be hardcoded or to be selected via hardcoded path list."
},
{
"code": null,
"e": 28507,
"s": 28379,
"text": "One must make sure that the required should have dynamic path concatenation i.e must contain (a-z) (0-9) instead of (/, /% etc)"
},
{
"code": null,
"e": 28674,
"s": 28507,
"text": "There should be specific limit the API so that only inclusion from directories under it work so that Directory Traversal attack could not take place in this situation"
},
{
"code": null,
"e": 28680,
"s": 28674,
"text": "GBlog"
},
{
"code": null,
"e": 28697,
"s": 28680,
"text": "Web Technologies"
},
{
"code": null,
"e": 28795,
"s": 28697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28804,
"s": 28795,
"text": "Comments"
},
{
"code": null,
"e": 28817,
"s": 28804,
"text": "Old Comments"
},
{
"code": null,
"e": 28859,
"s": 28817,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28884,
"s": 28859,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 28928,
"s": 28884,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28960,
"s": 28928,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 28994,
"s": 28960,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 29036,
"s": 28994,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29069,
"s": 29036,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29112,
"s": 29069,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29162,
"s": 29112,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Polynomial Regression in R Programming - GeeksforGeeks
|
21 Jul, 2021
Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y|x). Basically it adds the quadratic or polynomial terms to the regression. Generally, this kind of regression is used for one resultant variable and one predictor.
Unlike linear data set, if one tries to apply linear model on non-linear data set without any modification, then there will be a very unsatisfactory and drastic result .
This may lead to increase in loss function, decrease in accuracy and high error rate.
Unlike linear model, polynomial model covers more data points.
Generally, polynomial regression is used in the following scenarios :
Rate of growth of tissues.
Progression of the epidemics related to disease.
Distribution phenomenon of the isotopes of carbon in lake sediments.
Polynomial Regression is also known as Polynomial Linear Regression since it depends on the linearly arranged coefficients rather than the variables. In R, if one wants to implement polynomial regression then he must install the following packages:
tidyverse package for better visualization and manipulation.
caret package for a smoother and easier machine learning workflow.
After proper installation of the packages, one needs to set the data properly. For that, first one needs to split the data into two sets(train set and test set). Then one can visualize the data into various plots. In R, in order to fit a polynomial regression, first one needs to generate pseudo random numbers using the set.seed(n) function.
The polynomial regression adds polynomial or quadratic terms to the regression equation as follow:
medv = b0 + b1 * lstat + b2 * lstat 2
where
mdev: is the median house value
lstat: is the predictor variable
In R, to create a predictor x2 one should use the function I(), as follow: I(x2). This raise x to the power 2. The polynomial regression can be computed in R as follow:
lm(medv ~ lstat + I(lstat^2), data = train.data)
For this following example let’s take the Boston data set of MASS package.
Example:
r
# R program to illustrate# Polynomial regression # Importing required librarylibrary(tidyverse)library(caret)theme_set(theme_classic()) # Load the datadata("Boston", package = "MASS")# Split the data into training and test setset.seed(123)training.samples <- Boston$medv %>% createDataPartition(p = 0.8, list = FALSE)train.data <- Boston[training.samples, ]test.data <- Boston[-training.samples, ] # Build the modelmodel <- lm(medv ~ poly(lstat, 5, raw = TRUE), data = train.data)# Make predictionspredictions <- model %>% predict(test.data)# Model performancemodelPerfomance = data.frame( RMSE = RMSE(predictions, test.data$medv), R2 = R2(predictions, test.data$medv) ) print(lm(medv ~ lstat + I(lstat^2), data = train.data))print(modelPerfomance)
Output:
Call:
lm(formula = medv ~ lstat + I(lstat^2), data = train.data)
Coefficients:
(Intercept) lstat I(lstat^2)
42.5736 -2.2673 0.0412
RMSE R2
1 5.270374 0.6829474
In R, if one wants to plot a graph for the output generated on implementing Polynomial Regression he can use the ggplot() function.
Example:
r
# R program to illustrate# Graph plotting in# Polynomial regression # Importing required librarylibrary(tidyverse)library(caret)theme_set(theme_classic()) # Load the datadata("Boston", package = "MASS")# Split the data into training and test setset.seed(123)training.samples <- Boston$medv %>% createDataPartition(p = 0.8, list = FALSE)train.data <- Boston[training.samples, ]test.data <- Boston[-training.samples, ] # Build the modelmodel <- lm(medv ~ poly(lstat, 5, raw = TRUE), data = train.data)# Make predictionspredictions <- model %>% predict(test.data)# Model performancedata.frame(RMSE = RMSE(predictions, test.data$medv), R2 = R2(predictions, test.data$medv)) ggplot(train.data, aes(lstat, medv) ) + geom_point() +stat_smooth(method = lm, formula = y ~ poly(x, 5, raw = TRUE))
Output:
adnanirshad158
Picked
R Machine-Learning
R regression
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
K-Means Clustering in R Programming
Creating a Data Frame from Vectors in R Programming
|
[
{
"code": null,
"e": 26273,
"s": 26245,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 26748,
"s": 26273,
"text": "Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y|x). Basically it adds the quadratic or polynomial terms to the regression. Generally, this kind of regression is used for one resultant variable and one predictor."
},
{
"code": null,
"e": 26918,
"s": 26748,
"text": "Unlike linear data set, if one tries to apply linear model on non-linear data set without any modification, then there will be a very unsatisfactory and drastic result ."
},
{
"code": null,
"e": 27004,
"s": 26918,
"text": "This may lead to increase in loss function, decrease in accuracy and high error rate."
},
{
"code": null,
"e": 27067,
"s": 27004,
"text": "Unlike linear model, polynomial model covers more data points."
},
{
"code": null,
"e": 27137,
"s": 27067,
"text": "Generally, polynomial regression is used in the following scenarios :"
},
{
"code": null,
"e": 27164,
"s": 27137,
"text": "Rate of growth of tissues."
},
{
"code": null,
"e": 27213,
"s": 27164,
"text": "Progression of the epidemics related to disease."
},
{
"code": null,
"e": 27282,
"s": 27213,
"text": "Distribution phenomenon of the isotopes of carbon in lake sediments."
},
{
"code": null,
"e": 27531,
"s": 27282,
"text": "Polynomial Regression is also known as Polynomial Linear Regression since it depends on the linearly arranged coefficients rather than the variables. In R, if one wants to implement polynomial regression then he must install the following packages:"
},
{
"code": null,
"e": 27592,
"s": 27531,
"text": "tidyverse package for better visualization and manipulation."
},
{
"code": null,
"e": 27659,
"s": 27592,
"text": "caret package for a smoother and easier machine learning workflow."
},
{
"code": null,
"e": 28003,
"s": 27659,
"text": "After proper installation of the packages, one needs to set the data properly. For that, first one needs to split the data into two sets(train set and test set). Then one can visualize the data into various plots. In R, in order to fit a polynomial regression, first one needs to generate pseudo random numbers using the set.seed(n) function. "
},
{
"code": null,
"e": 28102,
"s": 28003,
"text": "The polynomial regression adds polynomial or quadratic terms to the regression equation as follow:"
},
{
"code": null,
"e": 28140,
"s": 28102,
"text": "medv = b0 + b1 * lstat + b2 * lstat 2"
},
{
"code": null,
"e": 28146,
"s": 28140,
"text": "where"
},
{
"code": null,
"e": 28178,
"s": 28146,
"text": "mdev: is the median house value"
},
{
"code": null,
"e": 28211,
"s": 28178,
"text": "lstat: is the predictor variable"
},
{
"code": null,
"e": 28380,
"s": 28211,
"text": "In R, to create a predictor x2 one should use the function I(), as follow: I(x2). This raise x to the power 2. The polynomial regression can be computed in R as follow:"
},
{
"code": null,
"e": 28429,
"s": 28380,
"text": "lm(medv ~ lstat + I(lstat^2), data = train.data)"
},
{
"code": null,
"e": 28506,
"s": 28429,
"text": "For this following example let’s take the Boston data set of MASS package. "
},
{
"code": null,
"e": 28515,
"s": 28506,
"text": "Example:"
},
{
"code": null,
"e": 28517,
"s": 28515,
"text": "r"
},
{
"code": "# R program to illustrate# Polynomial regression # Importing required librarylibrary(tidyverse)library(caret)theme_set(theme_classic()) # Load the datadata(\"Boston\", package = \"MASS\")# Split the data into training and test setset.seed(123)training.samples <- Boston$medv %>% createDataPartition(p = 0.8, list = FALSE)train.data <- Boston[training.samples, ]test.data <- Boston[-training.samples, ] # Build the modelmodel <- lm(medv ~ poly(lstat, 5, raw = TRUE), data = train.data)# Make predictionspredictions <- model %>% predict(test.data)# Model performancemodelPerfomance = data.frame( RMSE = RMSE(predictions, test.data$medv), R2 = R2(predictions, test.data$medv) ) print(lm(medv ~ lstat + I(lstat^2), data = train.data))print(modelPerfomance)",
"e": 29334,
"s": 28517,
"text": null
},
{
"code": null,
"e": 29342,
"s": 29334,
"text": "Output:"
},
{
"code": null,
"e": 29550,
"s": 29342,
"text": "Call:\nlm(formula = medv ~ lstat + I(lstat^2), data = train.data)\n\nCoefficients:\n(Intercept) lstat I(lstat^2) \n 42.5736 -2.2673 0.0412 \n\n RMSE R2\n1 5.270374 0.6829474"
},
{
"code": null,
"e": 29682,
"s": 29550,
"text": "In R, if one wants to plot a graph for the output generated on implementing Polynomial Regression he can use the ggplot() function."
},
{
"code": null,
"e": 29691,
"s": 29682,
"text": "Example:"
},
{
"code": null,
"e": 29693,
"s": 29691,
"text": "r"
},
{
"code": "# R program to illustrate# Graph plotting in# Polynomial regression # Importing required librarylibrary(tidyverse)library(caret)theme_set(theme_classic()) # Load the datadata(\"Boston\", package = \"MASS\")# Split the data into training and test setset.seed(123)training.samples <- Boston$medv %>% createDataPartition(p = 0.8, list = FALSE)train.data <- Boston[training.samples, ]test.data <- Boston[-training.samples, ] # Build the modelmodel <- lm(medv ~ poly(lstat, 5, raw = TRUE), data = train.data)# Make predictionspredictions <- model %>% predict(test.data)# Model performancedata.frame(RMSE = RMSE(predictions, test.data$medv), R2 = R2(predictions, test.data$medv)) ggplot(train.data, aes(lstat, medv) ) + geom_point() +stat_smooth(method = lm, formula = y ~ poly(x, 5, raw = TRUE))",
"e": 30494,
"s": 29693,
"text": null
},
{
"code": null,
"e": 30502,
"s": 30494,
"text": "Output:"
},
{
"code": null,
"e": 30517,
"s": 30502,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30524,
"s": 30517,
"text": "Picked"
},
{
"code": null,
"e": 30543,
"s": 30524,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 30556,
"s": 30543,
"text": "R regression"
},
{
"code": null,
"e": 30567,
"s": 30556,
"text": "R Language"
},
{
"code": null,
"e": 30665,
"s": 30567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30723,
"s": 30665,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 30775,
"s": 30723,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 30807,
"s": 30775,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 30851,
"s": 30807,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 30903,
"s": 30851,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30938,
"s": 30903,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30996,
"s": 30938,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31034,
"s": 30996,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31070,
"s": 31034,
"text": "K-Means Clustering in R Programming"
}
] |
How to sort a slice of ints in Golang? - GeeksforGeeks
|
26 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.Go language allows you to sort the elements of the slice according to its type. So, an int type slice is sorted by using the following functions. These functions are defined under the sort package so, you have to import sort package in your program for accessing these functions:
1. Ints: This function is used to only sorts a slice of ints and it sorts the elements of the slice in increasing order.
Syntax:
func Ints(slc []int)
Here, slc represent a slice of ints. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how // to sort the slice of intspackage main import ( "fmt" "sort") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []int{400, 600, 100, 300, 500, 200, 900} scl2 := []int{-23, 567, -34, 67, 0, 12, -5} // Displaying slices fmt.Println("Slices(Before):") fmt.Println("Slice 1: ", scl1) fmt.Println("Slice 2: ", scl2) // Sorting the slice of ints // Using Ints function sort.Ints (scl1) sort.Ints (scl2) // Displaying the result fmt.Println("\nSlices(After):") fmt.Println("Slice 1 : ", scl1) fmt.Println("Slice 2 : ",scl2)}
Output:
Slices(Before):
Slice 1: [400 600 100 300 500 200 900]
Slice 2: [-23 567 -34 67 0 12 -5]
Slices(After):
Slice 1 : [100 200 300 400 500 600 900]
Slice 2 : [-34 -23 -5 0 12 67 567]
2. IntsAreSorted: This function is used to check whether the given slice of ints is in the sorted form(in increasing order) or not. This method returns true if the slice is in sorted form, or return false if the slice is not in the sorted form.
Syntax:
func IntsAreSorted(scl []int) bool
Here, scl represents a slice of ints. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to check// whether the given slice of ints is in// sorted form or notpackage main import ( "fmt" "sort") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []int{100, 200, 300, 400, 500, 600, 700} scl2 := []int{-23, 567, -34, 67, 0, 12, -5} // Displaying slices fmt.Println("Slices:") fmt.Println("Slice 1: ", scl1) fmt.Println("Slice 2: ", scl2) // Checking the slice is in sorted form or not // Using IntsAreSorted function res1 := sort.IntsAreSorted(scl1) res2 := sort.IntsAreSorted(scl2) // Displaying the result fmt.Println("\nResult:") fmt.Println("Is Slice 1 is sorted?: ", res1) fmt.Println("Is Slice 2 is sorted?: ", res2)}
Output:
Slices:
Slice 1: [100 200 300 400 500 600 700]
Slice 2: [-23 567 -34 67 0 12 -5]
Result:
Is Slice 1 is sorted?: true
Is Slice 2 is sorted?: false
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
Time Formatting in Golang
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
|
[
{
"code": null,
"e": 26151,
"s": 26123,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 26698,
"s": 26151,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.Go language allows you to sort the elements of the slice according to its type. So, an int type slice is sorted by using the following functions. These functions are defined under the sort package so, you have to import sort package in your program for accessing these functions:"
},
{
"code": null,
"e": 26819,
"s": 26698,
"text": "1. Ints: This function is used to only sorts a slice of ints and it sorts the elements of the slice in increasing order."
},
{
"code": null,
"e": 26827,
"s": 26819,
"text": "Syntax:"
},
{
"code": null,
"e": 26848,
"s": 26827,
"text": "func Ints(slc []int)"
},
{
"code": null,
"e": 26942,
"s": 26848,
"text": "Here, slc represent a slice of ints. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 26951,
"s": 26942,
"text": "Example:"
},
{
"code": "// Go program to illustrate how // to sort the slice of intspackage main import ( \"fmt\" \"sort\") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []int{400, 600, 100, 300, 500, 200, 900} scl2 := []int{-23, 567, -34, 67, 0, 12, -5} // Displaying slices fmt.Println(\"Slices(Before):\") fmt.Println(\"Slice 1: \", scl1) fmt.Println(\"Slice 2: \", scl2) // Sorting the slice of ints // Using Ints function sort.Ints (scl1) sort.Ints (scl2) // Displaying the result fmt.Println(\"\\nSlices(After):\") fmt.Println(\"Slice 1 : \", scl1) fmt.Println(\"Slice 2 : \",scl2)}",
"e": 27644,
"s": 26951,
"text": null
},
{
"code": null,
"e": 27652,
"s": 27644,
"text": "Output:"
},
{
"code": null,
"e": 27837,
"s": 27652,
"text": "Slices(Before):\nSlice 1: [400 600 100 300 500 200 900]\nSlice 2: [-23 567 -34 67 0 12 -5]\n\nSlices(After):\nSlice 1 : [100 200 300 400 500 600 900]\nSlice 2 : [-34 -23 -5 0 12 67 567]\n"
},
{
"code": null,
"e": 28082,
"s": 27837,
"text": "2. IntsAreSorted: This function is used to check whether the given slice of ints is in the sorted form(in increasing order) or not. This method returns true if the slice is in sorted form, or return false if the slice is not in the sorted form."
},
{
"code": null,
"e": 28090,
"s": 28082,
"text": "Syntax:"
},
{
"code": null,
"e": 28125,
"s": 28090,
"text": "func IntsAreSorted(scl []int) bool"
},
{
"code": null,
"e": 28220,
"s": 28125,
"text": "Here, scl represents a slice of ints. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 28229,
"s": 28220,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to check// whether the given slice of ints is in// sorted form or notpackage main import ( \"fmt\" \"sort\") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []int{100, 200, 300, 400, 500, 600, 700} scl2 := []int{-23, 567, -34, 67, 0, 12, -5} // Displaying slices fmt.Println(\"Slices:\") fmt.Println(\"Slice 1: \", scl1) fmt.Println(\"Slice 2: \", scl2) // Checking the slice is in sorted form or not // Using IntsAreSorted function res1 := sort.IntsAreSorted(scl1) res2 := sort.IntsAreSorted(scl2) // Displaying the result fmt.Println(\"\\nResult:\") fmt.Println(\"Is Slice 1 is sorted?: \", res1) fmt.Println(\"Is Slice 2 is sorted?: \", res2)}",
"e": 29012,
"s": 28229,
"text": null
},
{
"code": null,
"e": 29020,
"s": 29012,
"text": "Output:"
},
{
"code": null,
"e": 29172,
"s": 29020,
"text": "Slices:\nSlice 1: [100 200 300 400 500 600 700]\nSlice 2: [-23 567 -34 67 0 12 -5]\n\nResult:\nIs Slice 1 is sorted?: true\nIs Slice 2 is sorted?: false\n"
},
{
"code": null,
"e": 29179,
"s": 29172,
"text": "Golang"
},
{
"code": null,
"e": 29193,
"s": 29179,
"text": "Golang-Slices"
},
{
"code": null,
"e": 29205,
"s": 29193,
"text": "Go Language"
},
{
"code": null,
"e": 29303,
"s": 29205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29355,
"s": 29303,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 29401,
"s": 29355,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 29451,
"s": 29401,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 29502,
"s": 29451,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 29528,
"s": 29502,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 29575,
"s": 29528,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 29587,
"s": 29575,
"text": "Golang Maps"
},
{
"code": null,
"e": 29641,
"s": 29587,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 29663,
"s": 29641,
"text": "Inheritance in GoLang"
}
] |
Underscore.js _.groupBy Function - GeeksforGeeks
|
24 Nov, 2021
The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects.The _.groupBy() function is used to make collection of the elements in the array passed. It works by matching the value of each element to the other. If they matches then they are put in one collection otherwise we will have 2 collections/groups. We can also pass a function based on who’s result we will collect the elements. It can group both on the basis of number and also by string.
Syntax:
_.groupBy( list, iteratee, context )
Parameters: This function accepts three parameters as mentioned above and described below:
List: This parameter contains the element list.
Iteratee: This parameter contains the condition which is used to text the elements.
Context: It is the text which is used to display. It is optional parameter.
Return values: It returns the collections as the different arrays.
Using Math.ceil() in the _.groupBy() function: The _.groupBy() function takes the element from the list one by one and pass it to the Math.ceil() function. Then each elements output of the function will be matched with the output of another element in the Math.ceil() then they are put in 1 group otherwise they will be in 2 separate groups. After all the elements are matched with all the rest elements then the _.groupBy function ends.
Example:
<html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.groupBy([2.7, 3.4, 6.6, 1.2, 2.0, 2.4], function(num) { return Math.ceil(num); })); </script> </body></html>
Output:
Using length() in the _.groupBy() function: Passing the array elements to the groupBy() function and match the elements on the basis of their length. If the length of two elements is same then the they will be grouped in 1 group otherwise 2 groups will be formed.
Example:
<html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.groupBy(['HTML', 'CSS3', 'JS', 'PHP'], 'length')); </script> </body></html>
Output:
Using a property of the array passed in the _.groupBy() function: First, declare the array (here array is ‘arr’). Choose one condition on which need to check like here ‘prop3’. Then the elements which have the same value in the ‘prop3’ will be grouped in 1 group. Console.log the final answer.
Example:
<html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var arr = [ {prop1:"10", prop2:"07", prop3: "Geeks"}, {prop1:"12", prop2:"86", prop3: "for"}, {prop1:"11", prop2:"58", prop3: "Geeks"} ]; console.log(_.groupBy(arr, 'prop3')); </script> </body></html>
Output:
Passing ‘date’ as property of the array to the _.groupBy() function together: First define an array with one property as ‘date’ of the format ‘dd-mm-yy’. Then pass the array and the ‘date’ property to the _.groupBy() function. The elements having the same date will be grouped in 1 group. The group numbering will start from 0.
Example:
<html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var orders = [ { date:"30-60-90 Day", Name:"Kim", amount:415 }, { date:"30-60-90 Day", Name:"Kelly", amount:175 }, { date:"30 Day", Name:"Shelly", amount:400 }, { date:"30 Day", Name:"Sarvesh", amount:180 } ]; console.log(_.groupBy(orders, "date")); </script> </body></html>
Output:
shubham_singh
JavaScript - Underscore.js
JavaScript
JQuery
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 append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
|
[
{
"code": null,
"e": 25738,
"s": 25710,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26324,
"s": 25738,
"text": "The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects.The _.groupBy() function is used to make collection of the elements in the array passed. It works by matching the value of each element to the other. If they matches then they are put in one collection otherwise we will have 2 collections/groups. We can also pass a function based on who’s result we will collect the elements. It can group both on the basis of number and also by string."
},
{
"code": null,
"e": 26332,
"s": 26324,
"text": "Syntax:"
},
{
"code": null,
"e": 26370,
"s": 26332,
"text": "_.groupBy( list, iteratee, context ) "
},
{
"code": null,
"e": 26461,
"s": 26370,
"text": "Parameters: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26509,
"s": 26461,
"text": "List: This parameter contains the element list."
},
{
"code": null,
"e": 26593,
"s": 26509,
"text": "Iteratee: This parameter contains the condition which is used to text the elements."
},
{
"code": null,
"e": 26669,
"s": 26593,
"text": "Context: It is the text which is used to display. It is optional parameter."
},
{
"code": null,
"e": 26736,
"s": 26669,
"text": "Return values: It returns the collections as the different arrays."
},
{
"code": null,
"e": 27174,
"s": 26736,
"text": "Using Math.ceil() in the _.groupBy() function: The _.groupBy() function takes the element from the list one by one and pass it to the Math.ceil() function. Then each elements output of the function will be matched with the output of another element in the Math.ceil() then they are put in 1 group otherwise they will be in 2 separate groups. After all the elements are matched with all the rest elements then the _.groupBy function ends."
},
{
"code": null,
"e": 27183,
"s": 27174,
"text": "Example:"
},
{
"code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.groupBy([2.7, 3.4, 6.6, 1.2, 2.0, 2.4], function(num) { return Math.ceil(num); })); </script> </body></html> ",
"e": 27600,
"s": 27183,
"text": null
},
{
"code": null,
"e": 27608,
"s": 27600,
"text": "Output:"
},
{
"code": null,
"e": 27872,
"s": 27608,
"text": "Using length() in the _.groupBy() function: Passing the array elements to the groupBy() function and match the elements on the basis of their length. If the length of two elements is same then the they will be grouped in 1 group otherwise 2 groups will be formed."
},
{
"code": null,
"e": 27881,
"s": 27872,
"text": "Example:"
},
{
"code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.groupBy(['HTML', 'CSS3', 'JS', 'PHP'], 'length')); </script> </body></html>",
"e": 28211,
"s": 27881,
"text": null
},
{
"code": null,
"e": 28219,
"s": 28211,
"text": "Output:"
},
{
"code": null,
"e": 28513,
"s": 28219,
"text": "Using a property of the array passed in the _.groupBy() function: First, declare the array (here array is ‘arr’). Choose one condition on which need to check like here ‘prop3’. Then the elements which have the same value in the ‘prop3’ will be grouped in 1 group. Console.log the final answer."
},
{
"code": null,
"e": 28522,
"s": 28513,
"text": "Example:"
},
{
"code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var arr = [ {prop1:\"10\", prop2:\"07\", prop3: \"Geeks\"}, {prop1:\"12\", prop2:\"86\", prop3: \"for\"}, {prop1:\"11\", prop2:\"58\", prop3: \"Geeks\"} ]; console.log(_.groupBy(arr, 'prop3')); </script> </body></html>",
"e": 29052,
"s": 28522,
"text": null
},
{
"code": null,
"e": 29060,
"s": 29052,
"text": "Output:"
},
{
"code": null,
"e": 29388,
"s": 29060,
"text": "Passing ‘date’ as property of the array to the _.groupBy() function together: First define an array with one property as ‘date’ of the format ‘dd-mm-yy’. Then pass the array and the ‘date’ property to the _.groupBy() function. The elements having the same date will be grouped in 1 group. The group numbering will start from 0."
},
{
"code": null,
"e": 29397,
"s": 29388,
"text": "Example:"
},
{
"code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var orders = [ { date:\"30-60-90 Day\", Name:\"Kim\", amount:415 }, { date:\"30-60-90 Day\", Name:\"Kelly\", amount:175 }, { date:\"30 Day\", Name:\"Shelly\", amount:400 }, { date:\"30 Day\", Name:\"Sarvesh\", amount:180 } ]; console.log(_.groupBy(orders, \"date\")); </script> </body></html>",
"e": 30058,
"s": 29397,
"text": null
},
{
"code": null,
"e": 30066,
"s": 30058,
"text": "Output:"
},
{
"code": null,
"e": 30080,
"s": 30066,
"text": "shubham_singh"
},
{
"code": null,
"e": 30107,
"s": 30080,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 30118,
"s": 30107,
"text": "JavaScript"
},
{
"code": null,
"e": 30125,
"s": 30118,
"text": "JQuery"
},
{
"code": null,
"e": 30142,
"s": 30125,
"text": "Web Technologies"
},
{
"code": null,
"e": 30240,
"s": 30142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30280,
"s": 30240,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30325,
"s": 30280,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30386,
"s": 30325,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30458,
"s": 30386,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30510,
"s": 30458,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30556,
"s": 30510,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 30585,
"s": 30556,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30648,
"s": 30585,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 30725,
"s": 30648,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Largest triplet product in a stream - GeeksforGeeks
|
05 Nov, 2021
Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of largest, second largest, third largest element of the subarray arr[0...i]. If i < 2 print -1.
Examples:
Input : arr[] = {1, 2, 3, 4, 5}
Output :-1
-1
6
24
60
Explanation : for i = 2 only three elements
are there {1, 2, 3} so answer is 6. For i = 3
largest three elements are {2, 3, 4} their
product is 2*3*4 = 24 ....so on
We will use priority queue here.
Insert arr[i] in the priority queueAs the top element in priority queue is largest so pop it and store it as x. Now the top element in the priority queue will be the second largest element in subarray arr[0...i] pop it and store as y. Now the top element is third largest element in subarray arr[0...i] so pop it and store it as z.Print x*y*zReinsert x, y, z.
Insert arr[i] in the priority queue
As the top element in priority queue is largest so pop it and store it as x. Now the top element in the priority queue will be the second largest element in subarray arr[0...i] pop it and store as y. Now the top element is third largest element in subarray arr[0...i] so pop it and store it as z.
Print x*y*z
Reinsert x, y, z.
C++
Java
Python3
C#
Javascript
// C++ implementation of largest triplet// multiplication#include <bits/stdc++.h>using namespace std; // Prints the product of three largest numbers// in subarray arr[0..i]void LargestTripletMultiplication(int arr[], int n){ // call a priority queue priority_queue<int> q; // traversing the array for (int i = 0; i < n; i++) { // pushing arr[i] in the array q.push(arr[i]); // if less than three elements are present // in array print -1 if (q.size() < 3) cout << "-1" << endl; else { // pop three largest elements int x = q.top(); q.pop(); int y = q.top(); q.pop(); int z = q.top(); q.pop(); // Reinsert x, y, z in priority_queue int ans = x * y * z; cout << ans << endl; q.push(x); q.push(y); q.push(z); } } return;} // Driver Functionint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); LargestTripletMultiplication(arr, n); return 0;}
// Java implementation of largest triplet// multiplicationimport java.util.Collections;import java.util.PriorityQueue; class GFG { // Prints the product of three largest numbers // in subarray arr[0..i] static void LargestTripletMultiplication(int arr[], int n) { // call a priority queue PriorityQueue<Integer> q = new PriorityQueue(Collections.reverseOrder()); // traversing the array for (int i = 0; i < n; i++) { // pushing arr[i] in array q.add(arr[i]); // if less than three elements are present // in array print -1 if (q.size() < 3) System.out.println("-1"); else { // pop three largest elements int x = q.poll(); int y = q.poll(); int z = q.poll(); // Reinsert x, y, z in priority_queue int ans = x * y * z; System.out.println(ans); q.add(x); q.add(y); q.add(z); } } } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; LargestTripletMultiplication(arr, n); }} // This code is contributed by shubham96301
# Python3 implementation of largest triplet# multiplicationfrom queue import PriorityQueue # Prints the product of three largest# numbers in subarray arr[0..i]def LargestTripletMultiplication(arr, n): # Call a priority queue q = PriorityQueue() # Traversing the array for i in range(n): # Pushing -arr[i] in array # to get max PriorityQueue q.put(-arr[i]) # If less than three elements # are present in array print -1 if (q.qsize() < 3): print(-1) else: # pop three largest elements x = q.get() y = q.get() z = q.get() # Reinsert x, y, z in # priority_queue ans = x * y * z print(-ans) q.put(x); q.put(y); q.put(z); # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5 ] n = len(arr) LargestTripletMultiplication(arr, n) # This code is contributed by math_lover
// C# implementation of largest triplet// multiplicationusing System;using System.Collections.Generic;public class GFG { // Prints the product of three largest numbers // in subarray arr[0..i] static void LargestTripletMultiplication(int []arr, int n) { // call a priority queue List<int> q = new List<int>(); // traversing the array for (int i = 0; i < n; i++) { // pushing arr[i] in array q.Add(arr[i]); q.Sort(); q.Reverse(); // if less than three elements are present // in array print -1 if (q.Count < 3) Console.WriteLine("-1"); else { // pop three largest elements int x = q[0]; int y = q[1]; int z = q[2]; q.RemoveRange(0, 3); // Reinsert x, y, z in priority_queue int ans = x * y * z; Console.WriteLine(ans); q.Add(x); q.Add(y); q.Add(z); } } } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; LargestTripletMultiplication(arr, n); }} // This code is contributed by Rajput-Ji
<script>// javascript implementation of largest triplet// multiplication // Prints the product of three largest numbers // in subarray arr[0..i] function LargestTripletMultiplication(arr , n) { // call a priority queue var q = []; // traversing the array for (i = 0; i < n; i++) { // pushing arr[i] in array q.push(arr[i]);q.sort(); // if less than three elements are present // in array print -1 if (q.length < 3) document.write("-1<br/>"); else { // pop three largest elements q.sort(); var x = q.pop(); var y = q.pop(); var z = q.pop(); // Reinsert x, y, z in priority_queue var ans = x * y * z; document.write(ans+"<br/>"); q.push(x); q.push(y); q.push(z); q.sort(); q.reverse(); } } } // Driver code var arr = [ 1, 2, 3, 4, 5 ]; var n = arr.length; LargestTripletMultiplication(arr, n); // This code contributed by umadevi9616</script>
Output:
-1
-1
6
24
60
This article is contributed by Ayush Jha. 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.
nobody_cares
math_lover
Rajput-Ji
umadevi9616
arorakashish0911
array-stream
Arrays
Heap
Arrays
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Python | Using 2D arrays/lists the right way
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array
|
[
{
"code": null,
"e": 25456,
"s": 25428,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 25660,
"s": 25456,
"text": "Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of largest, second largest, third largest element of the subarray arr[0...i]. If i < 2 print -1. "
},
{
"code": null,
"e": 25671,
"s": 25660,
"text": "Examples: "
},
{
"code": null,
"e": 25938,
"s": 25671,
"text": "Input : arr[] = {1, 2, 3, 4, 5}\nOutput :-1\n -1\n 6\n 24\n 60\nExplanation : for i = 2 only three elements \nare there {1, 2, 3} so answer is 6. For i = 3\nlargest three elements are {2, 3, 4} their\nproduct is 2*3*4 = 24 ....so on "
},
{
"code": null,
"e": 25972,
"s": 25938,
"text": "We will use priority queue here. "
},
{
"code": null,
"e": 26332,
"s": 25972,
"text": "Insert arr[i] in the priority queueAs the top element in priority queue is largest so pop it and store it as x. Now the top element in the priority queue will be the second largest element in subarray arr[0...i] pop it and store as y. Now the top element is third largest element in subarray arr[0...i] so pop it and store it as z.Print x*y*zReinsert x, y, z."
},
{
"code": null,
"e": 26368,
"s": 26332,
"text": "Insert arr[i] in the priority queue"
},
{
"code": null,
"e": 26665,
"s": 26368,
"text": "As the top element in priority queue is largest so pop it and store it as x. Now the top element in the priority queue will be the second largest element in subarray arr[0...i] pop it and store as y. Now the top element is third largest element in subarray arr[0...i] so pop it and store it as z."
},
{
"code": null,
"e": 26677,
"s": 26665,
"text": "Print x*y*z"
},
{
"code": null,
"e": 26695,
"s": 26677,
"text": "Reinsert x, y, z."
},
{
"code": null,
"e": 26699,
"s": 26695,
"text": "C++"
},
{
"code": null,
"e": 26704,
"s": 26699,
"text": "Java"
},
{
"code": null,
"e": 26712,
"s": 26704,
"text": "Python3"
},
{
"code": null,
"e": 26715,
"s": 26712,
"text": "C#"
},
{
"code": null,
"e": 26726,
"s": 26715,
"text": "Javascript"
},
{
"code": "// C++ implementation of largest triplet// multiplication#include <bits/stdc++.h>using namespace std; // Prints the product of three largest numbers// in subarray arr[0..i]void LargestTripletMultiplication(int arr[], int n){ // call a priority queue priority_queue<int> q; // traversing the array for (int i = 0; i < n; i++) { // pushing arr[i] in the array q.push(arr[i]); // if less than three elements are present // in array print -1 if (q.size() < 3) cout << \"-1\" << endl; else { // pop three largest elements int x = q.top(); q.pop(); int y = q.top(); q.pop(); int z = q.top(); q.pop(); // Reinsert x, y, z in priority_queue int ans = x * y * z; cout << ans << endl; q.push(x); q.push(y); q.push(z); } } return;} // Driver Functionint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); LargestTripletMultiplication(arr, n); return 0;}",
"e": 27829,
"s": 26726,
"text": null
},
{
"code": "// Java implementation of largest triplet// multiplicationimport java.util.Collections;import java.util.PriorityQueue; class GFG { // Prints the product of three largest numbers // in subarray arr[0..i] static void LargestTripletMultiplication(int arr[], int n) { // call a priority queue PriorityQueue<Integer> q = new PriorityQueue(Collections.reverseOrder()); // traversing the array for (int i = 0; i < n; i++) { // pushing arr[i] in array q.add(arr[i]); // if less than three elements are present // in array print -1 if (q.size() < 3) System.out.println(\"-1\"); else { // pop three largest elements int x = q.poll(); int y = q.poll(); int z = q.poll(); // Reinsert x, y, z in priority_queue int ans = x * y * z; System.out.println(ans); q.add(x); q.add(y); q.add(z); } } } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; LargestTripletMultiplication(arr, n); }} // This code is contributed by shubham96301",
"e": 29129,
"s": 27829,
"text": null
},
{
"code": "# Python3 implementation of largest triplet# multiplicationfrom queue import PriorityQueue # Prints the product of three largest# numbers in subarray arr[0..i]def LargestTripletMultiplication(arr, n): # Call a priority queue q = PriorityQueue() # Traversing the array for i in range(n): # Pushing -arr[i] in array # to get max PriorityQueue q.put(-arr[i]) # If less than three elements # are present in array print -1 if (q.qsize() < 3): print(-1) else: # pop three largest elements x = q.get() y = q.get() z = q.get() # Reinsert x, y, z in # priority_queue ans = x * y * z print(-ans) q.put(x); q.put(y); q.put(z); # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5 ] n = len(arr) LargestTripletMultiplication(arr, n) # This code is contributed by math_lover",
"e": 30169,
"s": 29129,
"text": null
},
{
"code": "// C# implementation of largest triplet// multiplicationusing System;using System.Collections.Generic;public class GFG { // Prints the product of three largest numbers // in subarray arr[0..i] static void LargestTripletMultiplication(int []arr, int n) { // call a priority queue List<int> q = new List<int>(); // traversing the array for (int i = 0; i < n; i++) { // pushing arr[i] in array q.Add(arr[i]); q.Sort(); q.Reverse(); // if less than three elements are present // in array print -1 if (q.Count < 3) Console.WriteLine(\"-1\"); else { // pop three largest elements int x = q[0]; int y = q[1]; int z = q[2]; q.RemoveRange(0, 3); // Reinsert x, y, z in priority_queue int ans = x * y * z; Console.WriteLine(ans); q.Add(x); q.Add(y); q.Add(z); } } } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; LargestTripletMultiplication(arr, n); }} // This code is contributed by Rajput-Ji",
"e": 31290,
"s": 30169,
"text": null
},
{
"code": "<script>// javascript implementation of largest triplet// multiplication // Prints the product of three largest numbers // in subarray arr[0..i] function LargestTripletMultiplication(arr , n) { // call a priority queue var q = []; // traversing the array for (i = 0; i < n; i++) { // pushing arr[i] in array q.push(arr[i]);q.sort(); // if less than three elements are present // in array print -1 if (q.length < 3) document.write(\"-1<br/>\"); else { // pop three largest elements q.sort(); var x = q.pop(); var y = q.pop(); var z = q.pop(); // Reinsert x, y, z in priority_queue var ans = x * y * z; document.write(ans+\"<br/>\"); q.push(x); q.push(y); q.push(z); q.sort(); q.reverse(); } } } // Driver code var arr = [ 1, 2, 3, 4, 5 ]; var n = arr.length; LargestTripletMultiplication(arr, n); // This code contributed by umadevi9616</script>",
"e": 32526,
"s": 31290,
"text": null
},
{
"code": null,
"e": 32535,
"s": 32526,
"text": "Output: "
},
{
"code": null,
"e": 32549,
"s": 32535,
"text": "-1\n-1\n6\n24\n60"
},
{
"code": null,
"e": 32967,
"s": 32549,
"text": "This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32980,
"s": 32967,
"text": "nobody_cares"
},
{
"code": null,
"e": 32991,
"s": 32980,
"text": "math_lover"
},
{
"code": null,
"e": 33001,
"s": 32991,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33013,
"s": 33001,
"text": "umadevi9616"
},
{
"code": null,
"e": 33030,
"s": 33013,
"text": "arorakashish0911"
},
{
"code": null,
"e": 33043,
"s": 33030,
"text": "array-stream"
},
{
"code": null,
"e": 33050,
"s": 33043,
"text": "Arrays"
},
{
"code": null,
"e": 33055,
"s": 33050,
"text": "Heap"
},
{
"code": null,
"e": 33062,
"s": 33055,
"text": "Arrays"
},
{
"code": null,
"e": 33067,
"s": 33062,
"text": "Heap"
},
{
"code": null,
"e": 33165,
"s": 33067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33174,
"s": 33165,
"text": "Comments"
},
{
"code": null,
"e": 33187,
"s": 33174,
"text": "Old Comments"
},
{
"code": null,
"e": 33231,
"s": 33187,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33254,
"s": 33231,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33286,
"s": 33254,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33300,
"s": 33286,
"text": "Linear Search"
},
{
"code": null,
"e": 33345,
"s": 33300,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 33354,
"s": 33345,
"text": "HeapSort"
},
{
"code": null,
"e": 33366,
"s": 33354,
"text": "Binary Heap"
},
{
"code": null,
"e": 33397,
"s": 33366,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 33453,
"s": 33397,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Convert string to DateTime and vice-versa in Python
|
Python has extensive date and time manipulation capabilities.In this article we'll see in how is string with proper format can we converted to a datetime and the vice versa.
This strptime function from datetime module can do the conversion from string to datetime by taking appropriate format specifiers.
Live Demo
import datetime
dt_str = 'September 19 2019 21:02:23 PM'
#Given date time
print("Given date time: \n",dt_str)
#Type check
print("Data Type: ",type(dt_str))
#Format
dtformat = '%B %d %Y %H:%M:%S %p'
datetime_val = datetime.datetime.strptime(dt_str, dtformat)
print("After converting to date time: \n",datetime_val)
#Type check
print("Data type: ",type(datetime_val))
# Reverting to string
dtstr_new=str(datetime_val)
print("The string Date time ",dtstr_new)
print("Data type: ",type(dtstr_new))
Running the above code gives us the following result −
Given date time:
September 19 2019 21:02:23 PM
Data Type:
After converting to date time:
2019-09-19 21:02:23
Data type:
The string Date time 2019-09-19 21:02:23
Data type:
The str function will convert its parameter to a string. So here we take a datetime value by using the today function and supply it as a parameter to the str function.
Live Demo
import datetime
print("Date time data type: \n",datetime.datetime.today())
print("Data type: \n",type(datetime.datetime.today()))
dtstr= str(datetime.datetime.today())
print("String Date time:\n ",dtstr)
print("Data type: \n",type(dtstr))
Running the above code gives us the following result −
Date time data type:
2020-05-18 11:09:40.986027
Data type:
String Date time:
2020-05-18 11:09:40.986027
Data type:
|
[
{
"code": null,
"e": 1236,
"s": 1062,
"text": "Python has extensive date and time manipulation capabilities.In this article we'll see in how is string with proper format can we converted to a datetime and the vice versa."
},
{
"code": null,
"e": 1367,
"s": 1236,
"text": "This strptime function from datetime module can do the conversion from string to datetime by taking appropriate format specifiers."
},
{
"code": null,
"e": 1378,
"s": 1367,
"text": " Live Demo"
},
{
"code": null,
"e": 1872,
"s": 1378,
"text": "import datetime\ndt_str = 'September 19 2019 21:02:23 PM'\n#Given date time\nprint(\"Given date time: \\n\",dt_str)\n#Type check\nprint(\"Data Type: \",type(dt_str))\n#Format\ndtformat = '%B %d %Y %H:%M:%S %p'\ndatetime_val = datetime.datetime.strptime(dt_str, dtformat)\nprint(\"After converting to date time: \\n\",datetime_val)\n#Type check\nprint(\"Data type: \",type(datetime_val))\n# Reverting to string\ndtstr_new=str(datetime_val)\nprint(\"The string Date time \",dtstr_new)\nprint(\"Data type: \",type(dtstr_new))"
},
{
"code": null,
"e": 1927,
"s": 1872,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2099,
"s": 1927,
"text": "Given date time:\nSeptember 19 2019 21:02:23 PM\nData Type:\nAfter converting to date time:\n2019-09-19 21:02:23\nData type:\nThe string Date time 2019-09-19 21:02:23\nData type:"
},
{
"code": null,
"e": 2267,
"s": 2099,
"text": "The str function will convert its parameter to a string. So here we take a datetime value by using the today function and supply it as a parameter to the str function."
},
{
"code": null,
"e": 2278,
"s": 2267,
"text": " Live Demo"
},
{
"code": null,
"e": 2517,
"s": 2278,
"text": "import datetime\nprint(\"Date time data type: \\n\",datetime.datetime.today())\nprint(\"Data type: \\n\",type(datetime.datetime.today()))\ndtstr= str(datetime.datetime.today())\nprint(\"String Date time:\\n \",dtstr)\nprint(\"Data type: \\n\",type(dtstr))"
},
{
"code": null,
"e": 2572,
"s": 2517,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2688,
"s": 2572,
"text": "Date time data type:\n2020-05-18 11:09:40.986027\nData type:\n\nString Date time:\n2020-05-18 11:09:40.986027\nData type:"
}
] |
Powershell - Copy File
|
Copy-Item cmdlet is used to copy a file by passing the path of the file to be copied and destination path where the file is to be copied.
In this example, we'll copy a folder D:\Temp\Test Folder\Test File.txt to D:\Temp\Test Folder1
Type the following command in PowerShell ISE Console
Copy-Item 'D:\temp\Test Folder\Test File.txt' 'D:\temp\Test Folder1\Test File1.txt'
You can see the Test File1.txt in Test Folder1 with content of Test File.txt. Test Folder1 folder should be present before running this command.
In this example, we'll copy all text file recursively D:\Temp\Test Folder to D:\Temp\Test Folder1
Type the following command in PowerShell ISE Console
Copy-Item -Filter *.txt -Path 'D:\temp\Test Folder' -Recurse -Destination 'D:\temp\Test Folder1'
You can see the content of Test Folder1 in Windows Explorer where it contains both the Test Folder and only text based file(s).
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2172,
"s": 2034,
"text": "Copy-Item cmdlet is used to copy a file by passing the path of the file to be copied and destination path where the file is to be copied."
},
{
"code": null,
"e": 2267,
"s": 2172,
"text": "In this example, we'll copy a folder D:\\Temp\\Test Folder\\Test File.txt to D:\\Temp\\Test Folder1"
},
{
"code": null,
"e": 2320,
"s": 2267,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2404,
"s": 2320,
"text": "Copy-Item 'D:\\temp\\Test Folder\\Test File.txt' 'D:\\temp\\Test Folder1\\Test File1.txt'"
},
{
"code": null,
"e": 2549,
"s": 2404,
"text": "You can see the Test File1.txt in Test Folder1 with content of Test File.txt. Test Folder1 folder should be present before running this command."
},
{
"code": null,
"e": 2647,
"s": 2549,
"text": "In this example, we'll copy all text file recursively D:\\Temp\\Test Folder to D:\\Temp\\Test Folder1"
},
{
"code": null,
"e": 2700,
"s": 2647,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2797,
"s": 2700,
"text": "Copy-Item -Filter *.txt -Path 'D:\\temp\\Test Folder' -Recurse -Destination 'D:\\temp\\Test Folder1'"
},
{
"code": null,
"e": 2925,
"s": 2797,
"text": "You can see the content of Test Folder1 in Windows Explorer where it contains both the Test Folder and only text based file(s)."
},
{
"code": null,
"e": 2960,
"s": 2925,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2981,
"s": 2960,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 3016,
"s": 2981,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3029,
"s": 3016,
"text": " Vijay Saini"
},
{
"code": null,
"e": 3066,
"s": 3029,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3078,
"s": 3066,
"text": " Fettah Ben"
},
{
"code": null,
"e": 3085,
"s": 3078,
"text": " Print"
},
{
"code": null,
"e": 3096,
"s": 3085,
"text": " Add Notes"
}
] |
How to convert PHP array to JavaScript or JSON ? - GeeksforGeeks
|
30 Sep, 2019
PHP provides a json_encode() function that converts PHP arrays into JavaScript. Technically, it is in JSON format. JSON stands for JavaScript Object Notation.
Statement: If you have a PHP array and you need to convert it into the JavaScript array so there is a function provided by PHP that will easily convert that PHP array into the JavaScript array. But before using this function you need few things that first make sure you are using PHP version 5.2 or above. Next, use the library function json_encode() to convert the PHP array to JavaScript array.
Syntax:
json_encode( $my_array );
Example 1: This example uses json_encode() function to convert PHP array to JavaScript JSON object.
<?php // Array in php$myArr = array('Geeks', 'GeeksforGeeks@geeks.com');?> <!-- Converting PHP array into JavaScript array --><script>var arr = <?php echo json_encode($myArr); ?>;document.write(arr[1]);</script> <?php ?>
Output:
GeeksforGeeks@geeks.com
Example 2: Here you will see converting single dimensional PHP array into javaScript array by using json_encode($myArr). Passing the php array and then using json_encode, we convert it into javascript array.
<?php ?><script type='text/javascript'><?php$php_array = array('geeks', 'for', 'geeks');$js_array = json_encode($php_array);echo "var javascript_array = ". $js_array . ";\n";?>document.write(javascript_array[0]);</script> <?php ?>
Output:
geeks
Example 3: Here you will see converting multi-dimensional PHP array into javaScript array by using json_encode($myArr). Passing the php array and then using json_encode, we convert it into javascript array.
<?php ?> <script type='text/javascript'> <?php$php_array = array( array('Geeks', 'for@example.com'), array('for', 'gfg@example.com'),);$js_array = json_encode($php_array);echo "var javascript_array = ". $js_array . ";\n";?> document.write(javascript_array[0][1]);</script> <?php ?>
Output:
for@example.com
Note:It should be noted that json_encode() function is only available in PHP 5.2 or after versions.
Akanksha_Rai
JSON
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.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
|
[
{
"code": null,
"e": 31015,
"s": 30987,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 31174,
"s": 31015,
"text": "PHP provides a json_encode() function that converts PHP arrays into JavaScript. Technically, it is in JSON format. JSON stands for JavaScript Object Notation."
},
{
"code": null,
"e": 31571,
"s": 31174,
"text": "Statement: If you have a PHP array and you need to convert it into the JavaScript array so there is a function provided by PHP that will easily convert that PHP array into the JavaScript array. But before using this function you need few things that first make sure you are using PHP version 5.2 or above. Next, use the library function json_encode() to convert the PHP array to JavaScript array."
},
{
"code": null,
"e": 31579,
"s": 31571,
"text": "Syntax:"
},
{
"code": null,
"e": 31605,
"s": 31579,
"text": "json_encode( $my_array );"
},
{
"code": null,
"e": 31705,
"s": 31605,
"text": "Example 1: This example uses json_encode() function to convert PHP array to JavaScript JSON object."
},
{
"code": "<?php // Array in php$myArr = array('Geeks', 'GeeksforGeeks@geeks.com');?> <!-- Converting PHP array into JavaScript array --><script>var arr = <?php echo json_encode($myArr); ?>;document.write(arr[1]);</script> <?php ?>",
"e": 31930,
"s": 31705,
"text": null
},
{
"code": null,
"e": 31938,
"s": 31930,
"text": "Output:"
},
{
"code": null,
"e": 31963,
"s": 31938,
"text": "GeeksforGeeks@geeks.com\n"
},
{
"code": null,
"e": 32171,
"s": 31963,
"text": "Example 2: Here you will see converting single dimensional PHP array into javaScript array by using json_encode($myArr). Passing the php array and then using json_encode, we convert it into javascript array."
},
{
"code": "<?php ?><script type='text/javascript'><?php$php_array = array('geeks', 'for', 'geeks');$js_array = json_encode($php_array);echo \"var javascript_array = \". $js_array . \";\\n\";?>document.write(javascript_array[0]);</script> <?php ?>",
"e": 32405,
"s": 32171,
"text": null
},
{
"code": null,
"e": 32413,
"s": 32405,
"text": "Output:"
},
{
"code": null,
"e": 32419,
"s": 32413,
"text": "geeks"
},
{
"code": null,
"e": 32626,
"s": 32419,
"text": "Example 3: Here you will see converting multi-dimensional PHP array into javaScript array by using json_encode($myArr). Passing the php array and then using json_encode, we convert it into javascript array."
},
{
"code": "<?php ?> <script type='text/javascript'> <?php$php_array = array( array('Geeks', 'for@example.com'), array('for', 'gfg@example.com'),);$js_array = json_encode($php_array);echo \"var javascript_array = \". $js_array . \";\\n\";?> document.write(javascript_array[0][1]);</script> <?php ?>",
"e": 32918,
"s": 32626,
"text": null
},
{
"code": null,
"e": 32926,
"s": 32918,
"text": "Output:"
},
{
"code": null,
"e": 32942,
"s": 32926,
"text": "for@example.com"
},
{
"code": null,
"e": 33042,
"s": 32942,
"text": "Note:It should be noted that json_encode() function is only available in PHP 5.2 or after versions."
},
{
"code": null,
"e": 33055,
"s": 33042,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 33060,
"s": 33055,
"text": "JSON"
},
{
"code": null,
"e": 33067,
"s": 33060,
"text": "Picked"
},
{
"code": null,
"e": 33071,
"s": 33067,
"text": "PHP"
},
{
"code": null,
"e": 33084,
"s": 33071,
"text": "PHP Programs"
},
{
"code": null,
"e": 33101,
"s": 33084,
"text": "Web Technologies"
},
{
"code": null,
"e": 33128,
"s": 33101,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 33132,
"s": 33128,
"text": "PHP"
},
{
"code": null,
"e": 33230,
"s": 33132,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33239,
"s": 33230,
"text": "Comments"
},
{
"code": null,
"e": 33252,
"s": 33239,
"text": "Old Comments"
},
{
"code": null,
"e": 33302,
"s": 33252,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 33347,
"s": 33302,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 33391,
"s": 33347,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 33415,
"s": 33391,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 33455,
"s": 33415,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 33505,
"s": 33455,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 33550,
"s": 33505,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 33594,
"s": 33550,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 33634,
"s": 33594,
"text": "How to convert array to string in PHP ?"
}
] |
How to use simple API using AJAX ? - GeeksforGeeks
|
03 Jun, 2020
AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX.
Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here.
What are basic building?We will be fetching employee’s names from an employee object from a free API and displaying them inside a list. There are many API available for free on the internet. You can use any one of them.
HTML Code: We have a button and to fetch data and an empty unordered list inside which we will be adding our list-items dynamically using JavaScript.
<!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 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <title> How to use simple API using AJAX ? </title></head> <body> <button type="button" id="fetchBtn" class="btn btn-primary"> Fetch Data </button> <div class="container"> <h1>Employee List</h1> <ul id="list"></ul> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="Ajax.js"></script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html>
AJAX Code:
Step 1: The first step is to get the button element getElementById method.
Step 2: The second step is to add an eventListener to the the button and providing a call-back function to it.
Step 3: Instantiate an XHR object using new keyword.
Step 4: Open an object using open function. It takes three parameters, the first one is type (GET or POST), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call).
Step 5: Now we will use onload function to display the data. The onload function is executed after the API call is done. We will check for the status of success. We are checking it with 200 as 200 is the success code for an HTTP request.
Step 6: Now, we will use parse it into a JSON object so that we can easily fetch data from it.
Step 7: In this step, we will use a loop to iterate over all the items in the object and adding it to the list using innerhtml property.
Step 8: Last step is to send the request using the send() function.Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand.<script> let fetchBtn = document.getElementById("fetchBtn"); fetchBtn.addEventListener("click", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById("list"); str = "" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log("File not found"); } } // At last send the request xhr.send(); }</script>Complete Code: It is the combination of the above two code sections.<!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 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <title> How to use simple API using AJAX ? </title></head> <body> <button type="button" id="fetchBtn" class="btn btn-primary"> Fetch Data </button> <div class="container"> <h1>Employee List</h1> <ul id="list"></ul> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script> let fetchBtn = document.getElementById("fetchBtn"); fetchBtn.addEventListener("click", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById("list"); str = "" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log("File not found"); } } xhr.send(); } </script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html>Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand.
<script> let fetchBtn = document.getElementById("fetchBtn"); fetchBtn.addEventListener("click", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById("list"); str = "" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log("File not found"); } } // At last send the request xhr.send(); }</script>
Complete Code: It is the combination of the above two code sections.
<!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 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <title> How to use simple API using AJAX ? </title></head> <body> <button type="button" id="fetchBtn" class="btn btn-primary"> Fetch Data </button> <div class="container"> <h1>Employee List</h1> <ul id="list"></ul> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script> let fetchBtn = document.getElementById("fetchBtn"); fetchBtn.addEventListener("click", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById("list"); str = "" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log("File not found"); } } xhr.send(); } </script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
jQuery-AJAX
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 create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 25108,
"s": 25080,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 25294,
"s": 25108,
"text": "AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX."
},
{
"code": null,
"e": 25391,
"s": 25294,
"text": "Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here."
},
{
"code": null,
"e": 25611,
"s": 25391,
"text": "What are basic building?We will be fetching employee’s names from an employee object from a free API and displaying them inside a list. There are many API available for free on the internet. You can use any one of them."
},
{
"code": null,
"e": 25761,
"s": 25611,
"text": "HTML Code: We have a button and to fetch data and an empty unordered list inside which we will be adding our list-items dynamically using JavaScript."
},
{
"code": "<!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 --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\" /> <title> How to use simple API using AJAX ? </title></head> <body> <button type=\"button\" id=\"fetchBtn\" class=\"btn btn-primary\"> Fetch Data </button> <div class=\"container\"> <h1>Employee List</h1> <ul id=\"list\"></ul> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"Ajax.js\"></script> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>",
"e": 27310,
"s": 25761,
"text": null
},
{
"code": null,
"e": 27321,
"s": 27310,
"text": "AJAX Code:"
},
{
"code": null,
"e": 27396,
"s": 27321,
"text": "Step 1: The first step is to get the button element getElementById method."
},
{
"code": null,
"e": 27507,
"s": 27396,
"text": "Step 2: The second step is to add an eventListener to the the button and providing a call-back function to it."
},
{
"code": null,
"e": 27560,
"s": 27507,
"text": "Step 3: Instantiate an XHR object using new keyword."
},
{
"code": null,
"e": 27795,
"s": 27560,
"text": "Step 4: Open an object using open function. It takes three parameters, the first one is type (GET or POST), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call)."
},
{
"code": null,
"e": 28033,
"s": 27795,
"text": "Step 5: Now we will use onload function to display the data. The onload function is executed after the API call is done. We will check for the status of success. We are checking it with 200 as 200 is the success code for an HTTP request."
},
{
"code": null,
"e": 28128,
"s": 28033,
"text": "Step 6: Now, we will use parse it into a JSON object so that we can easily fetch data from it."
},
{
"code": null,
"e": 28265,
"s": 28128,
"text": "Step 7: In this step, we will use a loop to iterate over all the items in the object and adding it to the list using innerhtml property."
},
{
"code": null,
"e": 32494,
"s": 28265,
"text": "Step 8: Last step is to send the request using the send() function.Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand.<script> let fetchBtn = document.getElementById(\"fetchBtn\"); fetchBtn.addEventListener(\"click\", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open(\"GET\", \"http://dummy.restapiexample.com/api/v1/employees\", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById(\"list\"); str = \"\" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log(\"File not found\"); } } // At last send the request xhr.send(); }</script>Complete Code: It is the combination of the above two code sections.<!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 --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\" /> <title> How to use simple API using AJAX ? </title></head> <body> <button type=\"button\" id=\"fetchBtn\" class=\"btn btn-primary\"> Fetch Data </button> <div class=\"container\"> <h1>Employee List</h1> <ul id=\"list\"></ul> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script> let fetchBtn = document.getElementById(\"fetchBtn\"); fetchBtn.addEventListener(\"click\", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open(\"GET\", \"http://dummy.restapiexample.com/api/v1/employees\", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById(\"list\"); str = \"\" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log(\"File not found\"); } } xhr.send(); } </script> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32626,
"s": 32494,
"text": "Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand."
},
{
"code": "<script> let fetchBtn = document.getElementById(\"fetchBtn\"); fetchBtn.addEventListener(\"click\", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open(\"GET\", \"http://dummy.restapiexample.com/api/v1/employees\", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById(\"list\"); str = \"\" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log(\"File not found\"); } } // At last send the request xhr.send(); }</script>",
"e": 33706,
"s": 32626,
"text": null
},
{
"code": null,
"e": 33775,
"s": 33706,
"text": "Complete Code: It is the combination of the above two code sections."
},
{
"code": "<!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 --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\" /> <title> How to use simple API using AJAX ? </title></head> <body> <button type=\"button\" id=\"fetchBtn\" class=\"btn btn-primary\"> Fetch Data </button> <div class=\"container\"> <h1>Employee List</h1> <ul id=\"list\"></ul> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script> let fetchBtn = document.getElementById(\"fetchBtn\"); fetchBtn.addEventListener(\"click\", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open(\"GET\", \"http://dummy.restapiexample.com/api/v1/employees\", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById(\"list\"); str = \"\" for (key in obj.data) { str += `<li>${obj.data[key].employee_name}</li>`; } list.innerHTML = str; } else { console.log(\"File not found\"); } } xhr.send(); } </script> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>",
"e": 36481,
"s": 33775,
"text": null
},
{
"code": null,
"e": 36489,
"s": 36481,
"text": "Output:"
},
{
"code": null,
"e": 36626,
"s": 36489,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 36638,
"s": 36626,
"text": "jQuery-AJAX"
},
{
"code": null,
"e": 36642,
"s": 36638,
"text": "CSS"
},
{
"code": null,
"e": 36647,
"s": 36642,
"text": "HTML"
},
{
"code": null,
"e": 36664,
"s": 36647,
"text": "Web Technologies"
},
{
"code": null,
"e": 36691,
"s": 36664,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 36696,
"s": 36691,
"text": "HTML"
},
{
"code": null,
"e": 36794,
"s": 36696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36852,
"s": 36794,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 36889,
"s": 36852,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 36953,
"s": 36889,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 36990,
"s": 36953,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 37031,
"s": 36990,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 37091,
"s": 37031,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 37152,
"s": 37091,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 37205,
"s": 37152,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 37255,
"s": 37205,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
console in JavaScript - GeeksforGeeks
|
11 Feb, 2022
Web console
A Web console is a tool which is mainly used to log information associated with a web page like: network requests, JavaScript, security errors, warnings, CSS etc. It enables us to interact with a web page by executing JavaScript expression in the contents of the page.
Console object
In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like :
log()
error()
warn()
clear()
time() and timeEnd()
table()
count()
group() and groupEnd()
custom console logs
Let’s look at all these methods one by one.
console.log()
Mainly used to log(print) the output to the console. We can put any type inside the log(), be it a string, array, object, boolean etc.
javascript
// console.log() methodconsole.log('abc');console.log(1);console.log(true);console.log(null);console.log(undefined);console.log([1, 2, 3, 4]); // array inside logconsole.log({a:1, b:2, c:3}); // object inside log
Output:
console.error()
This method is used to log error message to the console. Useful in testing of code. By default the error message will be highlighted with red color.
javascript
// console.error() methodconsole.error('This is a simple error');
Output:
console.warn()
Used to log warning message to the console. By default the warning message will be highlighted with yellow color.
javascript
// console.warn() methodconsole.warn('This is a warning.');
Output:
console.clear()
Used to clear the console. The console will be cleared, in case of Chrome a simple overlayed text will be printed like : ‘Console was cleared’ while in Firefox no message is returned.
javascript
// console.clear() methodconsole.clear();
Output:
console.time() and console.timeEnd()
Whenever we want to know the amount of time spend by a block or a function, we can make use of the time() and timeEnd() methods provided by the JavaScript console object. They take a label which must be same, and the code inside can be anything( function, object, simple console).
javascript
// console.time() and console.timeEnd() methodconsole.time('abc'); let fun = function(){ console.log('fun is running'); } let fun2 = function(){ console.log('fun2 is running..'); } fun(); // calling fun(); fun2(); // calling fun2();console.timeEnd('abc');
In the above code snippet, we can see that the label is ‘abc’ which is same for both the time() and the timeEnd() method. If we increase the amount of code inside the block defined by these methods, then the time will increase. It is also worth remembering that the time returned to the console will be in milliseconds and might be different each time we refresh the page. Output:
console.table()
This method allows us to generate a table inside a console. The input must be an array or an object which will be shown as a table.
javascript
// console.table() methodconsole.table({'a':1, 'b':2});
Output:
console.count()
This method is used to count the number that the function hit by this counting method.
javascript
// console.count() methodfor(let i=0;i<5;i++){ console.count(i);}
output:
console.group() and console.groupEnd()
group() and groupEnd() methods of the console object allows us to group contents in a separate block, which will be indented. Just like the time() and the timeEnd() they also accepts label, again of same value.
javascript
// console.group() and console.groupEnd() methodconsole.group('simple'); console.warn('warning!'); console.error('error here'); console.log('vivi vini vici');console.groupEnd('simple');console.log('new section');
Output:
Custom Console Logs
User can add Styling to the console logs in order to make logs Custom . The Syntax for it is to add the CSS styling as a parameter to the logs which will replace %c in the logs as shown in the example below .
javascript
// Custom Console log example const spacing = '10px'; const styles = `padding: ${spacing}; background-color: white; color: green; font-style: italic; border: 1px solid black; font-size: 2em;`; console.log('%cGeeks for Geeks', styles);
Output:
Console Sidebar
Console sidebar is used to organize logs and provides clarity in debugging experience.
After Filtering Errors only using console sidebar :
After Filtering Warnings only using console sidebar :
Supported Browser:
Google Chrome
Firefox
Internet Explorer
Opera
ShJos
ysachin2314
amansingla
javascript-basics
JavaScript
Web Technologies
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
How to Use the JavaScript Fetch API to Get Data?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24330,
"s": 24302,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 24342,
"s": 24330,
"text": "Web console"
},
{
"code": null,
"e": 24613,
"s": 24342,
"text": "A Web console is a tool which is mainly used to log information associated with a web page like: network requests, JavaScript, security errors, warnings, CSS etc. It enables us to interact with a web page by executing JavaScript expression in the contents of the page. "
},
{
"code": null,
"e": 24628,
"s": 24613,
"text": "Console object"
},
{
"code": null,
"e": 24906,
"s": 24628,
"text": "In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like : "
},
{
"code": null,
"e": 24912,
"s": 24906,
"text": "log()"
},
{
"code": null,
"e": 24920,
"s": 24912,
"text": "error()"
},
{
"code": null,
"e": 24927,
"s": 24920,
"text": "warn()"
},
{
"code": null,
"e": 24935,
"s": 24927,
"text": "clear()"
},
{
"code": null,
"e": 24956,
"s": 24935,
"text": "time() and timeEnd()"
},
{
"code": null,
"e": 24964,
"s": 24956,
"text": "table()"
},
{
"code": null,
"e": 24972,
"s": 24964,
"text": "count()"
},
{
"code": null,
"e": 24995,
"s": 24972,
"text": "group() and groupEnd()"
},
{
"code": null,
"e": 25015,
"s": 24995,
"text": "custom console logs"
},
{
"code": null,
"e": 25061,
"s": 25015,
"text": "Let’s look at all these methods one by one. "
},
{
"code": null,
"e": 25075,
"s": 25061,
"text": "console.log()"
},
{
"code": null,
"e": 25212,
"s": 25075,
"text": "Mainly used to log(print) the output to the console. We can put any type inside the log(), be it a string, array, object, boolean etc. "
},
{
"code": null,
"e": 25223,
"s": 25212,
"text": "javascript"
},
{
"code": "// console.log() methodconsole.log('abc');console.log(1);console.log(true);console.log(null);console.log(undefined);console.log([1, 2, 3, 4]); // array inside logconsole.log({a:1, b:2, c:3}); // object inside log",
"e": 25436,
"s": 25223,
"text": null
},
{
"code": null,
"e": 25446,
"s": 25436,
"text": "Output: "
},
{
"code": null,
"e": 25464,
"s": 25448,
"text": "console.error()"
},
{
"code": null,
"e": 25615,
"s": 25464,
"text": "This method is used to log error message to the console. Useful in testing of code. By default the error message will be highlighted with red color. "
},
{
"code": null,
"e": 25626,
"s": 25615,
"text": "javascript"
},
{
"code": "// console.error() methodconsole.error('This is a simple error');",
"e": 25692,
"s": 25626,
"text": null
},
{
"code": null,
"e": 25702,
"s": 25692,
"text": "Output: "
},
{
"code": null,
"e": 25719,
"s": 25704,
"text": "console.warn()"
},
{
"code": null,
"e": 25835,
"s": 25719,
"text": "Used to log warning message to the console. By default the warning message will be highlighted with yellow color. "
},
{
"code": null,
"e": 25846,
"s": 25835,
"text": "javascript"
},
{
"code": "// console.warn() methodconsole.warn('This is a warning.');",
"e": 25906,
"s": 25846,
"text": null
},
{
"code": null,
"e": 25916,
"s": 25906,
"text": "Output: "
},
{
"code": null,
"e": 25934,
"s": 25918,
"text": "console.clear()"
},
{
"code": null,
"e": 26120,
"s": 25934,
"text": "Used to clear the console. The console will be cleared, in case of Chrome a simple overlayed text will be printed like : ‘Console was cleared’ while in Firefox no message is returned. "
},
{
"code": null,
"e": 26131,
"s": 26120,
"text": "javascript"
},
{
"code": "// console.clear() methodconsole.clear();",
"e": 26173,
"s": 26131,
"text": null
},
{
"code": null,
"e": 26183,
"s": 26173,
"text": "Output: "
},
{
"code": null,
"e": 26222,
"s": 26185,
"text": "console.time() and console.timeEnd()"
},
{
"code": null,
"e": 26505,
"s": 26222,
"text": "Whenever we want to know the amount of time spend by a block or a function, we can make use of the time() and timeEnd() methods provided by the JavaScript console object. They take a label which must be same, and the code inside can be anything( function, object, simple console). "
},
{
"code": null,
"e": 26516,
"s": 26505,
"text": "javascript"
},
{
"code": "// console.time() and console.timeEnd() methodconsole.time('abc'); let fun = function(){ console.log('fun is running'); } let fun2 = function(){ console.log('fun2 is running..'); } fun(); // calling fun(); fun2(); // calling fun2();console.timeEnd('abc');",
"e": 26781,
"s": 26516,
"text": null
},
{
"code": null,
"e": 27164,
"s": 26781,
"text": "In the above code snippet, we can see that the label is ‘abc’ which is same for both the time() and the timeEnd() method. If we increase the amount of code inside the block defined by these methods, then the time will increase. It is also worth remembering that the time returned to the console will be in milliseconds and might be different each time we refresh the page. Output: "
},
{
"code": null,
"e": 27182,
"s": 27166,
"text": "console.table()"
},
{
"code": null,
"e": 27316,
"s": 27182,
"text": "This method allows us to generate a table inside a console. The input must be an array or an object which will be shown as a table. "
},
{
"code": null,
"e": 27327,
"s": 27316,
"text": "javascript"
},
{
"code": "// console.table() methodconsole.table({'a':1, 'b':2});",
"e": 27383,
"s": 27327,
"text": null
},
{
"code": null,
"e": 27393,
"s": 27383,
"text": "Output: "
},
{
"code": null,
"e": 27411,
"s": 27395,
"text": "console.count()"
},
{
"code": null,
"e": 27500,
"s": 27411,
"text": "This method is used to count the number that the function hit by this counting method. "
},
{
"code": null,
"e": 27511,
"s": 27500,
"text": "javascript"
},
{
"code": "// console.count() methodfor(let i=0;i<5;i++){ console.count(i);}",
"e": 27580,
"s": 27511,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27580,
"text": "output: "
},
{
"code": null,
"e": 27631,
"s": 27592,
"text": "console.group() and console.groupEnd()"
},
{
"code": null,
"e": 27844,
"s": 27631,
"text": "group() and groupEnd() methods of the console object allows us to group contents in a separate block, which will be indented. Just like the time() and the timeEnd() they also accepts label, again of same value. "
},
{
"code": null,
"e": 27855,
"s": 27844,
"text": "javascript"
},
{
"code": "// console.group() and console.groupEnd() methodconsole.group('simple'); console.warn('warning!'); console.error('error here'); console.log('vivi vini vici');console.groupEnd('simple');console.log('new section');",
"e": 28071,
"s": 27855,
"text": null
},
{
"code": null,
"e": 28081,
"s": 28071,
"text": "Output: "
},
{
"code": null,
"e": 28103,
"s": 28083,
"text": "Custom Console Logs"
},
{
"code": null,
"e": 28314,
"s": 28103,
"text": "User can add Styling to the console logs in order to make logs Custom . The Syntax for it is to add the CSS styling as a parameter to the logs which will replace %c in the logs as shown in the example below . "
},
{
"code": null,
"e": 28325,
"s": 28314,
"text": "javascript"
},
{
"code": "// Custom Console log example const spacing = '10px'; const styles = `padding: ${spacing}; background-color: white; color: green; font-style: italic; border: 1px solid black; font-size: 2em;`; console.log('%cGeeks for Geeks', styles);",
"e": 28578,
"s": 28325,
"text": null
},
{
"code": null,
"e": 28588,
"s": 28578,
"text": "Output: "
},
{
"code": null,
"e": 28606,
"s": 28590,
"text": "Console Sidebar"
},
{
"code": null,
"e": 28695,
"s": 28606,
"text": "Console sidebar is used to organize logs and provides clarity in debugging experience. "
},
{
"code": null,
"e": 28749,
"s": 28695,
"text": "After Filtering Errors only using console sidebar : "
},
{
"code": null,
"e": 28805,
"s": 28749,
"text": "After Filtering Warnings only using console sidebar : "
},
{
"code": null,
"e": 28824,
"s": 28805,
"text": "Supported Browser:"
},
{
"code": null,
"e": 28838,
"s": 28824,
"text": "Google Chrome"
},
{
"code": null,
"e": 28846,
"s": 28838,
"text": "Firefox"
},
{
"code": null,
"e": 28864,
"s": 28846,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28871,
"s": 28864,
"text": "Opera "
},
{
"code": null,
"e": 28877,
"s": 28871,
"text": "ShJos"
},
{
"code": null,
"e": 28889,
"s": 28877,
"text": "ysachin2314"
},
{
"code": null,
"e": 28900,
"s": 28889,
"text": "amansingla"
},
{
"code": null,
"e": 28918,
"s": 28900,
"text": "javascript-basics"
},
{
"code": null,
"e": 28929,
"s": 28918,
"text": "JavaScript"
},
{
"code": null,
"e": 28946,
"s": 28929,
"text": "Web Technologies"
},
{
"code": null,
"e": 29044,
"s": 28946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29053,
"s": 29044,
"text": "Comments"
},
{
"code": null,
"e": 29066,
"s": 29053,
"text": "Old Comments"
},
{
"code": null,
"e": 29127,
"s": 29066,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29172,
"s": 29127,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29244,
"s": 29172,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29285,
"s": 29244,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29334,
"s": 29285,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 29390,
"s": 29334,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29423,
"s": 29390,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29485,
"s": 29423,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29528,
"s": 29485,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python 3 - Tkinter Relief styles
|
The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here is a screenshot of a row of buttons exhibiting all the possible relief styles −
Here is list of possible constants which can be used for relief attribute −
FLAT
RAISED
SUNKEN
GROOVE
RIDGE
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
B1 = Button(top, text = "FLAT", relief = FLAT )
B2 = Button(top, text = "RAISED", relief = RAISED )
B3 = Button(top, text = "SUNKEN", relief = SUNKEN )
B4 = Button(top, text = "GROOVE", relief = GROOVE )
B5 = Button(top, text = "RIDGE", relief = RIDGE )
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result −
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": 2528,
"s": 2340,
"text": "The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here is a screenshot of a row of buttons exhibiting all the possible relief styles −"
},
{
"code": null,
"e": 2604,
"s": 2528,
"text": "Here is list of possible constants which can be used for relief attribute −"
},
{
"code": null,
"e": 2609,
"s": 2604,
"text": "FLAT"
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": "RAISED"
},
{
"code": null,
"e": 2623,
"s": 2616,
"text": "SUNKEN"
},
{
"code": null,
"e": 2630,
"s": 2623,
"text": "GROOVE"
},
{
"code": null,
"e": 2636,
"s": 2630,
"text": "RIDGE"
},
{
"code": null,
"e": 3026,
"s": 2636,
"text": "# !/usr/bin/python3\nfrom tkinter import *\nimport tkinter\n\ntop = Tk()\n\nB1 = Button(top, text = \"FLAT\", relief = FLAT )\nB2 = Button(top, text = \"RAISED\", relief = RAISED )\nB3 = Button(top, text = \"SUNKEN\", relief = SUNKEN )\nB4 = Button(top, text = \"GROOVE\", relief = GROOVE )\nB5 = Button(top, text = \"RIDGE\", relief = RIDGE )\n\nB1.pack()\nB2.pack()\nB3.pack()\nB4.pack()\nB5.pack()\ntop.mainloop()"
},
{
"code": null,
"e": 3094,
"s": 3026,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3131,
"s": 3094,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3147,
"s": 3131,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3180,
"s": 3147,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3199,
"s": 3180,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3234,
"s": 3199,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3256,
"s": 3234,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3290,
"s": 3256,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3318,
"s": 3290,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3353,
"s": 3318,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3367,
"s": 3353,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3400,
"s": 3367,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3417,
"s": 3400,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3424,
"s": 3417,
"text": " Print"
},
{
"code": null,
"e": 3435,
"s": 3424,
"text": " Add Notes"
}
] |
HTML | <input> autofocus Attribute - GeeksforGeeks
|
29 Apr, 2019
The HTML <input> autofocus Attribute is used to specify that the input field must get automatically get focus when the page loads. It is a Boolean attribute.
Syntax:
<input autofocus>
Example: This Example that illustrates the use of autofocus attribute in <input> element.
<!DOCTYPE html><html> <head> <title> HTML | <input>autofocus Attribute </title></head> <body style="text-align:center"> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML | <input>autofocus Attribute </h2> Name: <input type="text" autofocus> <br> <br> <!-- Assign id to the Button. --> <button id="GFG"> Submit </button> <br></body> </html>
Output:
Supported Browsers: The browser supported by HTML | <input>autofocus Attribute are listed below:
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.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
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 ?
Convert a string to an integer in JavaScript
Installation of Node.js on Linux
|
[
{
"code": null,
"e": 30376,
"s": 30348,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 30534,
"s": 30376,
"text": "The HTML <input> autofocus Attribute is used to specify that the input field must get automatically get focus when the page loads. It is a Boolean attribute."
},
{
"code": null,
"e": 30542,
"s": 30534,
"text": "Syntax:"
},
{
"code": null,
"e": 30561,
"s": 30542,
"text": "<input autofocus> "
},
{
"code": null,
"e": 30651,
"s": 30561,
"text": "Example: This Example that illustrates the use of autofocus attribute in <input> element."
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | <input>autofocus Attribute </title></head> <body style=\"text-align:center\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> HTML | <input>autofocus Attribute </h2> Name: <input type=\"text\" autofocus> <br> <br> <!-- Assign id to the Button. --> <button id=\"GFG\"> Submit </button> <br></body> </html>",
"e": 31091,
"s": 30651,
"text": null
},
{
"code": null,
"e": 31099,
"s": 31091,
"text": "Output:"
},
{
"code": null,
"e": 31196,
"s": 31099,
"text": "Supported Browsers: The browser supported by HTML | <input>autofocus Attribute are listed below:"
},
{
"code": null,
"e": 31210,
"s": 31196,
"text": "Google Chrome"
},
{
"code": null,
"e": 31228,
"s": 31210,
"text": "Internet Explorer"
},
{
"code": null,
"e": 31236,
"s": 31228,
"text": "Firefox"
},
{
"code": null,
"e": 31242,
"s": 31236,
"text": "Opera"
},
{
"code": null,
"e": 31249,
"s": 31242,
"text": "Safari"
},
{
"code": null,
"e": 31386,
"s": 31249,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31402,
"s": 31386,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 31407,
"s": 31402,
"text": "HTML"
},
{
"code": null,
"e": 31424,
"s": 31407,
"text": "Web Technologies"
},
{
"code": null,
"e": 31429,
"s": 31424,
"text": "HTML"
},
{
"code": null,
"e": 31527,
"s": 31429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31589,
"s": 31527,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31639,
"s": 31589,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31699,
"s": 31639,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31747,
"s": 31699,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31808,
"s": 31747,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31850,
"s": 31808,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31912,
"s": 31850,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31955,
"s": 31912,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32000,
"s": 31955,
"text": "Convert a string to an integer in JavaScript"
}
] |
Java - toString() Method
|
The method is used to get a String object representing the value of the Number Object.
If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.
If the method takes two arguments, then a String representation of the first argument in the radix specified by the second argument will be returned.
Following are all the variants of this method −
String toString()
static String toString(int i)
Here is the detail of parameters −
i − An int for which string representation would be returned.
i − An int for which string representation would be returned.
toString() − This returns a String object representing the value of this Integer.
toString() − This returns a String object representing the value of this Integer.
toString(int i) − This returns a String object representing the specified integer.
toString(int i) − This returns a String object representing the specified integer.
public class Test {
public static void main(String args[]) {
Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
}
}
This will produce the following result −
5
12
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": 2464,
"s": 2377,
"text": "The method is used to get a String object representing the value of the Number Object."
},
{
"code": null,
"e": 2601,
"s": 2464,
"text": "If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned."
},
{
"code": null,
"e": 2751,
"s": 2601,
"text": "If the method takes two arguments, then a String representation of the first argument in the radix specified by the second argument will be returned."
},
{
"code": null,
"e": 2799,
"s": 2751,
"text": "Following are all the variants of this method −"
},
{
"code": null,
"e": 2848,
"s": 2799,
"text": "String toString()\nstatic String toString(int i)\n"
},
{
"code": null,
"e": 2883,
"s": 2848,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2945,
"s": 2883,
"text": "i − An int for which string representation would be returned."
},
{
"code": null,
"e": 3007,
"s": 2945,
"text": "i − An int for which string representation would be returned."
},
{
"code": null,
"e": 3089,
"s": 3007,
"text": "toString() − This returns a String object representing the value of this Integer."
},
{
"code": null,
"e": 3171,
"s": 3089,
"text": "toString() − This returns a String object representing the value of this Integer."
},
{
"code": null,
"e": 3254,
"s": 3171,
"text": "toString(int i) − This returns a String object representing the specified integer."
},
{
"code": null,
"e": 3337,
"s": 3254,
"text": "toString(int i) − This returns a String object representing the specified integer."
},
{
"code": null,
"e": 3523,
"s": 3337,
"text": "public class Test { \n\n public static void main(String args[]) {\n Integer x = 5;\n\n System.out.println(x.toString()); \n System.out.println(Integer.toString(12)); \n }\n}"
},
{
"code": null,
"e": 3564,
"s": 3523,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3570,
"s": 3564,
"text": "5\n12\n"
},
{
"code": null,
"e": 3603,
"s": 3570,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3619,
"s": 3603,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3652,
"s": 3619,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3668,
"s": 3652,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3703,
"s": 3668,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3717,
"s": 3703,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3751,
"s": 3717,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3765,
"s": 3751,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3802,
"s": 3765,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3817,
"s": 3802,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3850,
"s": 3817,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3869,
"s": 3850,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3876,
"s": 3869,
"text": " Print"
},
{
"code": null,
"e": 3887,
"s": 3876,
"text": " Add Notes"
}
] |
BFS of graph | Practice | GeeksforGeeks
|
Given a directed graph. The task is to do Breadth First Traversal of this graph starting from 0.
Note: One can move from node u to node v only if there's an edge from u to v and find the BFS traversal of the graph starting from the 0th vertex, from left to right according to the graph. Also, you should only take nodes directly or indirectly connected from Node 0 in consideration.
Example 1:
Input:
Output: 0 1 2 3 4
Explanation:
0 is connected to 1 , 2 , 3.
2 is connected to 4.
so starting from 0, it will go to 1 then 2
then 3.After this 2 to 4, thus bfs will be
0 1 2 3 4.
Example 2:
Input:
Output: 0 1 2
Explanation:
0 is connected to 1 , 2.
so starting from 0, it will go to 1 then 2,
thus bfs will be 0 1 2 3 4.
Your task:
You don’t need to read input or print anything. Your task is to complete the function bfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a list containing the BFS traversal of the graph starting from the 0th vertex from left to right.
Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)
Constraints:
1 ≤ V, E ≤ 104
0
thakuraditya62116 hours ago
public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
ArrayList<Integer> ans = new ArrayList<>();
boolean []visited = new boolean[V];
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(0);
while(!queue.isEmpty()){
int rem = queue.remove();
ans.add(rem);
for(int e : adj.get(rem)){
if(visited[e] == false){
visited[e] = true;
queue.add(e);
}
}
}
return ans;
0
mankesh0163 days ago
vector<int> bfsOfGraph(int V, vector<int> adj[]) {
// Code here
vector<int> ans;
int visited[V]={0};
queue<int> q;
q.push(0);
visited[0]=true;
while(!q.empty()){
int n=q.front();
q.pop();
ans.push_back(n);
vector<int> :: iterator it;
for(it=adj[n].begin(); it!=adj[n].end(); it++){
if(!visited[*it]){
visited[*it]=true;
q.push(*it);
}
}
}
return ans;
}
-1
harshscode6 days ago
o(v+e) and o(v)
void bfs(int src,vector<int> &v1,vector<int> adj[],int v) { queue<int> q; vector<int> vis(v+1); q.push(0); while(!q.empty()) { int node=q.front(); q.pop(); v1.push_back(node); for(auto x:adj[node]) { if(!vis[x]) { q.push(x); vis[x]=1; } } } } vector<int> bfsOfGraph(int v, vector<int> adj[]) { vector<int> v1; bfs(0,v1,adj,v); return v1; }
0
jainmuskan5651 week ago
vector<int> bfsOfGraph(int V, vector<int> adj[]) { // we are going to use queue and visited array queue<int> q; vector<int>v; bool visited[V]={0}; q.push(0); visited[0]=true; while(!q.empty()){ int temp= q.front(); q.pop(); v.push_back(temp); // check the adjacency list for that node for(auto neighbor: adj[temp]){ if(!visited[neighbor]){ q.push(neighbor); visited[neighbor]=true; } } } return v; }
+1
aryany8711 week ago
vector<int> bfsOfGraph(int n, vector<int> adj[]) { //TC-O(V+E), AS-O(V) - queue and visited array are used bool visited[n] = {0}; vector<int>v; //to store the result queue<int>q; //source is 0 q.push(0); visited[0]=true; while(!q.empty()){ //pop the front node int currNode=q.front(); q.pop(); //push the current node in the result vector v.push_back(currNode); //now we will visit all the neighbours of the current node for(auto neighbour : adj[currNode]){ if(!visited[neighbour]){ q.push(neighbour); visited[neighbour]=true; } } } return v; }
+1
subhankar3184422 weeks ago
JAVA 0.53/6.06
ArrayList<Integer> list = new ArrayList<>(); Queue<Integer> q = new ArrayDeque<>(); boolean []vis = new boolean[V]; vis[0] = true; q.add(0); while(!q.isEmpty()){ int c = q.poll(); list.add(c); for(int i=0; i<adj.get(c).size(); i++){ int t = adj.get(c).get(i); if(!vis[t]){ vis[t] = true; q.add(t); } } } return list;
0
lilith2 weeks ago
Java Soln Bfs
class Solution {
// Function to return Breadth First Traversal of given graph.
public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
ArrayList<Integer> res = new ArrayList<>();
boolean[] visited = new boolean[V];
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(0);
while(!q.isEmpty()) {
int rem = q.remove();
res.add(rem);
for(int e : adj.get(rem)) {
if(visited[e] != true) {
visited[e] = true;
q.add(e);
}
}
}
return res;
}
}
+2
aryanvikas0072 weeks ago
For only first component :
Just use break after 1st iteration and you will get 1st component;
class Solution {
// Function to return Breadth First Traversal of given graph.
public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
ArrayList<Integer> bfs = new ArrayList<>();
boolean[] vis = new boolean[V];
for(int i=0; i<V; i++){
if(vis[i]==false){
Queue<Integer> q = new LinkedList<>();
q.add(i);
vis[i] = true;
while(!q.isEmpty()){
Integer node = q.poll();
bfs.add(node);
for(Integer it : adj.get(node)){
if(vis[it]==false){
vis[it]=true;
q.add(it);
}
}
}
}
break;
}
return bfs;
}
}
+1
deeptimayeemaharana062 weeks ago
code editor not working for this problem
pls check @gfg
+4
kuldeepy104593 weeks ago
vector<int> bfsOfGraph(int V, vector<int> adj[]) { // Code here vector<bool>visited(V,false); vector<int>ans; queue<int>q; q.push(0); visited[0]=true; while(!q.empty()){ int current= q.front(); ans.push_back(current); for(auto i: adj[current]){ if(!visited[i]){ q.push(i); visited[i]=true; } } q.pop(); } return ans; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 621,
"s": 238,
"text": "Given a directed graph. The task is to do Breadth First Traversal of this graph starting from 0.\nNote: One can move from node u to node v only if there's an edge from u to v and find the BFS traversal of the graph starting from the 0th vertex, from left to right according to the graph. Also, you should only take nodes directly or indirectly connected from Node 0 in consideration."
},
{
"code": null,
"e": 633,
"s": 621,
"text": "\nExample 1:"
},
{
"code": null,
"e": 821,
"s": 633,
"text": "Input:\n\nOutput: 0 1 2 3 4\nExplanation: \n0 is connected to 1 , 2 , 3.\n2 is connected to 4.\nso starting from 0, it will go to 1 then 2\nthen 3.After this 2 to 4, thus bfs will be\n0 1 2 3 4.\n"
},
{
"code": null,
"e": 832,
"s": 821,
"text": "Example 2:"
},
{
"code": null,
"e": 966,
"s": 832,
"text": "Input:\n\nOutput: 0 1 2\nExplanation:\n0 is connected to 1 , 2.\nso starting from 0, it will go to 1 then 2,\nthus bfs will be 0 1 2 3 4. \n"
},
{
"code": null,
"e": 1285,
"s": 966,
"text": "\nYour task:\nYou don’t need to read input or print anything. Your task is to complete the function bfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a list containing the BFS traversal of the graph starting from the 0th vertex from left to right."
},
{
"code": null,
"e": 1352,
"s": 1285,
"text": "\nExpected Time Complexity: O(V + E)\nExpected Auxiliary Space: O(V)"
},
{
"code": null,
"e": 1381,
"s": 1352,
"text": "\nConstraints:\n1 ≤ V, E ≤ 104"
},
{
"code": null,
"e": 1383,
"s": 1381,
"text": "0"
},
{
"code": null,
"e": 1411,
"s": 1383,
"text": "thakuraditya62116 hours ago"
},
{
"code": null,
"e": 2039,
"s": 1411,
"text": "public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n // Code here\n ArrayList<Integer> ans = new ArrayList<>();\n boolean []visited = new boolean[V];\n \n ArrayDeque<Integer> queue = new ArrayDeque<>();\n queue.add(0);\n \n while(!queue.isEmpty()){\n int rem = queue.remove();\n ans.add(rem);\n \n for(int e : adj.get(rem)){\n if(visited[e] == false){\n visited[e] = true;\n queue.add(e);\n }\n }\n }\n \n return ans;"
},
{
"code": null,
"e": 2041,
"s": 2039,
"text": "0"
},
{
"code": null,
"e": 2062,
"s": 2041,
"text": "mankesh0163 days ago"
},
{
"code": null,
"e": 2644,
"s": 2062,
"text": " vector<int> bfsOfGraph(int V, vector<int> adj[]) {\n // Code here\n vector<int> ans;\n int visited[V]={0};\n queue<int> q;\n \n q.push(0);\n visited[0]=true;\n \n while(!q.empty()){\n int n=q.front();\n q.pop();\n ans.push_back(n);\n vector<int> :: iterator it;\n \n for(it=adj[n].begin(); it!=adj[n].end(); it++){\n if(!visited[*it]){\n visited[*it]=true;\n q.push(*it);\n }\n }\n }\n \n return ans;\n }"
},
{
"code": null,
"e": 2647,
"s": 2644,
"text": "-1"
},
{
"code": null,
"e": 2668,
"s": 2647,
"text": "harshscode6 days ago"
},
{
"code": null,
"e": 2684,
"s": 2668,
"text": "o(v+e) and o(v)"
},
{
"code": null,
"e": 3245,
"s": 2684,
"text": "void bfs(int src,vector<int> &v1,vector<int> adj[],int v) { queue<int> q; vector<int> vis(v+1); q.push(0); while(!q.empty()) { int node=q.front(); q.pop(); v1.push_back(node); for(auto x:adj[node]) { if(!vis[x]) { q.push(x); vis[x]=1; } } } } vector<int> bfsOfGraph(int v, vector<int> adj[]) { vector<int> v1; bfs(0,v1,adj,v); return v1; }"
},
{
"code": null,
"e": 3247,
"s": 3245,
"text": "0"
},
{
"code": null,
"e": 3271,
"s": 3247,
"text": "jainmuskan5651 week ago"
},
{
"code": null,
"e": 3865,
"s": 3271,
"text": " vector<int> bfsOfGraph(int V, vector<int> adj[]) { // we are going to use queue and visited array queue<int> q; vector<int>v; bool visited[V]={0}; q.push(0); visited[0]=true; while(!q.empty()){ int temp= q.front(); q.pop(); v.push_back(temp); // check the adjacency list for that node for(auto neighbor: adj[temp]){ if(!visited[neighbor]){ q.push(neighbor); visited[neighbor]=true; } } } return v; }"
},
{
"code": null,
"e": 3868,
"s": 3865,
"text": "+1"
},
{
"code": null,
"e": 3888,
"s": 3868,
"text": "aryany8711 week ago"
},
{
"code": null,
"e": 4667,
"s": 3888,
"text": "vector<int> bfsOfGraph(int n, vector<int> adj[]) { //TC-O(V+E), AS-O(V) - queue and visited array are used bool visited[n] = {0}; vector<int>v; //to store the result queue<int>q; //source is 0 q.push(0); visited[0]=true; while(!q.empty()){ //pop the front node int currNode=q.front(); q.pop(); //push the current node in the result vector v.push_back(currNode); //now we will visit all the neighbours of the current node for(auto neighbour : adj[currNode]){ if(!visited[neighbour]){ q.push(neighbour); visited[neighbour]=true; } } } return v; }"
},
{
"code": null,
"e": 4670,
"s": 4667,
"text": "+1"
},
{
"code": null,
"e": 4697,
"s": 4670,
"text": "subhankar3184422 weeks ago"
},
{
"code": null,
"e": 4712,
"s": 4697,
"text": "JAVA 0.53/6.06"
},
{
"code": null,
"e": 5191,
"s": 4714,
"text": "ArrayList<Integer> list = new ArrayList<>(); Queue<Integer> q = new ArrayDeque<>(); boolean []vis = new boolean[V]; vis[0] = true; q.add(0); while(!q.isEmpty()){ int c = q.poll(); list.add(c); for(int i=0; i<adj.get(c).size(); i++){ int t = adj.get(c).get(i); if(!vis[t]){ vis[t] = true; q.add(t); } } } return list;"
},
{
"code": null,
"e": 5193,
"s": 5191,
"text": "0"
},
{
"code": null,
"e": 5211,
"s": 5193,
"text": "lilith2 weeks ago"
},
{
"code": null,
"e": 5225,
"s": 5211,
"text": "Java Soln Bfs"
},
{
"code": null,
"e": 5939,
"s": 5225,
"text": "class Solution {\n // Function to return Breadth First Traversal of given graph.\n public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n // Code here\n ArrayList<Integer> res = new ArrayList<>();\n \n boolean[] visited = new boolean[V];\n \n ArrayDeque<Integer> q = new ArrayDeque<>();\n q.add(0);\n \n while(!q.isEmpty()) {\n int rem = q.remove();\n res.add(rem);\n \n for(int e : adj.get(rem)) {\n if(visited[e] != true) {\n visited[e] = true;\n q.add(e);\n }\n }\n }\n \n return res;\n }\n}"
},
{
"code": null,
"e": 5942,
"s": 5939,
"text": "+2"
},
{
"code": null,
"e": 5967,
"s": 5942,
"text": "aryanvikas0072 weeks ago"
},
{
"code": null,
"e": 5995,
"s": 5967,
"text": "For only first component : "
},
{
"code": null,
"e": 6064,
"s": 5997,
"text": "Just use break after 1st iteration and you will get 1st component;"
},
{
"code": null,
"e": 7023,
"s": 6064,
"text": "class Solution {\n // Function to return Breadth First Traversal of given graph.\n public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n // Code here\n ArrayList<Integer> bfs = new ArrayList<>();\n boolean[] vis = new boolean[V];\n \n for(int i=0; i<V; i++){ \n if(vis[i]==false){\n Queue<Integer> q = new LinkedList<>();\n q.add(i);\n vis[i] = true;\n \n while(!q.isEmpty()){\n Integer node = q.poll();\n bfs.add(node);\n for(Integer it : adj.get(node)){\n if(vis[it]==false){\n vis[it]=true;\n q.add(it);\n \n }\n }\n } \n }\n break;\n \n }\n return bfs;\n }\n}"
},
{
"code": null,
"e": 7026,
"s": 7023,
"text": "+1"
},
{
"code": null,
"e": 7059,
"s": 7026,
"text": "deeptimayeemaharana062 weeks ago"
},
{
"code": null,
"e": 7100,
"s": 7059,
"text": "code editor not working for this problem"
},
{
"code": null,
"e": 7115,
"s": 7100,
"text": "pls check @gfg"
},
{
"code": null,
"e": 7118,
"s": 7115,
"text": "+4"
},
{
"code": null,
"e": 7143,
"s": 7118,
"text": "kuldeepy104593 weeks ago"
},
{
"code": null,
"e": 7650,
"s": 7143,
"text": " vector<int> bfsOfGraph(int V, vector<int> adj[]) { // Code here vector<bool>visited(V,false); vector<int>ans; queue<int>q; q.push(0); visited[0]=true; while(!q.empty()){ int current= q.front(); ans.push_back(current); for(auto i: adj[current]){ if(!visited[i]){ q.push(i); visited[i]=true; } } q.pop(); } return ans; }"
},
{
"code": null,
"e": 7796,
"s": 7650,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7832,
"s": 7796,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7842,
"s": 7832,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7852,
"s": 7842,
"text": "\nContest\n"
},
{
"code": null,
"e": 7915,
"s": 7852,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8063,
"s": 7915,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8271,
"s": 8063,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8377,
"s": 8271,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Contained Interval in C++
|
Suppose we have a two-dimensional list of intervals where each interval has two values [start, end]. We have to find whether there's an interval which contains another interval.
So, if the input is like [[2,4],[5,11],[5,9],[10,10]], then the output will be true as [5,11] is containing [5,9].
To solve this, we will follow these steps −
sort the array v
sort the array v
Define one 2D array ret
Define one 2D array ret
for each interval it in v −if ret is empty, then −insert it at the end of retotherwise when last element of ret >= it[0], then −return trueOtherwiseinsert it at the end of ret
for each interval it in v −
if ret is empty, then −insert it at the end of ret
if ret is empty, then −
insert it at the end of ret
insert it at the end of ret
otherwise when last element of ret >= it[0], then −return true
otherwise when last element of ret >= it[0], then −
return true
return true
Otherwiseinsert it at the end of ret
Otherwise
insert it at the end of ret
insert it at the end of ret
return false
return false
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool static cmp(vector<int> &a, vector<int> &b) {
return a[1] == b[1] ? a[0] > b[0] : a[1] < b[1];
}
bool solve(vector<vector<int>> &v) {
sort(v.begin(), v.end(), cmp);
vector<vector<int>> ret;
for (auto &it : v) {
if (ret.empty())
ret.push_back(it);
else if (ret.back()[0] >= it[0])
return true;
else
ret.push_back(it);
}
return false;
}
};
main() {
Solution ob;
vector<vector<int>> v = {{2,4},{5,11},{5,9},{10,10}};
cout << (ob.solve(v));
}
{{2,4},{5,11},{5,9},{10,10}}
1
|
[
{
"code": null,
"e": 1240,
"s": 1062,
"text": "Suppose we have a two-dimensional list of intervals where each interval has two values [start, end]. We have to find whether there's an interval which contains another interval."
},
{
"code": null,
"e": 1355,
"s": 1240,
"text": "So, if the input is like [[2,4],[5,11],[5,9],[10,10]], then the output will be true as [5,11] is containing [5,9]."
},
{
"code": null,
"e": 1399,
"s": 1355,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1416,
"s": 1399,
"text": "sort the array v"
},
{
"code": null,
"e": 1433,
"s": 1416,
"text": "sort the array v"
},
{
"code": null,
"e": 1457,
"s": 1433,
"text": "Define one 2D array ret"
},
{
"code": null,
"e": 1481,
"s": 1457,
"text": "Define one 2D array ret"
},
{
"code": null,
"e": 1657,
"s": 1481,
"text": "for each interval it in v −if ret is empty, then −insert it at the end of retotherwise when last element of ret >= it[0], then −return trueOtherwiseinsert it at the end of ret"
},
{
"code": null,
"e": 1685,
"s": 1657,
"text": "for each interval it in v −"
},
{
"code": null,
"e": 1736,
"s": 1685,
"text": "if ret is empty, then −insert it at the end of ret"
},
{
"code": null,
"e": 1760,
"s": 1736,
"text": "if ret is empty, then −"
},
{
"code": null,
"e": 1788,
"s": 1760,
"text": "insert it at the end of ret"
},
{
"code": null,
"e": 1816,
"s": 1788,
"text": "insert it at the end of ret"
},
{
"code": null,
"e": 1879,
"s": 1816,
"text": "otherwise when last element of ret >= it[0], then −return true"
},
{
"code": null,
"e": 1931,
"s": 1879,
"text": "otherwise when last element of ret >= it[0], then −"
},
{
"code": null,
"e": 1943,
"s": 1931,
"text": "return true"
},
{
"code": null,
"e": 1955,
"s": 1943,
"text": "return true"
},
{
"code": null,
"e": 1992,
"s": 1955,
"text": "Otherwiseinsert it at the end of ret"
},
{
"code": null,
"e": 2002,
"s": 1992,
"text": "Otherwise"
},
{
"code": null,
"e": 2030,
"s": 2002,
"text": "insert it at the end of ret"
},
{
"code": null,
"e": 2058,
"s": 2030,
"text": "insert it at the end of ret"
},
{
"code": null,
"e": 2071,
"s": 2058,
"text": "return false"
},
{
"code": null,
"e": 2084,
"s": 2071,
"text": "return false"
},
{
"code": null,
"e": 2154,
"s": 2084,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2165,
"s": 2154,
"text": " Live Demo"
},
{
"code": null,
"e": 2793,
"s": 2165,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n bool static cmp(vector<int> &a, vector<int> &b) {\n return a[1] == b[1] ? a[0] > b[0] : a[1] < b[1];\n }\n bool solve(vector<vector<int>> &v) {\n sort(v.begin(), v.end(), cmp);\n vector<vector<int>> ret;\n for (auto &it : v) {\n if (ret.empty())\n ret.push_back(it);\n else if (ret.back()[0] >= it[0])\n return true;\n else\n ret.push_back(it);\n }\n return false;\n }\n};\nmain() {\n Solution ob;\n vector<vector<int>> v = {{2,4},{5,11},{5,9},{10,10}};\n cout << (ob.solve(v));\n}"
},
{
"code": null,
"e": 2822,
"s": 2793,
"text": "{{2,4},{5,11},{5,9},{10,10}}"
},
{
"code": null,
"e": 2824,
"s": 2822,
"text": "1"
}
] |
How to check whether a particular key exist in javascript object or array?
|
There are different ways to check for existence of an object/key in an array and an object. Let us look at the Object case first.
To look if a key exists in a object, we need to use the in operator.
let obj = {
name: "John",
age: 22
}
console.log('name' in obj);
console.log('address' in obj);
true
false
Note −The in operator returns true if the specified property is in the specified object or its prototype chain.
For checking if an object exists in an array, we need to use the indexOf method on the array. If the object is not found, -1 is returned, else its index is returned.
let arr = ["test", 1, 2, "hello", 23.5];
console.log(arr.indexOf({}))
console.log(arr.indexOf("hello"))
console.log(arr.indexOf(23.5))
-1
3
4
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "There are different ways to check for existence of an object/key in an array and an object. Let us look at the Object case first."
},
{
"code": null,
"e": 1261,
"s": 1192,
"text": "To look if a key exists in a object, we need to use the in operator."
},
{
"code": null,
"e": 1362,
"s": 1261,
"text": "let obj = {\n name: \"John\",\n age: 22\n}\nconsole.log('name' in obj);\nconsole.log('address' in obj);"
},
{
"code": null,
"e": 1373,
"s": 1362,
"text": "true\nfalse"
},
{
"code": null,
"e": 1485,
"s": 1373,
"text": "Note −The in operator returns true if the specified property is in the specified object or its prototype chain."
},
{
"code": null,
"e": 1651,
"s": 1485,
"text": "For checking if an object exists in an array, we need to use the indexOf method on the array. If the object is not found, -1 is returned, else its index is returned."
},
{
"code": null,
"e": 1786,
"s": 1651,
"text": "let arr = [\"test\", 1, 2, \"hello\", 23.5];\nconsole.log(arr.indexOf({}))\nconsole.log(arr.indexOf(\"hello\"))\nconsole.log(arr.indexOf(23.5))"
},
{
"code": null,
"e": 1793,
"s": 1786,
"text": "-1\n3\n4"
}
] |
ES6 | Import and Export - GeeksforGeeks
|
28 Feb, 2020
The ES6 is a JavaScript standard. With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.
Export: You can export a variable using the export keyword in front of that variable declaration. You can also export a function and a class by doing the same.
Syntax for variable:export let variable_name;
export let variable_name;
Syntax for function:export function function_name() {
// Statements
}
export function function_name() {
// Statements
}
Syntax for class:export class Class_Name {
constructor() {
// Statements
}
}
export class Class_Name {
constructor() {
// Statements
}
}
Example 1: Create a file named export.js and write the below code in that file.export let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log("Hello World!");} export class Greeting { constructor(name) { this.greeting = "Hello, " + name; }}
export let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log("Hello World!");} export class Greeting { constructor(name) { this.greeting = "Hello, " + name; }}
Example 2: In this example, we export by specifying the members of the module at the end of the file. We can also use alias while exporting using the as keyword.let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log("Hello World!");} class Greeting { constructor(name) { this.greeting = "Hello, " + name; }} export { num_set, Greeting as Greet };Note: A default export should be specified here.
let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log("Hello World!");} class Greeting { constructor(name) { this.greeting = "Hello, " + name; }} export { num_set, Greeting as Greet };
Note: A default export should be specified here.
Import: You can import a variable using import keyword. You can specify one of all the members that you want to import from a JavaScript file.
Syntax:import member_to_import from “path_to_js_file”;// You can also use an alias while importing a member.
import Greeting as Greet from "./export.js";// If you want to import all the members but don’t
// want to Specify them all then you can do that using
// a ' * ' star symbol.
import * as exp from "./export.js";
import member_to_import from “path_to_js_file”;
// You can also use an alias while importing a member.
import Greeting as Greet from "./export.js";
// If you want to import all the members but don’t
// want to Specify them all then you can do that using
// a ' * ' star symbol.
import * as exp from "./export.js";
Example 1: Create a file named import.html and write the below code in that file.<!DOCTYPE html><html lang="en"> <head> <title>Import in ES6</title> </head> <body> <script type="module"> // Default member first import hello, { num_set, Greeting } from "./export.js"; console.log(num_set); hello(); let g = new Greeting("Aakash"); console.log(g.greeting); </script> </body></html>
<!DOCTYPE html><html lang="en"> <head> <title>Import in ES6</title> </head> <body> <script type="module"> // Default member first import hello, { num_set, Greeting } from "./export.js"; console.log(num_set); hello(); let g = new Greeting("Aakash"); console.log(g.greeting); </script> </body></html>
Example 2:<!DOCTYPE html><html lang="en"> <head> <title>Import in ES6</title> </head> <body> <script type="module"> import * as exp from "./export.js"; // Use dot notation to access members console.log(exp.num_set); exp.hello(); let g = new exp.Greeting("Aakash"); console.log(g.greeting); </script> </body></html>
<!DOCTYPE html><html lang="en"> <head> <title>Import in ES6</title> </head> <body> <script type="module"> import * as exp from "./export.js"; // Use dot notation to access members console.log(exp.num_set); exp.hello(); let g = new exp.Greeting("Aakash"); console.log(g.greeting); </script> </body></html>
Output: Output will be same, importing the same file.
Note: The default member should be imported first and then the none default members in curly brackets.
ES6
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24361,
"s": 24333,
"text": "\n28 Feb, 2020"
},
{
"code": null,
"e": 24712,
"s": 24361,
"text": "The ES6 is a JavaScript standard. With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module."
},
{
"code": null,
"e": 24872,
"s": 24712,
"text": "Export: You can export a variable using the export keyword in front of that variable declaration. You can also export a function and a class by doing the same."
},
{
"code": null,
"e": 24918,
"s": 24872,
"text": "Syntax for variable:export let variable_name;"
},
{
"code": null,
"e": 24944,
"s": 24918,
"text": "export let variable_name;"
},
{
"code": null,
"e": 25017,
"s": 24944,
"text": "Syntax for function:export function function_name() {\n // Statements\n}\n"
},
{
"code": null,
"e": 25070,
"s": 25017,
"text": "export function function_name() {\n // Statements\n}\n"
},
{
"code": null,
"e": 25156,
"s": 25070,
"text": "Syntax for class:export class Class_Name {\n constructor() {\n // Statements\n }\n}\n"
},
{
"code": null,
"e": 25225,
"s": 25156,
"text": "export class Class_Name {\n constructor() {\n // Statements\n }\n}\n"
},
{
"code": null,
"e": 25505,
"s": 25225,
"text": "Example 1: Create a file named export.js and write the below code in that file.export let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log(\"Hello World!\");} export class Greeting { constructor(name) { this.greeting = \"Hello, \" + name; }}"
},
{
"code": "export let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log(\"Hello World!\");} export class Greeting { constructor(name) { this.greeting = \"Hello, \" + name; }}",
"e": 25706,
"s": 25505,
"text": null
},
{
"code": null,
"e": 26142,
"s": 25706,
"text": "Example 2: In this example, we export by specifying the members of the module at the end of the file. We can also use alias while exporting using the as keyword.let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log(\"Hello World!\");} class Greeting { constructor(name) { this.greeting = \"Hello, \" + name; }} export { num_set, Greeting as Greet };Note: A default export should be specified here."
},
{
"code": "let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log(\"Hello World!\");} class Greeting { constructor(name) { this.greeting = \"Hello, \" + name; }} export { num_set, Greeting as Greet };",
"e": 26369,
"s": 26142,
"text": null
},
{
"code": null,
"e": 26418,
"s": 26369,
"text": "Note: A default export should be specified here."
},
{
"code": null,
"e": 26561,
"s": 26418,
"text": "Import: You can import a variable using import keyword. You can specify one of all the members that you want to import from a JavaScript file."
},
{
"code": null,
"e": 26880,
"s": 26561,
"text": "Syntax:import member_to_import from “path_to_js_file”;// You can also use an alias while importing a member.\nimport Greeting as Greet from \"./export.js\";// If you want to import all the members but don’t\n// want to Specify them all then you can do that using\n// a ' * ' star symbol.\nimport * as exp from \"./export.js\";"
},
{
"code": null,
"e": 26928,
"s": 26880,
"text": "import member_to_import from “path_to_js_file”;"
},
{
"code": null,
"e": 27028,
"s": 26928,
"text": "// You can also use an alias while importing a member.\nimport Greeting as Greet from \"./export.js\";"
},
{
"code": null,
"e": 27194,
"s": 27028,
"text": "// If you want to import all the members but don’t\n// want to Specify them all then you can do that using\n// a ' * ' star symbol.\nimport * as exp from \"./export.js\";"
},
{
"code": null,
"e": 27675,
"s": 27194,
"text": "Example 1: Create a file named import.html and write the below code in that file.<!DOCTYPE html><html lang=\"en\"> <head> <title>Import in ES6</title> </head> <body> <script type=\"module\"> // Default member first import hello, { num_set, Greeting } from \"./export.js\"; console.log(num_set); hello(); let g = new Greeting(\"Aakash\"); console.log(g.greeting); </script> </body></html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Import in ES6</title> </head> <body> <script type=\"module\"> // Default member first import hello, { num_set, Greeting } from \"./export.js\"; console.log(num_set); hello(); let g = new Greeting(\"Aakash\"); console.log(g.greeting); </script> </body></html>",
"e": 28075,
"s": 27675,
"text": null
},
{
"code": null,
"e": 28491,
"s": 28075,
"text": "Example 2:<!DOCTYPE html><html lang=\"en\"> <head> <title>Import in ES6</title> </head> <body> <script type=\"module\"> import * as exp from \"./export.js\"; // Use dot notation to access members console.log(exp.num_set); exp.hello(); let g = new exp.Greeting(\"Aakash\"); console.log(g.greeting); </script> </body></html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Import in ES6</title> </head> <body> <script type=\"module\"> import * as exp from \"./export.js\"; // Use dot notation to access members console.log(exp.num_set); exp.hello(); let g = new exp.Greeting(\"Aakash\"); console.log(g.greeting); </script> </body></html>",
"e": 28897,
"s": 28491,
"text": null
},
{
"code": null,
"e": 28951,
"s": 28897,
"text": "Output: Output will be same, importing the same file."
},
{
"code": null,
"e": 29054,
"s": 28951,
"text": "Note: The default member should be imported first and then the none default members in curly brackets."
},
{
"code": null,
"e": 29058,
"s": 29054,
"text": "ES6"
},
{
"code": null,
"e": 29065,
"s": 29058,
"text": "Picked"
},
{
"code": null,
"e": 29076,
"s": 29065,
"text": "JavaScript"
},
{
"code": null,
"e": 29093,
"s": 29076,
"text": "Web Technologies"
},
{
"code": null,
"e": 29191,
"s": 29093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29236,
"s": 29191,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29297,
"s": 29236,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29369,
"s": 29297,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29421,
"s": 29369,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29467,
"s": 29421,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29509,
"s": 29467,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29571,
"s": 29509,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29604,
"s": 29571,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29647,
"s": 29604,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Packing and Unpacking Arguments in Python
|
25 Jan, 2022
We use two operators * (for tuples) and ** (for dictionaries).
Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn’t work.
Python3
# A Python program to demonstrate need# of packing and unpacking # A sample function that takes 4 arguments# and prints them.def fun(a, b, c, d): print(a, b, c, d) # Driver Codemy_list = [1, 2, 3, 4] # This doesn't workfun(my_list)
Output :
TypeError: fun() takes exactly 4 arguments (1 given)
Unpacking We can use * to unpack the list so that all elements of it can be passed as different parameters.
Python3
# A sample function that takes 4 arguments# and prints the,def fun(a, b, c, d): print(a, b, c, d) # Driver Codemy_list = [1, 2, 3, 4] # Unpacking list into four argumentsfun(*my_list)
Output :
(1, 2, 3, 4)
We need to keep in mind that the no. of arguments must be the same as the length of the list that we are unpacking for the arguments.
Python3
# Error when len(args) != no of actual arguments# required by the function args = [0, 1, 4, 9] def func(a, b, c): return a + b + c # calling function with unpacking argsfunc(*args)
Output:
Traceback (most recent call last):
File "/home/592a8d2a568a0c12061950aa99d6dec3.py", line 10, in <module>
func(*args)
TypeError: func() takes 3 positional arguments but 4 were given
As another example, consider the built-in range() function that expects separate start and stops arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:
Python3
>>>>>> range(3, 6) # normal call with separate arguments[3, 4, 5]>>> args = [3, 6]>>> range(*args) # call with arguments unpacked from a list[3, 4, 5]
Packing When we don’t know how many arguments need to be passed to a python function, we can use Packing to pack all arguments in a tuple.
Python3
# A Python program to demonstrate use# of packing # This function uses packing to sum# unknown number of argumentsdef mySum(*args): return sum(args) # Driver codeprint(mySum(1, 2, 3, 4, 5))print(mySum(10, 20))
Output:
15
30
The above function mySum() does ‘packing’ to pack all the arguments that this method call receives into one single variable. Once we have this ‘packed’ variable, we can do things with it that we would with a normal tuple. args[0] and args[1] would give you the first and second argument, respectively. Since our tuples are immutable, you can convert the args tuple to a list so you can also modify, delete, and re-arrange items in i.
Packing and Unpacking Below is an example that shows both packing and unpacking.
Python3
# A Python program to demonstrate both packing and# unpacking. # A sample python function that takes three arguments# and prints themdef fun1(a, b, c): print(a, b, c) # Another sample function.# This is an example of PACKING. All arguments passed# to fun2 are packed into tuple *args.def fun2(*args): # Convert args tuple to a list so we can modify it args = list(args) # Modifying args args[0] = 'Geeksforgeeks' args[1] = 'awesome' # UNPACKING args and calling fun1() fun1(*args) # Driver codefun2('Hello', 'beautiful', 'world!')
Output:
(Geeksforgeeks, awesome, world!)
** is used for dictionaries
Python3
# A sample program to demonstrate unpacking of# dictionary items using **def fun(a, b, c): print(a, b, c) # A call with unpacking of dictionaryd = {'a':2, 'b':4, 'c':10}fun(**d)
Output:
2 4 10
Here ** unpacked the dictionary used with it, and passed the items in the dictionary as keyword arguments to the function. So writing “fun(1, **d)” was equivalent to writing “fun(1, b=4, c=10)”.
Python3
# A Python program to demonstrate packing of# dictionary items using **def fun(**kwargs): # kwargs is a dict print(type(kwargs)) # Printing dictionary items for key in kwargs: print("%s = %s" % (key, kwargs[key])) # Driver codefun(name="geeks", ID="101", language="Python")
<class 'dict'>
name = geeks
ID = 101
language = Python
Applications and Important Points
Used in socket programming to send a vast number of requests to a server.Used in the Django framework to send variable arguments to view functions.There are wrapper functions that require us to pass in variable arguments.Modification of arguments becomes easy, but at the same time validation is not proper, so they must be used with care.
Used in socket programming to send a vast number of requests to a server.
Used in the Django framework to send variable arguments to view functions.
There are wrapper functions that require us to pass in variable arguments.
Modification of arguments becomes easy, but at the same time validation is not proper, so they must be used with care.
Reference : http://hangar.runway7.net/python/packing-unpacking-argumentsThis article is contributed by Shwetanshu Rohatgi. 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
Jablonski
ashish2021
varshagumber28
amartyaghoshgfg
python-dict
python-tuple
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "We use two operators * (for tuples) and ** (for dictionaries). "
},
{
"code": null,
"e": 390,
"s": 118,
"text": "Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn’t work. "
},
{
"code": null,
"e": 398,
"s": 390,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate need# of packing and unpacking # A sample function that takes 4 arguments# and prints them.def fun(a, b, c, d): print(a, b, c, d) # Driver Codemy_list = [1, 2, 3, 4] # This doesn't workfun(my_list)",
"e": 633,
"s": 398,
"text": null
},
{
"code": null,
"e": 643,
"s": 633,
"text": "Output : "
},
{
"code": null,
"e": 696,
"s": 643,
"text": "TypeError: fun() takes exactly 4 arguments (1 given)"
},
{
"code": null,
"e": 807,
"s": 696,
"text": " Unpacking We can use * to unpack the list so that all elements of it can be passed as different parameters. "
},
{
"code": null,
"e": 815,
"s": 807,
"text": "Python3"
},
{
"code": "# A sample function that takes 4 arguments# and prints the,def fun(a, b, c, d): print(a, b, c, d) # Driver Codemy_list = [1, 2, 3, 4] # Unpacking list into four argumentsfun(*my_list)",
"e": 1002,
"s": 815,
"text": null
},
{
"code": null,
"e": 1012,
"s": 1002,
"text": "Output : "
},
{
"code": null,
"e": 1025,
"s": 1012,
"text": "(1, 2, 3, 4)"
},
{
"code": null,
"e": 1159,
"s": 1025,
"text": "We need to keep in mind that the no. of arguments must be the same as the length of the list that we are unpacking for the arguments."
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Python3"
},
{
"code": "# Error when len(args) != no of actual arguments# required by the function args = [0, 1, 4, 9] def func(a, b, c): return a + b + c # calling function with unpacking argsfunc(*args)",
"e": 1353,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Output:"
},
{
"code": null,
"e": 1549,
"s": 1361,
"text": "Traceback (most recent call last):\n File \"/home/592a8d2a568a0c12061950aa99d6dec3.py\", line 10, in <module>\n func(*args)\nTypeError: func() takes 3 positional arguments but 4 were given"
},
{
"code": null,
"e": 1788,
"s": 1549,
"text": "As another example, consider the built-in range() function that expects separate start and stops arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: "
},
{
"code": null,
"e": 1796,
"s": 1788,
"text": "Python3"
},
{
"code": ">>>>>> range(3, 6) # normal call with separate arguments[3, 4, 5]>>> args = [3, 6]>>> range(*args) # call with arguments unpacked from a list[3, 4, 5]",
"e": 1949,
"s": 1796,
"text": null
},
{
"code": null,
"e": 2090,
"s": 1949,
"text": "Packing When we don’t know how many arguments need to be passed to a python function, we can use Packing to pack all arguments in a tuple. "
},
{
"code": null,
"e": 2098,
"s": 2090,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate use# of packing # This function uses packing to sum# unknown number of argumentsdef mySum(*args): return sum(args) # Driver codeprint(mySum(1, 2, 3, 4, 5))print(mySum(10, 20))",
"e": 2311,
"s": 2098,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2311,
"text": "Output: "
},
{
"code": null,
"e": 2327,
"s": 2321,
"text": "15\n30"
},
{
"code": null,
"e": 2762,
"s": 2327,
"text": "The above function mySum() does ‘packing’ to pack all the arguments that this method call receives into one single variable. Once we have this ‘packed’ variable, we can do things with it that we would with a normal tuple. args[0] and args[1] would give you the first and second argument, respectively. Since our tuples are immutable, you can convert the args tuple to a list so you can also modify, delete, and re-arrange items in i. "
},
{
"code": null,
"e": 2845,
"s": 2762,
"text": "Packing and Unpacking Below is an example that shows both packing and unpacking. "
},
{
"code": null,
"e": 2853,
"s": 2845,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate both packing and# unpacking. # A sample python function that takes three arguments# and prints themdef fun1(a, b, c): print(a, b, c) # Another sample function.# This is an example of PACKING. All arguments passed# to fun2 are packed into tuple *args.def fun2(*args): # Convert args tuple to a list so we can modify it args = list(args) # Modifying args args[0] = 'Geeksforgeeks' args[1] = 'awesome' # UNPACKING args and calling fun1() fun1(*args) # Driver codefun2('Hello', 'beautiful', 'world!')",
"e": 3411,
"s": 2853,
"text": null
},
{
"code": null,
"e": 3421,
"s": 3411,
"text": "Output: "
},
{
"code": null,
"e": 3454,
"s": 3421,
"text": "(Geeksforgeeks, awesome, world!)"
},
{
"code": null,
"e": 3484,
"s": 3454,
"text": "** is used for dictionaries "
},
{
"code": null,
"e": 3492,
"s": 3484,
"text": "Python3"
},
{
"code": "# A sample program to demonstrate unpacking of# dictionary items using **def fun(a, b, c): print(a, b, c) # A call with unpacking of dictionaryd = {'a':2, 'b':4, 'c':10}fun(**d)",
"e": 3673,
"s": 3492,
"text": null
},
{
"code": null,
"e": 3682,
"s": 3673,
"text": "Output: "
},
{
"code": null,
"e": 3689,
"s": 3682,
"text": "2 4 10"
},
{
"code": null,
"e": 3885,
"s": 3689,
"text": "Here ** unpacked the dictionary used with it, and passed the items in the dictionary as keyword arguments to the function. So writing “fun(1, **d)” was equivalent to writing “fun(1, b=4, c=10)”. "
},
{
"code": null,
"e": 3893,
"s": 3885,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate packing of# dictionary items using **def fun(**kwargs): # kwargs is a dict print(type(kwargs)) # Printing dictionary items for key in kwargs: print(\"%s = %s\" % (key, kwargs[key])) # Driver codefun(name=\"geeks\", ID=\"101\", language=\"Python\")",
"e": 4188,
"s": 3893,
"text": null
},
{
"code": null,
"e": 4244,
"s": 4188,
"text": "<class 'dict'>\nname = geeks\nID = 101\nlanguage = Python\n"
},
{
"code": null,
"e": 4279,
"s": 4244,
"text": "Applications and Important Points "
},
{
"code": null,
"e": 4619,
"s": 4279,
"text": "Used in socket programming to send a vast number of requests to a server.Used in the Django framework to send variable arguments to view functions.There are wrapper functions that require us to pass in variable arguments.Modification of arguments becomes easy, but at the same time validation is not proper, so they must be used with care."
},
{
"code": null,
"e": 4693,
"s": 4619,
"text": "Used in socket programming to send a vast number of requests to a server."
},
{
"code": null,
"e": 4768,
"s": 4693,
"text": "Used in the Django framework to send variable arguments to view functions."
},
{
"code": null,
"e": 4843,
"s": 4768,
"text": "There are wrapper functions that require us to pass in variable arguments."
},
{
"code": null,
"e": 4962,
"s": 4843,
"text": "Modification of arguments becomes easy, but at the same time validation is not proper, so they must be used with care."
},
{
"code": null,
"e": 5460,
"s": 4962,
"text": "Reference : http://hangar.runway7.net/python/packing-unpacking-argumentsThis article is contributed by Shwetanshu Rohatgi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 5470,
"s": 5460,
"text": "Jablonski"
},
{
"code": null,
"e": 5481,
"s": 5470,
"text": "ashish2021"
},
{
"code": null,
"e": 5496,
"s": 5481,
"text": "varshagumber28"
},
{
"code": null,
"e": 5512,
"s": 5496,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 5524,
"s": 5512,
"text": "python-dict"
},
{
"code": null,
"e": 5537,
"s": 5524,
"text": "python-tuple"
},
{
"code": null,
"e": 5544,
"s": 5537,
"text": "Python"
},
{
"code": null,
"e": 5556,
"s": 5544,
"text": "python-dict"
}
] |
Mongoose find() Function
|
10 Feb, 2021
The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).
Installation of mongoose module:
You can visit the link to Install mongoose module https://www.npmjs.com/package/mongoose. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module https://www.npmjs.com/package/mongoose. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Only one parameter [query/condition]// Find all documents that matches the// condition name='Punit'User.find({ name: 'Punit'}, function (err, docs) { if (err){ console.log(err); } else{ console.log("First function call : ", docs); }}); // Only Two parameters [condition, query projection]// Here age:0 means don't include age field in result User.find({ name: 'Punit'}, {age:0}, function (err, docs) { if (err){ console.log(err); } else{ console.log("Second function call : ", docs); }}); // All three parameter [condition, query projection,// general query options]// Fetch first two records whose age >= 10 // Second parameter is null i.e. no projections// Third parameter is limit:2 i.e. fetch// only first 2 recordsUser.find({ age: {$gte:10}}, null, {limit:2}, function (err, docs) { if (err){ console.log(err); } else{ console.log("Third function call : ", docs); }});
Steps to run the program:
The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the find() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js
The project structure will look like this:
Make sure you have install mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the find() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
So this is how you can use the mongoose find() function in Node.js and MongoDB.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
MongoDB - Check the existence of the fields in the specified collection
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Feb, 2021"
},
{
"code": null,
"e": 367,
"s": 53,
"text": "The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc)."
},
{
"code": null,
"e": 400,
"s": 367,
"text": "Installation of mongoose module:"
},
{
"code": null,
"e": 835,
"s": 400,
"text": "You can visit the link to Install mongoose module https://www.npmjs.com/package/mongoose. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 997,
"s": 835,
"text": "You can visit the link to Install mongoose module https://www.npmjs.com/package/mongoose. You can install this package by using this command.npm install mongoose"
},
{
"code": null,
"e": 1018,
"s": 997,
"text": "npm install mongoose"
},
{
"code": null,
"e": 1145,
"s": 1018,
"text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose"
},
{
"code": null,
"e": 1166,
"s": 1145,
"text": "npm version mongoose"
},
{
"code": null,
"e": 1314,
"s": 1166,
"text": "After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1328,
"s": 1314,
"text": "node index.js"
},
{
"code": null,
"e": 1347,
"s": 1328,
"text": "Filename: index.js"
},
{
"code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Only one parameter [query/condition]// Find all documents that matches the// condition name='Punit'User.find({ name: 'Punit'}, function (err, docs) { if (err){ console.log(err); } else{ console.log(\"First function call : \", docs); }}); // Only Two parameters [condition, query projection]// Here age:0 means don't include age field in result User.find({ name: 'Punit'}, {age:0}, function (err, docs) { if (err){ console.log(err); } else{ console.log(\"Second function call : \", docs); }}); // All three parameter [condition, query projection,// general query options]// Fetch first two records whose age >= 10 // Second parameter is null i.e. no projections// Third parameter is limit:2 i.e. fetch// only first 2 recordsUser.find({ age: {$gte:10}}, null, {limit:2}, function (err, docs) { if (err){ console.log(err); } else{ console.log(\"Third function call : \", docs); }});",
"e": 2617,
"s": 1347,
"text": null
},
{
"code": null,
"e": 2643,
"s": 2617,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 3012,
"s": 2643,
"text": "The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the find() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 3055,
"s": 3012,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 3143,
"s": 3055,
"text": "Make sure you have install mongoose module using following command:npm install mongoose"
},
{
"code": null,
"e": 3164,
"s": 3143,
"text": "npm install mongoose"
},
{
"code": null,
"e": 3353,
"s": 3164,
"text": "Below is the sample data in the database before the find() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:"
},
{
"code": null,
"e": 3405,
"s": 3353,
"text": "Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 3419,
"s": 3405,
"text": "node index.js"
},
{
"code": null,
"e": 3499,
"s": 3419,
"text": "So this is how you can use the mongoose find() function in Node.js and MongoDB."
},
{
"code": null,
"e": 3508,
"s": 3499,
"text": "Mongoose"
},
{
"code": null,
"e": 3516,
"s": 3508,
"text": "MongoDB"
},
{
"code": null,
"e": 3524,
"s": 3516,
"text": "Node.js"
},
{
"code": null,
"e": 3541,
"s": 3524,
"text": "Web Technologies"
},
{
"code": null,
"e": 3639,
"s": 3541,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3678,
"s": 3639,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 3705,
"s": 3678,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 3743,
"s": 3705,
"text": "MongoDB - db.collection.Find() Method"
},
{
"code": null,
"e": 3766,
"s": 3743,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 3838,
"s": 3766,
"text": "MongoDB - Check the existence of the fields in the specified collection"
},
{
"code": null,
"e": 3886,
"s": 3838,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3919,
"s": 3886,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3952,
"s": 3919,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3982,
"s": 3952,
"text": "Node.js fs.writeFile() Method"
}
] |
Java System.nanoTime() vs System.currentTimeMillis
|
12 Apr, 2018
Java provides two methods to time operations, System.nanoTime() and System.currentTimeMillis(). But which one should be used in which condition? And which is more efficient?
From the first look it might seem that nanoTime() should be used because it gives more precise value of time (in nano seconds, compared to milli seconds that the other method returns). But is it always efficient on the CPU to use nanoTime? Let us look at pros and cons of using both the methods:
System.currentTimeMillis()
public static long currentTimeMillis()
// Returns the current time in milliseconds.
Pros:
It is thread safe. Thread safety means that if this method is called between two or more different threads, it will not return erroneous results.Always returns the absolute time elapsed since the epoch (number of millis since 1 Jan 1970 00:00).Consumes lesser clock cycles to execute (around 5-6 cpu clocks).Gives more accurate time, since the point of reference (the epoch) is fixed.
It is thread safe. Thread safety means that if this method is called between two or more different threads, it will not return erroneous results.
Always returns the absolute time elapsed since the epoch (number of millis since 1 Jan 1970 00:00).
Consumes lesser clock cycles to execute (around 5-6 cpu clocks).
Gives more accurate time, since the point of reference (the epoch) is fixed.
Cons:
Less precise. The result is somewhere between 1/1000th to 15/1000th of a second. On some machines, the resolution is even less than 50ms and can go down to upto 10ms only.It may give wrong results if the user changes the system time, hits a leap second or there are changes in NTP sync.
Less precise. The result is somewhere between 1/1000th to 15/1000th of a second. On some machines, the resolution is even less than 50ms and can go down to upto 10ms only.
It may give wrong results if the user changes the system time, hits a leap second or there are changes in NTP sync.
System.nanoTime()
public static long nanoTime()
// Returns the current value of the running JVM's high-resolution
// time source, in nanoseconds.
Pros:
Highly precise. The time returned is around 1/1000000th of a second.The resolution is much higher than currentTimeMillis().
Highly precise. The time returned is around 1/1000000th of a second.
The resolution is much higher than currentTimeMillis().
Cons:
The result reflected doesn’t have any fixed reference point. According to Java documentation,The value returned represents nanoseconds since some fixed
but arbitrary time (perhaps in the future, so values may be negative).Less accurate. This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.Depending on the system, it can take more than 100 cpu cycles to execute.Not thread safe. May return erroneous results if used between more than one threads.
The result reflected doesn’t have any fixed reference point. According to Java documentation,The value returned represents nanoseconds since some fixed
but arbitrary time (perhaps in the future, so values may be negative).
The value returned represents nanoseconds since some fixed
but arbitrary time (perhaps in the future, so values may be negative).
Less accurate. This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.
Depending on the system, it can take more than 100 cpu cycles to execute.
Not thread safe. May return erroneous results if used between more than one threads.
Let’s see a working example to compare the results of these two functions:
// Java program to illustrate// difference between// Java System.nanoTime()// and System.currentTimeMillisclass Main { public static void main(String[] args) { // Get the current system time in // both nano and milli-seconds before // calling the function. long nano_startTime = System.nanoTime(); long millis_startTime = System.currentTimeMillis(); // Perform the work whose time is to be measured someFunction(); // Get the current system time in both // nano and milli-seconds after // the function returns. long nano_endTime = System.nanoTime(); long millis_endTime = System.currentTimeMillis(); // Print the time taken by subtracting // the end-time from the start-time System.out.println("Time taken in nano seconds: " + (nano_endTime - nano_startTime)); System.out.println("Time taken in milli seconds: " + (millis_endTime - millis_startTime)); } // The function whose execution // time is to be measured public static void someFunction() { for (int i = 0; i < Integer.MAX_VALUE; i++) { for (int j = 0; j < Integer.MAX_VALUE; j++) { // Here for example purpose // we run an empty loop } } }}
Output:
Time taken in nano seconds: 2519657
Time taken in milli seconds: 3
In conclusion, System.nanoTime() can/must be used whenever tasks of high precisions are to be performed, because it might seem that milli seconds is enough precision but for applications requiring fast performances (like games) nanoTime() will give much better results.However, it should be avoided whenever possible due to computational overheads and risks related to thread safety, in which case currentTimeMillis() is to be used.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Apr, 2018"
},
{
"code": null,
"e": 227,
"s": 53,
"text": "Java provides two methods to time operations, System.nanoTime() and System.currentTimeMillis(). But which one should be used in which condition? And which is more efficient?"
},
{
"code": null,
"e": 523,
"s": 227,
"text": "From the first look it might seem that nanoTime() should be used because it gives more precise value of time (in nano seconds, compared to milli seconds that the other method returns). But is it always efficient on the CPU to use nanoTime? Let us look at pros and cons of using both the methods:"
},
{
"code": null,
"e": 550,
"s": 523,
"text": "System.currentTimeMillis()"
},
{
"code": null,
"e": 635,
"s": 550,
"text": "public static long currentTimeMillis()\n// Returns the current time in milliseconds.\n"
},
{
"code": null,
"e": 641,
"s": 635,
"text": "Pros:"
},
{
"code": null,
"e": 1026,
"s": 641,
"text": "It is thread safe. Thread safety means that if this method is called between two or more different threads, it will not return erroneous results.Always returns the absolute time elapsed since the epoch (number of millis since 1 Jan 1970 00:00).Consumes lesser clock cycles to execute (around 5-6 cpu clocks).Gives more accurate time, since the point of reference (the epoch) is fixed."
},
{
"code": null,
"e": 1172,
"s": 1026,
"text": "It is thread safe. Thread safety means that if this method is called between two or more different threads, it will not return erroneous results."
},
{
"code": null,
"e": 1272,
"s": 1172,
"text": "Always returns the absolute time elapsed since the epoch (number of millis since 1 Jan 1970 00:00)."
},
{
"code": null,
"e": 1337,
"s": 1272,
"text": "Consumes lesser clock cycles to execute (around 5-6 cpu clocks)."
},
{
"code": null,
"e": 1414,
"s": 1337,
"text": "Gives more accurate time, since the point of reference (the epoch) is fixed."
},
{
"code": null,
"e": 1420,
"s": 1414,
"text": "Cons:"
},
{
"code": null,
"e": 1707,
"s": 1420,
"text": "Less precise. The result is somewhere between 1/1000th to 15/1000th of a second. On some machines, the resolution is even less than 50ms and can go down to upto 10ms only.It may give wrong results if the user changes the system time, hits a leap second or there are changes in NTP sync."
},
{
"code": null,
"e": 1879,
"s": 1707,
"text": "Less precise. The result is somewhere between 1/1000th to 15/1000th of a second. On some machines, the resolution is even less than 50ms and can go down to upto 10ms only."
},
{
"code": null,
"e": 1995,
"s": 1879,
"text": "It may give wrong results if the user changes the system time, hits a leap second or there are changes in NTP sync."
},
{
"code": null,
"e": 2013,
"s": 1995,
"text": "System.nanoTime()"
},
{
"code": null,
"e": 2142,
"s": 2013,
"text": "public static long nanoTime()\n// Returns the current value of the running JVM's high-resolution\n// time source, in nanoseconds.\n"
},
{
"code": null,
"e": 2148,
"s": 2142,
"text": "Pros:"
},
{
"code": null,
"e": 2272,
"s": 2148,
"text": "Highly precise. The time returned is around 1/1000000th of a second.The resolution is much higher than currentTimeMillis()."
},
{
"code": null,
"e": 2341,
"s": 2272,
"text": "Highly precise. The time returned is around 1/1000000th of a second."
},
{
"code": null,
"e": 2397,
"s": 2341,
"text": "The resolution is much higher than currentTimeMillis()."
},
{
"code": null,
"e": 2403,
"s": 2397,
"text": "Cons:"
},
{
"code": null,
"e": 2940,
"s": 2403,
"text": "The result reflected doesn’t have any fixed reference point. According to Java documentation,The value returned represents nanoseconds since some fixed\nbut arbitrary time (perhaps in the future, so values may be negative).Less accurate. This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.Depending on the system, it can take more than 100 cpu cycles to execute.Not thread safe. May return erroneous results if used between more than one threads."
},
{
"code": null,
"e": 3163,
"s": 2940,
"text": "The result reflected doesn’t have any fixed reference point. According to Java documentation,The value returned represents nanoseconds since some fixed\nbut arbitrary time (perhaps in the future, so values may be negative)."
},
{
"code": null,
"e": 3293,
"s": 3163,
"text": "The value returned represents nanoseconds since some fixed\nbut arbitrary time (perhaps in the future, so values may be negative)."
},
{
"code": null,
"e": 3451,
"s": 3293,
"text": "Less accurate. This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change."
},
{
"code": null,
"e": 3525,
"s": 3451,
"text": "Depending on the system, it can take more than 100 cpu cycles to execute."
},
{
"code": null,
"e": 3610,
"s": 3525,
"text": "Not thread safe. May return erroneous results if used between more than one threads."
},
{
"code": null,
"e": 3685,
"s": 3610,
"text": "Let’s see a working example to compare the results of these two functions:"
},
{
"code": "// Java program to illustrate// difference between// Java System.nanoTime()// and System.currentTimeMillisclass Main { public static void main(String[] args) { // Get the current system time in // both nano and milli-seconds before // calling the function. long nano_startTime = System.nanoTime(); long millis_startTime = System.currentTimeMillis(); // Perform the work whose time is to be measured someFunction(); // Get the current system time in both // nano and milli-seconds after // the function returns. long nano_endTime = System.nanoTime(); long millis_endTime = System.currentTimeMillis(); // Print the time taken by subtracting // the end-time from the start-time System.out.println(\"Time taken in nano seconds: \" + (nano_endTime - nano_startTime)); System.out.println(\"Time taken in milli seconds: \" + (millis_endTime - millis_startTime)); } // The function whose execution // time is to be measured public static void someFunction() { for (int i = 0; i < Integer.MAX_VALUE; i++) { for (int j = 0; j < Integer.MAX_VALUE; j++) { // Here for example purpose // we run an empty loop } } }}",
"e": 5046,
"s": 3685,
"text": null
},
{
"code": null,
"e": 5054,
"s": 5046,
"text": "Output:"
},
{
"code": null,
"e": 5123,
"s": 5054,
"text": "Time taken in nano seconds: 2519657\nTime taken in milli seconds: 3\n\n"
},
{
"code": null,
"e": 5556,
"s": 5123,
"text": "In conclusion, System.nanoTime() can/must be used whenever tasks of high precisions are to be performed, because it might seem that milli seconds is enough precision but for applications requiring fast performances (like games) nanoTime() will give much better results.However, it should be avoided whenever possible due to computational overheads and risks related to thread safety, in which case currentTimeMillis() is to be used."
},
{
"code": null,
"e": 5561,
"s": 5556,
"text": "Java"
},
{
"code": null,
"e": 5566,
"s": 5561,
"text": "Java"
},
{
"code": null,
"e": 5664,
"s": 5566,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5715,
"s": 5664,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5746,
"s": 5715,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5765,
"s": 5746,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5795,
"s": 5765,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5813,
"s": 5795,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5833,
"s": 5813,
"text": "Collections in Java"
},
{
"code": null,
"e": 5848,
"s": 5833,
"text": "Stream In Java"
},
{
"code": null,
"e": 5880,
"s": 5848,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5904,
"s": 5880,
"text": "Singleton Class in Java"
}
] |
Implement Inter Thread Communication with Event( ) Method in Python
|
02 Feb, 2021
Here we will start from the basics of what inter-thread communication is? Inter Thread Communication is the process of communicating requirements between one to another thread. In simple words sometimes one thread may be required to communicate to another thread depending on the requirements. This is considered as Inter Thread Communication.
Event() Method: Here we talk about the Event() method, the Event object is considered or recommended as the simplest communication process or system between any threads. This system works on two conditions where the Event object is Enabled means set() or disabled means clear().
Syntax:
event_object = threading.Event()
In the Internally Event manages the process which will be worked internally and it can be Set (enabled) or Clear (disabled) using the methods on event objects. If the threads are to be Set then all the threads are going to be executed but if the threads are to be Clear then generally all the threads become to wait for execution.
Example :
We take an example to explain how the event method is used in the implementation of inter-thread communication:
Python3
#import modulesimport threadingimport time if __name__ == '__main__': # initializing the event object event_object = threading.Event() # defining taskdef task(): print("\nStarted thread but waiting for event...") event_set = event_object.wait(4) if event_set: print("\nreceived and releasing thread") else: print("\ntime is gone...") # assigning taskthread1 = threading.Thread(target=task) # starting threadthread1.start() time.sleep(3)event_object.set()print("\nsetting of event is done")
Output:
In the above following program in which we create the event object, and then we create a thread and start it, now the thread is set the event object with the set() method and in function task() where the thread is in waiting for the state if the event is set to the thread will execute here next instruction if it was not set then the program is terminated still there is having an instruction to be executed.
Here are some general methods are used in the Event class:-
clear( ) Method: This method is fully opposite of the set() method, but this method also acts as a condition changer if the condition becomes False then which thread is not running or already in waiting, so they are still is in waiting for state and don’t continue there execution.
set( ) Method: In the set() method we used it as a condition changer between threads where if the condition will True then there are much thread which was in waiting for the state they become continue their execution.
isSet( ) Method: This isSet() method has meaning as their name suggests is set, this method simplifies that the following event that we have created are set or not set.
wait( time ) Method: To describe the wait() method in simple words we can say that thread waits until the execution of the set() method is not done. We can use time in it if we set a certain time then the execution will stop until time overs after that it will execute still the set() of an event is remaining.
Here we will take a simple example to explain how the above methods are used throughout the entire program:
Python3
# import time moduleimport time # import threading moduleimport threading class product: def buyer(self): print('John consumer is wait for product') print('...............') event_object.wait() print('got product') def seller(self): time.sleep(5) print('Tom producer producing items') print('tom goes to retailer') event_object.wait() def retailer(self): time.sleep(10) print('retailer found that product and directly send to buyer') event_object.set() # class object class_obj = product() # setting event objectif __name__=='__main__': event_object = threading.Event() # creating threadsT1 = threading.Thread(target=class_obj.buyer)T2 = threading.Thread(target=class_obj.seller)T3 = threading.Thread(target=class_obj.retailer) # starting threadsT1.start()T2.start()T3.start()
Output:
This is a simple example to explain the use of event() class and their methods in inter-thread communication. Here we use an example of buyer-seller and retailer, first, we have import two modules which are the threading module and time module, then we create a class product in which has the first function which is the buyer() which are having several instructions. At the first T3 thread will execute for retailer() function but the T3 is going to wait for 10sec because of the timer after this T2 is going to execute but same here T2 also have to wait for 5 sec, after that now T1 is going to execute for buyer() function in the buyer function when the wait() method is executed then thread T1 has to wait until an event is set(), Now T2 will execute their instructions where it has also wait() method when wait() is executed then thread T2 stops their execution until set() method called. Now it’s time for thread T3 in this set() method is called which releases all the waiting thread from waiting for state and those threads like T2 and T1 continue their execution.
Python-threading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 373,
"s": 28,
"text": "Here we will start from the basics of what inter-thread communication is? Inter Thread Communication is the process of communicating requirements between one to another thread. In simple words sometimes one thread may be required to communicate to another thread depending on the requirements. This is considered as Inter Thread Communication. "
},
{
"code": null,
"e": 654,
"s": 373,
"text": "Event() Method: Here we talk about the Event() method, the Event object is considered or recommended as the simplest communication process or system between any threads. This system works on two conditions where the Event object is Enabled means set() or disabled means clear(). "
},
{
"code": null,
"e": 662,
"s": 654,
"text": "Syntax:"
},
{
"code": null,
"e": 695,
"s": 662,
"text": "event_object = threading.Event()"
},
{
"code": null,
"e": 1026,
"s": 695,
"text": "In the Internally Event manages the process which will be worked internally and it can be Set (enabled) or Clear (disabled) using the methods on event objects. If the threads are to be Set then all the threads are going to be executed but if the threads are to be Clear then generally all the threads become to wait for execution."
},
{
"code": null,
"e": 1036,
"s": 1026,
"text": "Example :"
},
{
"code": null,
"e": 1149,
"s": 1036,
"text": " We take an example to explain how the event method is used in the implementation of inter-thread communication:"
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Python3"
},
{
"code": "#import modulesimport threadingimport time if __name__ == '__main__': # initializing the event object event_object = threading.Event() # defining taskdef task(): print(\"\\nStarted thread but waiting for event...\") event_set = event_object.wait(4) if event_set: print(\"\\nreceived and releasing thread\") else: print(\"\\ntime is gone...\") # assigning taskthread1 = threading.Thread(target=task) # starting threadthread1.start() time.sleep(3)event_object.set()print(\"\\nsetting of event is done\")",
"e": 1698,
"s": 1157,
"text": null
},
{
"code": null,
"e": 1706,
"s": 1698,
"text": "Output:"
},
{
"code": null,
"e": 2116,
"s": 1706,
"text": "In the above following program in which we create the event object, and then we create a thread and start it, now the thread is set the event object with the set() method and in function task() where the thread is in waiting for the state if the event is set to the thread will execute here next instruction if it was not set then the program is terminated still there is having an instruction to be executed."
},
{
"code": null,
"e": 2176,
"s": 2116,
"text": "Here are some general methods are used in the Event class:-"
},
{
"code": null,
"e": 2459,
"s": 2176,
"text": " clear( ) Method: This method is fully opposite of the set() method, but this method also acts as a condition changer if the condition becomes False then which thread is not running or already in waiting, so they are still is in waiting for state and don’t continue there execution."
},
{
"code": null,
"e": 2677,
"s": 2459,
"text": "set( ) Method: In the set() method we used it as a condition changer between threads where if the condition will True then there are much thread which was in waiting for the state they become continue their execution."
},
{
"code": null,
"e": 2846,
"s": 2677,
"text": "isSet( ) Method: This isSet() method has meaning as their name suggests is set, this method simplifies that the following event that we have created are set or not set."
},
{
"code": null,
"e": 3157,
"s": 2846,
"text": "wait( time ) Method: To describe the wait() method in simple words we can say that thread waits until the execution of the set() method is not done. We can use time in it if we set a certain time then the execution will stop until time overs after that it will execute still the set() of an event is remaining."
},
{
"code": null,
"e": 3265,
"s": 3157,
"text": "Here we will take a simple example to explain how the above methods are used throughout the entire program:"
},
{
"code": null,
"e": 3273,
"s": 3265,
"text": "Python3"
},
{
"code": "# import time moduleimport time # import threading moduleimport threading class product: def buyer(self): print('John consumer is wait for product') print('...............') event_object.wait() print('got product') def seller(self): time.sleep(5) print('Tom producer producing items') print('tom goes to retailer') event_object.wait() def retailer(self): time.sleep(10) print('retailer found that product and directly send to buyer') event_object.set() # class object class_obj = product() # setting event objectif __name__=='__main__': event_object = threading.Event() # creating threadsT1 = threading.Thread(target=class_obj.buyer)T2 = threading.Thread(target=class_obj.seller)T3 = threading.Thread(target=class_obj.retailer) # starting threadsT1.start()T2.start()T3.start()",
"e": 4144,
"s": 3273,
"text": null
},
{
"code": null,
"e": 4152,
"s": 4144,
"text": "Output:"
},
{
"code": null,
"e": 5225,
"s": 4152,
"text": "This is a simple example to explain the use of event() class and their methods in inter-thread communication. Here we use an example of buyer-seller and retailer, first, we have import two modules which are the threading module and time module, then we create a class product in which has the first function which is the buyer() which are having several instructions. At the first T3 thread will execute for retailer() function but the T3 is going to wait for 10sec because of the timer after this T2 is going to execute but same here T2 also have to wait for 5 sec, after that now T1 is going to execute for buyer() function in the buyer function when the wait() method is executed then thread T1 has to wait until an event is set(), Now T2 will execute their instructions where it has also wait() method when wait() is executed then thread T2 stops their execution until set() method called. Now it’s time for thread T3 in this set() method is called which releases all the waiting thread from waiting for state and those threads like T2 and T1 continue their execution."
},
{
"code": null,
"e": 5242,
"s": 5225,
"text": "Python-threading"
},
{
"code": null,
"e": 5249,
"s": 5242,
"text": "Python"
}
] |
Ruby Hook Methods - GeeksforGeeks
|
13 Aug, 2021
Ruby Hook Methods are called in reaction to something you do. They are usually used to extend the working of methods at run time. These methods are not defined by default, but a programmer can define them according to imply them on any object or class or module and they will come into picture when certain events occur.
These methods help to extend the behavior of fundamentals when methods are called or subclasses of a class are formed or modules are incorporated. The meta programming ability of Ruby language helps the users to comfortably write dynamic codes at run time. The Hook Methods can perform a certain function once a particular action has been executed.
There are several Ruby Hook Methods, but majorly, the followings have major roles to play:
IncludedPrependedExtendedInheritedmethod_missing
Included
Prepended
Extended
Inherited
method_missing
Modules in RubyBefore going through each of the methods, one needs to understand the concept of modules in Ruby. Modules are simply sets of code that could be written once and be used at multiple places. Usually, hook methods are used to access them and make changes in them.
1. Included:This method is used to include a method or attribute or module to another module. The method makes the underlined module available to the instances of the class. The following example explains the usage and working of the include method.
The example is a simple code to generate a comment when the module is executed in the class in which it is included.
Ruby
# Declaring a module to greet a personmodule Greetings def self.included(person_to_be_greeted) puts "The #{person_to_be_greeted} is welcomed with an open heart !" endend # Class where the module is includedclass Person include Greetings # implementation of the include statementend
Output:
The Person is welcomed with an open heart !
2. Prepended:This method was brought by Ruby 2.0. This is slightly different from what we observed above. Prepended method provides another way of extending the functioning of modules at different places. This uses the concept of overriding. The modules can be overridden using methods defined in the target class.
The concept of Prepended method could be understood by the following self-explanatory example:
Ruby
# Code as an example for prepend methodmodule Ruby def self.prepended(target)# Implementation of prepend method puts "#{self} has been prepended to #{target}" end def Type "The Type belongs to Ruby" endend class Coding prepend Ruby # the module Ruby is prependedend # Method callputs Coding.new.Type
Output:
Ruby has been prepended to Coding
The Type belongs to Ruby
3. Extended:This method is a bit different from both the include and prepend method. While include applies methods in a certain module to instance of a class, extend applies those methods to the same class.
The execution of the above mentioned code using the extend method can be done as follows:
Ruby
# Code as an example for extend methodmodule Ruby def self.extended(target) puts "#{self} was extended by #{target}" end def Type "The Type is Ruby" endend class Coding extend Ruby # Extending the module Rubyend # Method callingputs Coding.Type
Output:
Ruby was extended by Coding
The Type is Ruby
4. Inherited:Inheritance as a concept is one of the most important concepts of Object Oriented Programming and is common in almost every programming language. In ruby, we deal in objects that are inspired from the real life, and thus, Oops operations play a very important role there. The inherited method is called whenever a subclass of a class is implemented. It is a method of making a child class from a parent class.
The following example shows the same:
Ruby
# Making the parent Vehicle classclass Vehicle def self.inherited(car_type) puts "#{car_type} is a kind of Vehicle" end end # Target classclass Hyundai < Vehicle #Inhereting the Vehicle classend
Output:
Hyundai is a kind of Vehicle
5. method_missing: method_missing method which is one of the most widely used in Ruby. This comes to action when one tries to call a method on an object that does not exist.
The following example explains its working:
Ruby
# The main classclass Ruby def method_missing(input, *args) # method_missing function in action "#{input} not defined on #{self}" end def Type "The Type is Ruby" endend var = Ruby.new # Calling a method that existsputs var.Type # Calling a method that does not existputs var.Name
Output:
The Type is Ruby
Name not defined on #<Ruby:0x0000000002363290> (object var)
There is a concept of callback that is often confused with the hook methods. While callbacks are the elements of the code of the program like methods, modules, etc, hook is just a spot in the code where they are accessed. Thus, the concept of callback should not be confused with hooks in Ruby.
As we know, the Ruby language is one programming language that has a very clear correspondence with the daily life objects and methods, it is required that one who is working in the same, has thorough knowledge of all the necessary Oops concepts and Hook methods is one of them.
2000sparshgoyal
Picked
Ruby Keyword
Ruby-OOP
Ruby
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Case Statement
Ruby | Hash delete() function
Ruby | Data Types
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | String gsub! Method
|
[
{
"code": null,
"e": 23692,
"s": 23664,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 24014,
"s": 23692,
"text": "Ruby Hook Methods are called in reaction to something you do. They are usually used to extend the working of methods at run time. These methods are not defined by default, but a programmer can define them according to imply them on any object or class or module and they will come into picture when certain events occur. "
},
{
"code": null,
"e": 24364,
"s": 24014,
"text": "These methods help to extend the behavior of fundamentals when methods are called or subclasses of a class are formed or modules are incorporated. The meta programming ability of Ruby language helps the users to comfortably write dynamic codes at run time. The Hook Methods can perform a certain function once a particular action has been executed. "
},
{
"code": null,
"e": 24456,
"s": 24364,
"text": "There are several Ruby Hook Methods, but majorly, the followings have major roles to play: "
},
{
"code": null,
"e": 24505,
"s": 24456,
"text": "IncludedPrependedExtendedInheritedmethod_missing"
},
{
"code": null,
"e": 24514,
"s": 24505,
"text": "Included"
},
{
"code": null,
"e": 24524,
"s": 24514,
"text": "Prepended"
},
{
"code": null,
"e": 24533,
"s": 24524,
"text": "Extended"
},
{
"code": null,
"e": 24543,
"s": 24533,
"text": "Inherited"
},
{
"code": null,
"e": 24558,
"s": 24543,
"text": "method_missing"
},
{
"code": null,
"e": 24835,
"s": 24558,
"text": "Modules in RubyBefore going through each of the methods, one needs to understand the concept of modules in Ruby. Modules are simply sets of code that could be written once and be used at multiple places. Usually, hook methods are used to access them and make changes in them. "
},
{
"code": null,
"e": 25085,
"s": 24835,
"text": "1. Included:This method is used to include a method or attribute or module to another module. The method makes the underlined module available to the instances of the class. The following example explains the usage and working of the include method."
},
{
"code": null,
"e": 25203,
"s": 25085,
"text": "The example is a simple code to generate a comment when the module is executed in the class in which it is included. "
},
{
"code": null,
"e": 25208,
"s": 25203,
"text": "Ruby"
},
{
"code": "# Declaring a module to greet a personmodule Greetings def self.included(person_to_be_greeted) puts \"The #{person_to_be_greeted} is welcomed with an open heart !\" endend # Class where the module is includedclass Person include Greetings # implementation of the include statementend",
"e": 25500,
"s": 25208,
"text": null
},
{
"code": null,
"e": 25509,
"s": 25500,
"text": "Output: "
},
{
"code": null,
"e": 25553,
"s": 25509,
"text": "The Person is welcomed with an open heart !"
},
{
"code": null,
"e": 25869,
"s": 25553,
"text": "2. Prepended:This method was brought by Ruby 2.0. This is slightly different from what we observed above. Prepended method provides another way of extending the functioning of modules at different places. This uses the concept of overriding. The modules can be overridden using methods defined in the target class. "
},
{
"code": null,
"e": 25965,
"s": 25869,
"text": "The concept of Prepended method could be understood by the following self-explanatory example: "
},
{
"code": null,
"e": 25970,
"s": 25965,
"text": "Ruby"
},
{
"code": "# Code as an example for prepend methodmodule Ruby def self.prepended(target)# Implementation of prepend method puts \"#{self} has been prepended to #{target}\" end def Type \"The Type belongs to Ruby\" endend class Coding prepend Ruby # the module Ruby is prependedend # Method callputs Coding.new.Type",
"e": 26284,
"s": 25970,
"text": null
},
{
"code": null,
"e": 26293,
"s": 26284,
"text": "Output: "
},
{
"code": null,
"e": 26352,
"s": 26293,
"text": "Ruby has been prepended to Coding\nThe Type belongs to Ruby"
},
{
"code": null,
"e": 26560,
"s": 26352,
"text": "3. Extended:This method is a bit different from both the include and prepend method. While include applies methods in a certain module to instance of a class, extend applies those methods to the same class. "
},
{
"code": null,
"e": 26651,
"s": 26560,
"text": "The execution of the above mentioned code using the extend method can be done as follows: "
},
{
"code": null,
"e": 26656,
"s": 26651,
"text": "Ruby"
},
{
"code": "# Code as an example for extend methodmodule Ruby def self.extended(target) puts \"#{self} was extended by #{target}\" end def Type \"The Type is Ruby\" endend class Coding extend Ruby # Extending the module Rubyend # Method callingputs Coding.Type",
"e": 26916,
"s": 26656,
"text": null
},
{
"code": null,
"e": 26925,
"s": 26916,
"text": "Output: "
},
{
"code": null,
"e": 26970,
"s": 26925,
"text": "Ruby was extended by Coding\nThe Type is Ruby"
},
{
"code": null,
"e": 27394,
"s": 26970,
"text": "4. Inherited:Inheritance as a concept is one of the most important concepts of Object Oriented Programming and is common in almost every programming language. In ruby, we deal in objects that are inspired from the real life, and thus, Oops operations play a very important role there. The inherited method is called whenever a subclass of a class is implemented. It is a method of making a child class from a parent class. "
},
{
"code": null,
"e": 27433,
"s": 27394,
"text": "The following example shows the same: "
},
{
"code": null,
"e": 27438,
"s": 27433,
"text": "Ruby"
},
{
"code": "# Making the parent Vehicle classclass Vehicle def self.inherited(car_type) puts \"#{car_type} is a kind of Vehicle\" end end # Target classclass Hyundai < Vehicle #Inhereting the Vehicle classend",
"e": 27639,
"s": 27438,
"text": null
},
{
"code": null,
"e": 27648,
"s": 27639,
"text": "Output: "
},
{
"code": null,
"e": 27677,
"s": 27648,
"text": "Hyundai is a kind of Vehicle"
},
{
"code": null,
"e": 27852,
"s": 27677,
"text": "5. method_missing: method_missing method which is one of the most widely used in Ruby. This comes to action when one tries to call a method on an object that does not exist. "
},
{
"code": null,
"e": 27897,
"s": 27852,
"text": "The following example explains its working: "
},
{
"code": null,
"e": 27902,
"s": 27897,
"text": "Ruby"
},
{
"code": "# The main classclass Ruby def method_missing(input, *args) # method_missing function in action \"#{input} not defined on #{self}\" end def Type \"The Type is Ruby\" endend var = Ruby.new # Calling a method that existsputs var.Type # Calling a method that does not existputs var.Name ",
"e": 28199,
"s": 27902,
"text": null
},
{
"code": null,
"e": 28208,
"s": 28199,
"text": "Output: "
},
{
"code": null,
"e": 28285,
"s": 28208,
"text": "The Type is Ruby\nName not defined on #<Ruby:0x0000000002363290> (object var)"
},
{
"code": null,
"e": 28581,
"s": 28285,
"text": "There is a concept of callback that is often confused with the hook methods. While callbacks are the elements of the code of the program like methods, modules, etc, hook is just a spot in the code where they are accessed. Thus, the concept of callback should not be confused with hooks in Ruby. "
},
{
"code": null,
"e": 28860,
"s": 28581,
"text": "As we know, the Ruby language is one programming language that has a very clear correspondence with the daily life objects and methods, it is required that one who is working in the same, has thorough knowledge of all the necessary Oops concepts and Hook methods is one of them."
},
{
"code": null,
"e": 28878,
"s": 28862,
"text": "2000sparshgoyal"
},
{
"code": null,
"e": 28885,
"s": 28878,
"text": "Picked"
},
{
"code": null,
"e": 28898,
"s": 28885,
"text": "Ruby Keyword"
},
{
"code": null,
"e": 28907,
"s": 28898,
"text": "Ruby-OOP"
},
{
"code": null,
"e": 28912,
"s": 28907,
"text": "Ruby"
},
{
"code": null,
"e": 28931,
"s": 28912,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29029,
"s": 28931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29060,
"s": 29029,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 29087,
"s": 29060,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 29130,
"s": 29087,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 29154,
"s": 29130,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 29185,
"s": 29154,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 29207,
"s": 29185,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 29237,
"s": 29207,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 29255,
"s": 29237,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 29323,
"s": 29255,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
}
] |
Augmented Assignment Operators in Python - GeeksforGeeks
|
07 Sep, 2021
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write “a = 5“ to assign value 5 to variable ‘a’. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “a = a + 7“, we can use the augmented assignment operator and write the expression as “a += 7“. Here += has combined the functionality of arithmetic addition and assignment.
So, augmented assignment operators provide a short way to perform a binary operation and assigning results back to one of the operands. The way to write an augmented operator is just to write that binary operator and assignment operator together. In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes:
1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,
a = a + b can be written as a += b
Example:
Python3
# Addition & Assignmenta = 15b = 20 a += bprint(a)
35
2. Subtraction and Assignment (-=): This operator combines the impact of subtraction and assignment.
a = a – b can be written as a -= b
Example:
Python3
# Subtraction & Assignmenta = 107b = 99 a -= bprint(a)
8
3. Multiplication and Assignment (*=): This operator combines the functionality of multiplication and assignment.
a = a * b can be written as a *= b
Example:
Python3
# Multiplication & Assignmenta = 12b = 23 a *= bprint(a)
276
4. Division and Assignment (/=): This operator has the combined functionality of division and assignment.
a = a / b can be written as a /= b
Example:
Python3
# Division & Assignmenta = 56b = 5 a /= bprint(a)
11.2
5. Floor Division and Assignment (//=): It performs the functioning of floor division and assignment.
a = a // b can be written as a //= b
Example:
Python3
# Floor Division & Assignmenta = 56b = 8 a //= bprint(a)
7
6. Modulo and Assignment (%=): This operator combines the impact of the modulo operator and assignment.
a = a % b can be written as a %= b
Example:
Python3
# Modulo & Assignmenta = 34b = 5 a %= bprint(a)
4
7. Power and Assignment (**=): This operator is equivalent to the power and assignment operator together.
a = a**b can be written as a **= b
Example:
Python3
# Power & Assignmenta = 5b = 3 a **= bprint(a)
125
8. Bitwise AND & Assignment (&=): This operator combines the impact of the bitwise AND operator and assignment operator.
a = a & b can be written as a &= b
Example:
Python3
# Bitwise AND & Assignmenta = 12b = 10 a &= bprint(a)
8
9. Bitwise OR and Assignment (|=): This operator combines the impact of Bitwise OR and assignment operator.
a = a | b can be written as a |= b
Example:
Python3
# Bitwise OR and Assignmenta = 12b = 10 a |= bprint(a)
14
10. Bitwise XOR and Assignment (^=): This augmented assignment operator combines the functionality of the bitwise XOR operator and assignment operator.
a = a ^ b can be written as a ^= b
Example:
Python3
# Bitwise XOR and Assignmenta = 12b = 10 a ^= bprint(a)
6
11. Bitwise Left Shift and Assignment (<<=): It puts together the functioning of the bitwise left shift operator and assignment operator.
a = a << b can be written as a <<= b
Example:
Python3
# Bitwise Left Shift and Assignmenta = 17b = 2 a <<= bprint(a)
68
12. Bitwise Right Shift and Assignment (>>=): It puts together the functioning of the bitwise right shift operator and assignment operator.
a = a >> b can be written as a >>= b
Example:
Python3
# Bitwise Right Shift and Assignmenta = 17b = 2 a >>= bprint(a)
4
surindertarika1234
Picked
Class 11
Python
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Measures of Central Tendency
What is Cyber Bullying? Definition, Types, Effects, Laws
Importance of Chemistry in Everyday Life
Measure of Dispersion
What is Plagiarism? Definition, Types, How to Avoid, Laws
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24224,
"s": 24196,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 24869,
"s": 24224,
"text": "An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write “a = 5“ to assign value 5 to variable ‘a’. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “a = a + 7“, we can use the augmented assignment operator and write the expression as “a += 7“. Here += has combined the functionality of arithmetic addition and assignment."
},
{
"code": null,
"e": 25310,
"s": 24869,
"text": "So, augmented assignment operators provide a short way to perform a binary operation and assigning results back to one of the operands. The way to write an augmented operator is just to write that binary operator and assignment operator together. In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes:"
},
{
"code": null,
"e": 25422,
"s": 25310,
"text": "1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,"
},
{
"code": null,
"e": 25458,
"s": 25422,
"text": " a = a + b can be written as a += b"
},
{
"code": null,
"e": 25467,
"s": 25458,
"text": "Example:"
},
{
"code": null,
"e": 25475,
"s": 25467,
"text": "Python3"
},
{
"code": "# Addition & Assignmenta = 15b = 20 a += bprint(a)",
"e": 25526,
"s": 25475,
"text": null
},
{
"code": null,
"e": 25529,
"s": 25526,
"text": "35"
},
{
"code": null,
"e": 25632,
"s": 25529,
"text": "2. Subtraction and Assignment (-=): This operator combines the impact of subtraction and assignment. "
},
{
"code": null,
"e": 25667,
"s": 25632,
"text": "a = a – b can be written as a -= b"
},
{
"code": null,
"e": 25677,
"s": 25667,
"text": "Example: "
},
{
"code": null,
"e": 25685,
"s": 25677,
"text": "Python3"
},
{
"code": "# Subtraction & Assignmenta = 107b = 99 a -= bprint(a)",
"e": 25740,
"s": 25685,
"text": null
},
{
"code": null,
"e": 25742,
"s": 25740,
"text": "8"
},
{
"code": null,
"e": 25858,
"s": 25742,
"text": "3. Multiplication and Assignment (*=): This operator combines the functionality of multiplication and assignment. "
},
{
"code": null,
"e": 25893,
"s": 25858,
"text": "a = a * b can be written as a *= b"
},
{
"code": null,
"e": 25902,
"s": 25893,
"text": "Example:"
},
{
"code": null,
"e": 25910,
"s": 25902,
"text": "Python3"
},
{
"code": "# Multiplication & Assignmenta = 12b = 23 a *= bprint(a)",
"e": 25967,
"s": 25910,
"text": null
},
{
"code": null,
"e": 25971,
"s": 25967,
"text": "276"
},
{
"code": null,
"e": 26079,
"s": 25971,
"text": "4. Division and Assignment (/=): This operator has the combined functionality of division and assignment. "
},
{
"code": null,
"e": 26114,
"s": 26079,
"text": "a = a / b can be written as a /= b"
},
{
"code": null,
"e": 26124,
"s": 26114,
"text": "Example: "
},
{
"code": null,
"e": 26132,
"s": 26124,
"text": "Python3"
},
{
"code": "# Division & Assignmenta = 56b = 5 a /= bprint(a)",
"e": 26182,
"s": 26132,
"text": null
},
{
"code": null,
"e": 26187,
"s": 26182,
"text": "11.2"
},
{
"code": null,
"e": 26291,
"s": 26187,
"text": "5. Floor Division and Assignment (//=): It performs the functioning of floor division and assignment. "
},
{
"code": null,
"e": 26328,
"s": 26291,
"text": "a = a // b can be written as a //= b"
},
{
"code": null,
"e": 26338,
"s": 26328,
"text": "Example: "
},
{
"code": null,
"e": 26346,
"s": 26338,
"text": "Python3"
},
{
"code": "# Floor Division & Assignmenta = 56b = 8 a //= bprint(a)",
"e": 26403,
"s": 26346,
"text": null
},
{
"code": null,
"e": 26405,
"s": 26403,
"text": "7"
},
{
"code": null,
"e": 26511,
"s": 26405,
"text": "6. Modulo and Assignment (%=): This operator combines the impact of the modulo operator and assignment. "
},
{
"code": null,
"e": 26546,
"s": 26511,
"text": "a = a % b can be written as a %= b"
},
{
"code": null,
"e": 26556,
"s": 26546,
"text": "Example: "
},
{
"code": null,
"e": 26564,
"s": 26556,
"text": "Python3"
},
{
"code": "# Modulo & Assignmenta = 34b = 5 a %= bprint(a)",
"e": 26612,
"s": 26564,
"text": null
},
{
"code": null,
"e": 26614,
"s": 26612,
"text": "4"
},
{
"code": null,
"e": 26722,
"s": 26614,
"text": "7. Power and Assignment (**=): This operator is equivalent to the power and assignment operator together. "
},
{
"code": null,
"e": 26757,
"s": 26722,
"text": "a = a**b can be written as a **= b"
},
{
"code": null,
"e": 26767,
"s": 26757,
"text": "Example: "
},
{
"code": null,
"e": 26775,
"s": 26767,
"text": "Python3"
},
{
"code": "# Power & Assignmenta = 5b = 3 a **= bprint(a)",
"e": 26822,
"s": 26775,
"text": null
},
{
"code": null,
"e": 26826,
"s": 26822,
"text": "125"
},
{
"code": null,
"e": 26948,
"s": 26826,
"text": "8. Bitwise AND & Assignment (&=): This operator combines the impact of the bitwise AND operator and assignment operator. "
},
{
"code": null,
"e": 26983,
"s": 26948,
"text": "a = a & b can be written as a &= b"
},
{
"code": null,
"e": 26993,
"s": 26983,
"text": "Example: "
},
{
"code": null,
"e": 27001,
"s": 26993,
"text": "Python3"
},
{
"code": "# Bitwise AND & Assignmenta = 12b = 10 a &= bprint(a)",
"e": 27055,
"s": 27001,
"text": null
},
{
"code": null,
"e": 27057,
"s": 27055,
"text": "8"
},
{
"code": null,
"e": 27167,
"s": 27057,
"text": "9. Bitwise OR and Assignment (|=): This operator combines the impact of Bitwise OR and assignment operator. "
},
{
"code": null,
"e": 27202,
"s": 27167,
"text": "a = a | b can be written as a |= b"
},
{
"code": null,
"e": 27212,
"s": 27202,
"text": "Example: "
},
{
"code": null,
"e": 27220,
"s": 27212,
"text": "Python3"
},
{
"code": "# Bitwise OR and Assignmenta = 12b = 10 a |= bprint(a)",
"e": 27275,
"s": 27220,
"text": null
},
{
"code": null,
"e": 27278,
"s": 27275,
"text": "14"
},
{
"code": null,
"e": 27431,
"s": 27278,
"text": "10. Bitwise XOR and Assignment (^=): This augmented assignment operator combines the functionality of the bitwise XOR operator and assignment operator. "
},
{
"code": null,
"e": 27466,
"s": 27431,
"text": "a = a ^ b can be written as a ^= b"
},
{
"code": null,
"e": 27476,
"s": 27466,
"text": "Example: "
},
{
"code": null,
"e": 27484,
"s": 27476,
"text": "Python3"
},
{
"code": "# Bitwise XOR and Assignmenta = 12b = 10 a ^= bprint(a)",
"e": 27540,
"s": 27484,
"text": null
},
{
"code": null,
"e": 27542,
"s": 27540,
"text": "6"
},
{
"code": null,
"e": 27682,
"s": 27542,
"text": "11. Bitwise Left Shift and Assignment (<<=): It puts together the functioning of the bitwise left shift operator and assignment operator. "
},
{
"code": null,
"e": 27719,
"s": 27682,
"text": "a = a << b can be written as a <<= b"
},
{
"code": null,
"e": 27729,
"s": 27719,
"text": "Example: "
},
{
"code": null,
"e": 27737,
"s": 27729,
"text": "Python3"
},
{
"code": "# Bitwise Left Shift and Assignmenta = 17b = 2 a <<= bprint(a)",
"e": 27800,
"s": 27737,
"text": null
},
{
"code": null,
"e": 27803,
"s": 27800,
"text": "68"
},
{
"code": null,
"e": 27945,
"s": 27803,
"text": "12. Bitwise Right Shift and Assignment (>>=): It puts together the functioning of the bitwise right shift operator and assignment operator. "
},
{
"code": null,
"e": 27982,
"s": 27945,
"text": "a = a >> b can be written as a >>= b"
},
{
"code": null,
"e": 27992,
"s": 27982,
"text": "Example: "
},
{
"code": null,
"e": 28000,
"s": 27992,
"text": "Python3"
},
{
"code": "# Bitwise Right Shift and Assignmenta = 17b = 2 a >>= bprint(a)",
"e": 28064,
"s": 28000,
"text": null
},
{
"code": null,
"e": 28066,
"s": 28064,
"text": "4"
},
{
"code": null,
"e": 28087,
"s": 28068,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28094,
"s": 28087,
"text": "Picked"
},
{
"code": null,
"e": 28103,
"s": 28094,
"text": "Class 11"
},
{
"code": null,
"e": 28110,
"s": 28103,
"text": "Python"
},
{
"code": null,
"e": 28126,
"s": 28110,
"text": "School Learning"
},
{
"code": null,
"e": 28145,
"s": 28126,
"text": "School Programming"
},
{
"code": null,
"e": 28243,
"s": 28145,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28252,
"s": 28243,
"text": "Comments"
},
{
"code": null,
"e": 28265,
"s": 28252,
"text": "Old Comments"
},
{
"code": null,
"e": 28294,
"s": 28265,
"text": "Measures of Central Tendency"
},
{
"code": null,
"e": 28351,
"s": 28294,
"text": "What is Cyber Bullying? Definition, Types, Effects, Laws"
},
{
"code": null,
"e": 28392,
"s": 28351,
"text": "Importance of Chemistry in Everyday Life"
},
{
"code": null,
"e": 28414,
"s": 28392,
"text": "Measure of Dispersion"
},
{
"code": null,
"e": 28472,
"s": 28414,
"text": "What is Plagiarism? Definition, Types, How to Avoid, Laws"
},
{
"code": null,
"e": 28500,
"s": 28472,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28550,
"s": 28500,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28572,
"s": 28550,
"text": "Python map() function"
}
] |
How to find MongoDB documents with a specific string?
|
To find documents with a specific string, use find() and in that search for a string with regex. Let us create a collection with documents −
> db.demo409.insertOne({"Name":"John Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70e4e515dc524f7022767c")
}
> db.demo409.insertOne({"Name":"Chris Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70e4ec15dc524f7022767d")
}
> db.demo409.insertOne({"Name":"Robert Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70e4f415dc524f7022767e")
}
> db.demo409.insertOne({"Name":"David Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70e4fe15dc524f7022767f")
}
Display all documents from a collection with the help of find() method −
> db.demo409.find();
This will produce the following output −
{ "_id" : ObjectId("5e70e4e515dc524f7022767c"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e70e4ec15dc524f7022767d"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e70e4f415dc524f7022767e"), "Name" : "Robert Doe" }
{ "_id" : ObjectId("5e70e4fe15dc524f7022767f"), "Name" : "David Brown" }
Following is the query to find documents with a specific string in MongoDB −
> db.demo409.find({Name: /Doe/});
This will produce the following output −
{ "_id" : ObjectId("5e70e4e515dc524f7022767c"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e70e4f415dc524f7022767e"), "Name" : "Robert Doe" }
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "To find documents with a specific string, use find() and in that search for a string with regex. Let us create a collection with documents −"
},
{
"code": null,
"e": 1731,
"s": 1203,
"text": "> db.demo409.insertOne({\"Name\":\"John Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e70e4e515dc524f7022767c\")\n}\n> db.demo409.insertOne({\"Name\":\"Chris Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e70e4ec15dc524f7022767d\")\n}\n> db.demo409.insertOne({\"Name\":\"Robert Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e70e4f415dc524f7022767e\")\n}\n> db.demo409.insertOne({\"Name\":\"David Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e70e4fe15dc524f7022767f\")\n}"
},
{
"code": null,
"e": 1804,
"s": 1731,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1825,
"s": 1804,
"text": "> db.demo409.find();"
},
{
"code": null,
"e": 1866,
"s": 1825,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2154,
"s": 1866,
"text": "{ \"_id\" : ObjectId(\"5e70e4e515dc524f7022767c\"), \"Name\" : \"John Doe\" }\n{ \"_id\" : ObjectId(\"5e70e4ec15dc524f7022767d\"), \"Name\" : \"Chris Brown\" }\n{ \"_id\" : ObjectId(\"5e70e4f415dc524f7022767e\"), \"Name\" : \"Robert Doe\" }\n{ \"_id\" : ObjectId(\"5e70e4fe15dc524f7022767f\"), \"Name\" : \"David Brown\" }"
},
{
"code": null,
"e": 2231,
"s": 2154,
"text": "Following is the query to find documents with a specific string in MongoDB −"
},
{
"code": null,
"e": 2265,
"s": 2231,
"text": "> db.demo409.find({Name: /Doe/});"
},
{
"code": null,
"e": 2306,
"s": 2265,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2448,
"s": 2306,
"text": "{ \"_id\" : ObjectId(\"5e70e4e515dc524f7022767c\"), \"Name\" : \"John Doe\" }\n{ \"_id\" : ObjectId(\"5e70e4f415dc524f7022767e\"), \"Name\" : \"Robert Doe\" }"
}
] |
Windows 10 Development - First App
|
In this chapter, we will be creating our first simple application "Hello world" in Universal Windows Platform (UWP) using XAML and C# on Windows 10. We will demonstrate how a single UWP application created in Visual Studio can be run and executed on any Windows 10 device.
Let us start creating the App by following the steps given below.
Launch Visual Studio 2015.
Launch Visual Studio 2015.
Click on the File menu and select New > Project.
Click on the File menu and select New > Project.
The following New Project dialog window will be displayed. You can see the different types of templates on the left pane of the dialog box.
The following New Project dialog window will be displayed. You can see the different types of templates on the left pane of the dialog box.
In the left pane, you can see the tree view. Select Universal template from Templates > Visual C# > Windows.
In the left pane, you can see the tree view. Select Universal template from Templates > Visual C# > Windows.
From the center pane, select the Blank App (Universal Windows) template
From the center pane, select the Blank App (Universal Windows) template
Give a name to the project by writing UWPHelloWorld in the Name field.
Give a name to the project by writing UWPHelloWorld in the Name field.
Click OK to create a new UWP project.
Click OK to create a new UWP project.
You can see the newly created project in the Solution Explorer.
You can see the newly created project in the Solution Explorer.
This is a blank app but it contains many files, which is the minimum requirement for any UWP application.
This is a blank app but it contains many files, which is the minimum requirement for any UWP application.
MainPage.xaml and MainPage.xaml.cs run when you execute your application.
MainPage.xaml and MainPage.xaml.cs run when you execute your application.
By default, MainPage.xaml file contains the following information.
By default, MainPage.xaml file contains the following information.
<Page
x:Class = ”UWPHellowWorld.MainPage”
xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local = ”using:UWPHellowWorld”
xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable = ”d”>
<Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”>
</Grid>
</Page>
Given below is the default information available in MainPage.xaml.cs.
Given below is the default information available in MainPage.xaml.cs.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at
http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWPHellowWorld {
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page {
public MainPage(){
this.InitializeComponent();
}
}
}
Let us add some Text Blocks, a textbox, and a button as shown in the XAML code below.
Let us add some Text Blocks, a textbox, and a button as shown in the XAML code below.
<Page
x:Class = ”UWPHellowWorld.MainPage”
xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local = ”using:UWPHellowWorld”
xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable = ”d”>
<Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”>
<StackPanel HorizontalAlignment = ”Center”>
<TextBlock Text = ”Hello, world!” Margin = ”20” Width = ”200”
HorizontalAlignment = ”Left”/>
<TextBlock Text = ”Write your name.” Margin = ”20” Width = ”200”
HorizontalAlignment = ”Left”/>
<TextBox x:Name = ”txtbox” Width = ”280” Margin = ”20”
HorizontalAlignment = ”Left”/>
<Button x:Name = ”button” Content = ”Click Me” Margin = ”20”
Click = ”button_Click”/>
<TextBlock x:Name = ”txtblock” HorizontalAlignment = ”Left”
Margin = ”20”/>
</StackPanel>
</Grid>
</Page>
Given below is the click-event button in C#.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at
http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWPHellowWorld {
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e) {
if (txtbox.Text != “”)
txtblock.Text = “Hello: “ + txtbox.Text;
else
txtblock.Text = “You have not write your name”;
}
}
}
In the UWP project, device preview option is available on the Design Window, with the help of which you can change the layout easily, to fit into the screen size of all the devices in a device family you are targeting for your application.
In the UWP project, device preview option is available on the Design Window, with the help of which you can change the layout easily, to fit into the screen size of all the devices in a device family you are targeting for your application.
You can run and test your app either on a local machine, a simulator or an emulator, or on a remote device. You can select the target device from the following menu as shown below −
You can run and test your app either on a local machine, a simulator or an emulator, or on a remote device. You can select the target device from the following menu as shown below −
Let us run the above code on a local machine and you will see the following window. Now, write any name in the text box and click the button Click Me.
Let us run the above code on a local machine and you will see the following window. Now, write any name in the text box and click the button Click Me.
Now, if you want to test your app on an emulator, you can select a particular emulator from the menu and execute your application. You will see the following emulator −
Now, if you want to test your app on an emulator, you can select a particular emulator from the menu and execute your application. You will see the following emulator −
We recommend you to execute the above application with different devices.
23 Lectures
2 hours
Pavan Lalwani
37 Lectures
13 hours
Trevoir Williams
46 Lectures
3.5 hours
Fettah Ben
55 Lectures
6 hours
Total Seminars
20 Lectures
2.5 hours
Brandon Dennis
52 Lectures
9 hours
Fabrice Chrzanowski
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2557,
"s": 2284,
"text": "In this chapter, we will be creating our first simple application \"Hello world\" in Universal Windows Platform (UWP) using XAML and C# on Windows 10. We will demonstrate how a single UWP application created in Visual Studio can be run and executed on any Windows 10 device."
},
{
"code": null,
"e": 2623,
"s": 2557,
"text": "Let us start creating the App by following the steps given below."
},
{
"code": null,
"e": 2650,
"s": 2623,
"text": "Launch Visual Studio 2015."
},
{
"code": null,
"e": 2677,
"s": 2650,
"text": "Launch Visual Studio 2015."
},
{
"code": null,
"e": 2726,
"s": 2677,
"text": "Click on the File menu and select New > Project."
},
{
"code": null,
"e": 2775,
"s": 2726,
"text": "Click on the File menu and select New > Project."
},
{
"code": null,
"e": 2915,
"s": 2775,
"text": "The following New Project dialog window will be displayed. You can see the different types of templates on the left pane of the dialog box."
},
{
"code": null,
"e": 3055,
"s": 2915,
"text": "The following New Project dialog window will be displayed. You can see the different types of templates on the left pane of the dialog box."
},
{
"code": null,
"e": 3164,
"s": 3055,
"text": "In the left pane, you can see the tree view. Select Universal template from Templates > Visual C# > Windows."
},
{
"code": null,
"e": 3273,
"s": 3164,
"text": "In the left pane, you can see the tree view. Select Universal template from Templates > Visual C# > Windows."
},
{
"code": null,
"e": 3345,
"s": 3273,
"text": "From the center pane, select the Blank App (Universal Windows) template"
},
{
"code": null,
"e": 3417,
"s": 3345,
"text": "From the center pane, select the Blank App (Universal Windows) template"
},
{
"code": null,
"e": 3488,
"s": 3417,
"text": "Give a name to the project by writing UWPHelloWorld in the Name field."
},
{
"code": null,
"e": 3559,
"s": 3488,
"text": "Give a name to the project by writing UWPHelloWorld in the Name field."
},
{
"code": null,
"e": 3597,
"s": 3559,
"text": "Click OK to create a new UWP project."
},
{
"code": null,
"e": 3635,
"s": 3597,
"text": "Click OK to create a new UWP project."
},
{
"code": null,
"e": 3699,
"s": 3635,
"text": "You can see the newly created project in the Solution Explorer."
},
{
"code": null,
"e": 3763,
"s": 3699,
"text": "You can see the newly created project in the Solution Explorer."
},
{
"code": null,
"e": 3869,
"s": 3763,
"text": "This is a blank app but it contains many files, which is the minimum requirement for any UWP application."
},
{
"code": null,
"e": 3975,
"s": 3869,
"text": "This is a blank app but it contains many files, which is the minimum requirement for any UWP application."
},
{
"code": null,
"e": 4049,
"s": 3975,
"text": "MainPage.xaml and MainPage.xaml.cs run when you execute your application."
},
{
"code": null,
"e": 4123,
"s": 4049,
"text": "MainPage.xaml and MainPage.xaml.cs run when you execute your application."
},
{
"code": null,
"e": 4190,
"s": 4123,
"text": "By default, MainPage.xaml file contains the following information."
},
{
"code": null,
"e": 4257,
"s": 4190,
"text": "By default, MainPage.xaml file contains the following information."
},
{
"code": null,
"e": 4747,
"s": 4257,
"text": "<Page \n x:Class = ”UWPHellowWorld.MainPage” \n xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation” \n xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml” \n xmlns:local = ”using:UWPHellowWorld” \n xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008” \n xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006” \n mc:Ignorable = ”d”> \n\t\n <Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”>\n </Grid>\n\t\n</Page>"
},
{
"code": null,
"e": 4817,
"s": 4747,
"text": "Given below is the default information available in MainPage.xaml.cs."
},
{
"code": null,
"e": 4887,
"s": 4817,
"text": "Given below is the default information available in MainPage.xaml.cs."
},
{
"code": null,
"e": 5719,
"s": 4887,
"text": "using System; \nusing System.Collections.Generic; \nusing System.IO; \nusing System.Linq; \nusing System.Runtime.InteropServices.WindowsRuntime; \n\nusing Windows.Foundation; \nusing Windows.Foundation.Collections; \n\nusing Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls; \nusing Windows.UI.Xaml.Controls.Primitives; \nusing Windows.UI.Xaml.Data; \nusing Windows.UI.Xaml.Input; \nusing Windows.UI.Xaml.Media; \nusing Windows.UI.Xaml.Navigation;\n\n// The Blank Page item template is documented at \n http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409\n\nnamespace UWPHellowWorld {\n \n /// <summary> \n /// An empty page that can be used on its own or navigated to within a Frame. \n /// </summary> \n\t\n public sealed partial class MainPage : Page {\n public MainPage(){ \n this.InitializeComponent(); \n } \n } \n\t\n}"
},
{
"code": null,
"e": 5805,
"s": 5719,
"text": "Let us add some Text Blocks, a textbox, and a button as shown in the XAML code below."
},
{
"code": null,
"e": 5891,
"s": 5805,
"text": "Let us add some Text Blocks, a textbox, and a button as shown in the XAML code below."
},
{
"code": null,
"e": 7037,
"s": 5891,
"text": "<Page \n x:Class = ”UWPHellowWorld.MainPage” \n xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation” \n xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml” \n xmlns:local = ”using:UWPHellowWorld” \n xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008”\n xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006” \n mc:Ignorable = ”d”> \n \n <Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”> \n\t\n <StackPanel HorizontalAlignment = ”Center”> \n <TextBlock Text = ”Hello, world!” Margin = ”20” Width = ”200” \n HorizontalAlignment = ”Left”/> \n\t\t\t\t\n <TextBlock Text = ”Write your name.” Margin = ”20” Width = ”200” \n HorizontalAlignment = ”Left”/> \n\t\t\t\t\n <TextBox x:Name = ”txtbox” Width = ”280” Margin = ”20” \n HorizontalAlignment = ”Left”/> \n\t\t\t\t\n <Button x:Name = ”button” Content = ”Click Me” Margin = ”20” \n Click = ”button_Click”/> \n\t\t\t\t\n <TextBlock x:Name = ”txtblock” HorizontalAlignment = ”Left” \n Margin = ”20”/> \n </StackPanel> \n\t\t\n </Grid> \n\t\n</Page> "
},
{
"code": null,
"e": 7082,
"s": 7037,
"text": "Given below is the click-event button in C#."
},
{
"code": null,
"e": 8163,
"s": 7082,
"text": "using System; \nusing System.Collections.Generic; \nusing System.IO; \nusing System.Linq; \n\nusing System.Runtime.InteropServices.WindowsRuntime; \nusing Windows.Foundation; \nusing Windows.Foundation.Collections;\n \nusing Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls; \nusing Windows.UI.Xaml.Controls.Primitives; \nusing Windows.UI.Xaml.Data; \nusing Windows.UI.Xaml.Input; \nusing Windows.UI.Xaml.Media; \nusing Windows.UI.Xaml.Navigation; \n \n// The Blank Page item template is documented at\n http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 \n\nnamespace UWPHellowWorld {\n\n /// <summary> \n /// An empty page that can be used on its own or navigated to within a Frame. \n /// </summary> \n\t\n public sealed partial class MainPage : Page {\n public MainPage() {\n this.InitializeComponent(); \n } \n\t\t\n private void button_Click(object sender, RoutedEventArgs e) {\n if (txtbox.Text != “”) \n txtblock.Text = “Hello: “ + txtbox.Text; \n else \n txtblock.Text = “You have not write your name”; \n } \n\t\t\n }\t\n\t\n}"
},
{
"code": null,
"e": 8403,
"s": 8163,
"text": "In the UWP project, device preview option is available on the Design Window, with the help of which you can change the layout easily, to fit into the screen size of all the devices in a device family you are targeting for your application."
},
{
"code": null,
"e": 8643,
"s": 8403,
"text": "In the UWP project, device preview option is available on the Design Window, with the help of which you can change the layout easily, to fit into the screen size of all the devices in a device family you are targeting for your application."
},
{
"code": null,
"e": 8825,
"s": 8643,
"text": "You can run and test your app either on a local machine, a simulator or an emulator, or on a remote device. You can select the target device from the following menu as shown below −"
},
{
"code": null,
"e": 9007,
"s": 8825,
"text": "You can run and test your app either on a local machine, a simulator or an emulator, or on a remote device. You can select the target device from the following menu as shown below −"
},
{
"code": null,
"e": 9158,
"s": 9007,
"text": "Let us run the above code on a local machine and you will see the following window. Now, write any name in the text box and click the button Click Me."
},
{
"code": null,
"e": 9309,
"s": 9158,
"text": "Let us run the above code on a local machine and you will see the following window. Now, write any name in the text box and click the button Click Me."
},
{
"code": null,
"e": 9478,
"s": 9309,
"text": "Now, if you want to test your app on an emulator, you can select a particular emulator from the menu and execute your application. You will see the following emulator −"
},
{
"code": null,
"e": 9647,
"s": 9478,
"text": "Now, if you want to test your app on an emulator, you can select a particular emulator from the menu and execute your application. You will see the following emulator −"
},
{
"code": null,
"e": 9721,
"s": 9647,
"text": "We recommend you to execute the above application with different devices."
},
{
"code": null,
"e": 9754,
"s": 9721,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9769,
"s": 9754,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 9803,
"s": 9769,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 9821,
"s": 9803,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 9856,
"s": 9821,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9868,
"s": 9856,
"text": " Fettah Ben"
},
{
"code": null,
"e": 9901,
"s": 9868,
"text": "\n 55 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9917,
"s": 9901,
"text": " Total Seminars"
},
{
"code": null,
"e": 9952,
"s": 9917,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9968,
"s": 9952,
"text": " Brandon Dennis"
},
{
"code": null,
"e": 10001,
"s": 9968,
"text": "\n 52 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 10022,
"s": 10001,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 10029,
"s": 10022,
"text": " Print"
},
{
"code": null,
"e": 10040,
"s": 10029,
"text": " Add Notes"
}
] |
Express as sum of power of natural numbers | Practice | GeeksforGeeks
|
Given two numbers n and x, find out the total number of ways n can be expressed as sum of xth power of unique natural numbers.As total number of ways can be very large ,so return the number of ways modulo 109 + 7.
Example 1:
Input: n = 10, x = 2
Output: 1
Explanation: 10 = 12 + 32, Hence total 1 possibility.
Example 2:
Input: n = 100, x = 2
Output: 3
Explanation: 100 = 102
62 + 82 and 12 + 32 + 42 + 52 + 72
Hence total 3 possibilities.
Your Task:
You dont need to read input or print anything. Complete the function numOfWays() which takes n and x as input parameter and returns the total number of ways n can be expressed as sum of xth power of unique natural numbers.
Expected Time Complexity: O(n2logn)
Expected Auxiliary Space: O(n)
Constraints:
1 <= n <= 103
1 <= x <= 5
0
ksandeep27072 months ago
DP solution:-
class Solution{
public:
int numOfWays(int n, int x)
{
vector<long long int > v(n,0);
for (int i =0; i <n; ++i)
{
v[i]=(long long int)pow(i+1,x);
}
int sum=n;
long long int dp[n+1][sum+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int j=1;j<=sum;j++)
dp[0][j]=0;
for (int i =1; i <=n; ++i)
{
for (int j = 1; j <=sum; ++j)
{
dp[i][j]=dp[i-1][j]%(1000000007);
if(j>=v[i-1])
dp[i][j]=(dp[i][j]+dp[i-1][j-v[i-1]])%(1000000007);
}
}
return dp[n][sum]%(1000000007);
}
};
0
araj2920183 months ago
class Solution{ public: long long int t[1001][1001]; long long int mod=1e9+7; long long int solve(int n,int x,int i){ if(n==0){ return 1; } if(i>n){ return 0; } if(t[n][i]!=-1){ return t[n][i]; } int pa=pow(i,x); if(pa<=n){ return t[n][i]=(solve(n-pa,x,i+1)+solve(n,x,i+1))%mod; } else{ return t[n][i]=0; } } int numOfWays(int n, int x) { memset(t,-1,sizeof(t)); return solve(n,x,1); }};
+2
priyasingh073 months ago
class Solution{
public:
long long int dp[1001][1001];
long long int p=1e9+7;
long long int ans(int n, int x, int i)
{
if(n==0)
return 1;
if(i>n)
return 0;
if(dp[n][i]!=-1)
return (dp[n][i]%p);
long long int t=pow(i,x);
if(t<=n)
{
dp[n][i]=ans(n-t, x, i+1)+ans(n, x, i+1);
return dp[n][i]%p;
}
else
{
dp[n][i]=0;
return dp[n][i]%p;
}
}
long long int numOfWays(int n, int x)
{
// code here
memset(dp, -1, sizeof(dp));
return ans(n, x, 1);
}
};
0
sangamchoudhary73 months ago
Given function code is wrongMod please correct it , that's why people shift toward LeetCode
To prevent overflow → I used long long it
class Solution{
public:
long long int dp[1001][1001];
long long int find(int i,int sum,int limit,int x,int n){
if(i > limit+1) return 0; // as we can't miss the ceil of limit
else if(sum > n) return 0;
else if(dp[i][sum] != -1) return dp[i][sum];
else if(sum == n) return 1;
long long int withPowSum = find(i+1,sum + pow(i,x),limit,x,n);
long long int withoutPowSum = find(i+1,sum,limit,x,n);
return dp[i][sum] = withPowSum + withoutPowSum;
}
long long int numOfWays(int n, int x){
int limit = pow(n,1.0/x);
memset(dp,-1,sizeof dp);
return find(1,0,limit,x,n);
}
};
0
vankshu593 months ago
Use long long to prevent overflow
TC: O(N N^(1/x) * log(x))
class Solution {
vector<vector<long long>> dp;
public:
long long numOfWays(long long n, int x) {
int num = pow(n, 1.0 / x);
dp.resize(n + 1, vector<long long>(num + 1, -1));
return util(n, x, num);
}
long long util(int n, int x, int curr) {
if(n == 0) return 1;
else if(curr == 0) return 0;
long long &ans = dp[n][curr];
if(ans != -1) return ans;
long long power = pow(curr, x);
return ans = (n - power >= 0 ? util(n - power, x, curr - 1): 0) + util(n, x, curr - 1);
}
};
0
kh4bnl3wsyyoqfbgviezyy2frk58ob5nee8ixigi
This comment was deleted.
0
wallflower9 months ago
wallflower
Backtracking solution. Find all numbers from 1 to n powered to x. And then backtrack to find all possible solutions.
https://ide.geeksforgeeks.o...
+4
Bharat Gupta1 year ago
Bharat Gupta
long long numOfWays(int n, int x) { // Here, dp[i] represents number of ways to represent i long long dp[n+1]; memset(dp, 0, sizeof(dp)); // Always 1 way to represent 0 or 1 // as sum of powers of natural numbers dp[0] = dp[1] = 1; // For n == 10 and x == 2, we will only try till 3^2 // else, the sum will exceed n int maxLimit = pow(n, 1.0/x); for(int i = 2; i <= maxLimit; i++){ int curr = pow(i, x); // Same as "include" condition in recursive code // and since, we are running a loop from i to maxLimit // the "exclude" condition is also handled. for(int j = n; j >= curr; j--){ dp[j] += dp[j-curr]; } } return dp[n]; }
+2
niffoxic1 year ago
niffoxic
Why its saying use Dp if the topic tags says Recursion ?!
+5
aadi1551 year ago
aadi155
return type should be long int otherwise it will give wrong answer.@moderator please look into the issue.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 465,
"s": 238,
"text": "Given two numbers n and x, find out the total number of ways n can be expressed as sum of xth power of unique natural numbers.As total number of ways can be very large ,so return the number of ways modulo 109 + 7. \n\nExample 1:"
},
{
"code": null,
"e": 553,
"s": 465,
"text": "Input: n = 10, x = 2\nOutput: 1 \nExplanation: 10 = 12 + 32, Hence total 1 possibility. \n"
},
{
"code": null,
"e": 565,
"s": 553,
"text": "\nExample 2:"
},
{
"code": null,
"e": 688,
"s": 565,
"text": "Input: n = 100, x = 2\nOutput: 3\nExplanation: 100 = 102 \n62 + 82 and 12 + 32 + 42 + 52 + 72 \nHence total 3 possibilities. \n"
},
{
"code": null,
"e": 1033,
"s": 688,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function numOfWays() which takes n and x as input parameter and returns the total number of ways n can be expressed as sum of xth power of unique natural numbers.\n\nExpected Time Complexity: O(n2logn)\nExpected Auxiliary Space: O(n)\n\nConstraints:\n1 <= n <= 103\n1 <= x <= 5"
},
{
"code": null,
"e": 1035,
"s": 1033,
"text": "0"
},
{
"code": null,
"e": 1060,
"s": 1035,
"text": "ksandeep27072 months ago"
},
{
"code": null,
"e": 1074,
"s": 1060,
"text": "DP solution:-"
},
{
"code": null,
"e": 1739,
"s": 1074,
"text": "class Solution{\n public:\n int numOfWays(int n, int x)\n {\n vector<long long int > v(n,0);\n \n for (int i =0; i <n; ++i)\n {\n v[i]=(long long int)pow(i+1,x);\n }\n int sum=n;\n long long int dp[n+1][sum+1];\n\n for(int i=0;i<=n;i++)\n dp[i][0]=1;\n for(int j=1;j<=sum;j++)\n dp[0][j]=0;\n\n for (int i =1; i <=n; ++i)\n {\n for (int j = 1; j <=sum; ++j)\n {\n dp[i][j]=dp[i-1][j]%(1000000007);\n if(j>=v[i-1])\n dp[i][j]=(dp[i][j]+dp[i-1][j-v[i-1]])%(1000000007);\n }\n }\n return dp[n][sum]%(1000000007);\n }\n};"
},
{
"code": null,
"e": 1741,
"s": 1739,
"text": "0"
},
{
"code": null,
"e": 1764,
"s": 1741,
"text": "araj2920183 months ago"
},
{
"code": null,
"e": 2325,
"s": 1764,
"text": "class Solution{ public: long long int t[1001][1001]; long long int mod=1e9+7; long long int solve(int n,int x,int i){ if(n==0){ return 1; } if(i>n){ return 0; } if(t[n][i]!=-1){ return t[n][i]; } int pa=pow(i,x); if(pa<=n){ return t[n][i]=(solve(n-pa,x,i+1)+solve(n,x,i+1))%mod; } else{ return t[n][i]=0; } } int numOfWays(int n, int x) { memset(t,-1,sizeof(t)); return solve(n,x,1); }};"
},
{
"code": null,
"e": 2328,
"s": 2325,
"text": "+2"
},
{
"code": null,
"e": 2353,
"s": 2328,
"text": "priyasingh073 months ago"
},
{
"code": null,
"e": 3007,
"s": 2353,
"text": "class Solution{\n public:\n long long int dp[1001][1001];\n long long int p=1e9+7;\n long long int ans(int n, int x, int i)\n {\n if(n==0)\n return 1;\n if(i>n)\n return 0;\n if(dp[n][i]!=-1)\n return (dp[n][i]%p);\n long long int t=pow(i,x);\n if(t<=n)\n {\n dp[n][i]=ans(n-t, x, i+1)+ans(n, x, i+1);\n return dp[n][i]%p;\n }\n else\n {\n dp[n][i]=0;\n return dp[n][i]%p;\n }\n }\n long long int numOfWays(int n, int x)\n {\n // code here\n memset(dp, -1, sizeof(dp));\n return ans(n, x, 1);\n }\n};"
},
{
"code": null,
"e": 3009,
"s": 3007,
"text": "0"
},
{
"code": null,
"e": 3038,
"s": 3009,
"text": "sangamchoudhary73 months ago"
},
{
"code": null,
"e": 3130,
"s": 3038,
"text": "Given function code is wrongMod please correct it , that's why people shift toward LeetCode"
},
{
"code": null,
"e": 3172,
"s": 3130,
"text": "To prevent overflow → I used long long it"
},
{
"code": null,
"e": 3915,
"s": 3172,
"text": "class Solution{\n public:\n long long int dp[1001][1001];\n long long int find(int i,int sum,int limit,int x,int n){\n if(i > limit+1) return 0; // as we can't miss the ceil of limit\n \n else if(sum > n) return 0;\n \n else if(dp[i][sum] != -1) return dp[i][sum];\n \n else if(sum == n) return 1;\n \n long long int withPowSum = find(i+1,sum + pow(i,x),limit,x,n); \n \n long long int withoutPowSum = find(i+1,sum,limit,x,n);\n \n return dp[i][sum] = withPowSum + withoutPowSum;\n }\n \n long long int numOfWays(int n, int x){\n int limit = pow(n,1.0/x);\n memset(dp,-1,sizeof dp);\n return find(1,0,limit,x,n);\n }\n};"
},
{
"code": null,
"e": 3917,
"s": 3915,
"text": "0"
},
{
"code": null,
"e": 3939,
"s": 3917,
"text": "vankshu593 months ago"
},
{
"code": null,
"e": 3973,
"s": 3939,
"text": "Use long long to prevent overflow"
},
{
"code": null,
"e": 4001,
"s": 3973,
"text": "TC: O(N N^(1/x) * log(x))"
},
{
"code": null,
"e": 4572,
"s": 4001,
"text": "class Solution {\n vector<vector<long long>> dp;\n public:\n long long numOfWays(long long n, int x) {\n int num = pow(n, 1.0 / x);\n dp.resize(n + 1, vector<long long>(num + 1, -1));\n return util(n, x, num);\n }\n \n long long util(int n, int x, int curr) {\n if(n == 0) return 1;\n else if(curr == 0) return 0;\n long long &ans = dp[n][curr];\n if(ans != -1) return ans;\n long long power = pow(curr, x);\n return ans = (n - power >= 0 ? util(n - power, x, curr - 1): 0) + util(n, x, curr - 1);\n }\n};"
},
{
"code": null,
"e": 4574,
"s": 4572,
"text": "0"
},
{
"code": null,
"e": 4615,
"s": 4574,
"text": "kh4bnl3wsyyoqfbgviezyy2frk58ob5nee8ixigi"
},
{
"code": null,
"e": 4641,
"s": 4615,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4643,
"s": 4641,
"text": "0"
},
{
"code": null,
"e": 4666,
"s": 4643,
"text": "wallflower9 months ago"
},
{
"code": null,
"e": 4677,
"s": 4666,
"text": "wallflower"
},
{
"code": null,
"e": 4794,
"s": 4677,
"text": "Backtracking solution. Find all numbers from 1 to n powered to x. And then backtrack to find all possible solutions."
},
{
"code": null,
"e": 4825,
"s": 4794,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4828,
"s": 4825,
"text": "+4"
},
{
"code": null,
"e": 4851,
"s": 4828,
"text": "Bharat Gupta1 year ago"
},
{
"code": null,
"e": 4864,
"s": 4851,
"text": "Bharat Gupta"
},
{
"code": null,
"e": 5700,
"s": 4864,
"text": " long long numOfWays(int n, int x) { // Here, dp[i] represents number of ways to represent i long long dp[n+1]; memset(dp, 0, sizeof(dp)); // Always 1 way to represent 0 or 1 // as sum of powers of natural numbers dp[0] = dp[1] = 1; // For n == 10 and x == 2, we will only try till 3^2 // else, the sum will exceed n int maxLimit = pow(n, 1.0/x); for(int i = 2; i <= maxLimit; i++){ int curr = pow(i, x); // Same as \"include\" condition in recursive code // and since, we are running a loop from i to maxLimit // the \"exclude\" condition is also handled. for(int j = n; j >= curr; j--){ dp[j] += dp[j-curr]; } } return dp[n]; }"
},
{
"code": null,
"e": 5703,
"s": 5700,
"text": "+2"
},
{
"code": null,
"e": 5722,
"s": 5703,
"text": "niffoxic1 year ago"
},
{
"code": null,
"e": 5731,
"s": 5722,
"text": "niffoxic"
},
{
"code": null,
"e": 5789,
"s": 5731,
"text": "Why its saying use Dp if the topic tags says Recursion ?!"
},
{
"code": null,
"e": 5792,
"s": 5789,
"text": "+5"
},
{
"code": null,
"e": 5810,
"s": 5792,
"text": "aadi1551 year ago"
},
{
"code": null,
"e": 5818,
"s": 5810,
"text": "aadi155"
},
{
"code": null,
"e": 5925,
"s": 5818,
"text": "return type should be long int otherwise it will give wrong answer.@moderator please look into the issue."
},
{
"code": null,
"e": 6071,
"s": 5925,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6107,
"s": 6071,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6117,
"s": 6107,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6127,
"s": 6117,
"text": "\nContest\n"
},
{
"code": null,
"e": 6190,
"s": 6127,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6338,
"s": 6190,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6546,
"s": 6338,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6652,
"s": 6546,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
5-Minute Guide to Calling Functions from R Scripts | by Emily A. Halford | Towards Data Science
|
You’ve likely heard the popular guideline that if you find yourself copying and pasting code more than 3 times, you should write it as a function. While you can write and store these functions at the top of your R Markdown files, this approach can get messy and is counterproductive if you end up copying and pasting the functions into multiple files. Often, the best way to stay organized is to write your functions in a script and to call them from any additional files where they’re needed.
To demonstrate this process, I will use 3 functions to conduct a very simple change point analysis of Google searches containing the words “supreme court” over the past month.
In an R script, we write three simple functions. The first plots the Google Trends data, the second performs a simple change point analysis using the bcp() function from the “bcp” package, and the third plots the results of this analysis.
google_graph = function(data, date, observation, graph_title) { data %>% ggplot() + geom_line(aes(x = date, y = observation), color = "#09557f", alpha = 0.6, size = 0.6) + labs(x = "Date (Start of Week)", y = "Relative Proportion", title = graph_title) + theme_minimal() + scale_x_date(date_breaks = "1 week") + theme(axis.text.x = element_text(angle = 45)) }bcp_analysis = function(observation, data) { set.seed(100) bcp = bcp(observation) prob = bcp$posterior.prob prob = as.data.frame(prob) bcp_dataframe = cbind(data, prob) %>% select(date, prob) }bcp_plot = function(dataframe){ dataframe %>% ggplot() + geom_line(aes(x = date, y = prob), color = "#09557f", alpha = 0.6, size = 0.6) + labs(x = "", y = "Posterior Probability", title = "Changepoint Probabilities") + theme_minimal() + ylim(0, 1) + scale_x_date(date_breaks = "1 week") + theme(axis.text.x = element_text(angle = 45)) }
I’ve also checked this “Source on Save” box. If you check this box, then the file will be sourced automatically to the global environment when you save changes to your functions in the script.
Connecting to functions stored in a script from an R Markdown file is very similar to connecting to functions stored in a package. Instead of using a library() statement, we use a source() statement and indicate the script’s path name. In this case, we use the following code:
source("./functions.R")
When we run this line of code, the functions contained within the script automatically appear in the Global Environment. The connection was successful!
First, we’ll just use the gtrends() function from the “gtrendsR” package to pull Google search volume for searches containing the words “supreme court” in the United States over the past month. A mutate step is also used to convert the “date” variable to a date format:
data = gtrends(keyword = "supreme court", geo = "US", time = "today 1-m")$interest_over_time %>% mutate(date = as.Date(date))
Now we have data to use in our functions! We use the google_graph() function the same way we would use any other function, allowing us to easily plot the data:
google_graph(data, data$date, data$hits, ‘Google Searches for “Supreme Court”’)
The plot looks good! Unsurprisingly, there is a massive surge in searches containing “supreme court” following the death of Supreme Court Justice Ruth Bader Ginsburg. Let’s use the bcp_analysis() and bcp_plot() functions to see if this spike represents a significant change point in this time-series object. Again, we use the functions the same way we would if we were using functions from a loaded package:
bcp_dataframe = bcp_analysis(data$hits, data)bcp_plot(bcp_dataframe)
Several days following the death of Ruth Bader Ginsburg have posterior probabilities of 1.00, indicating that searches containing the words “supreme court” likely changed in a statistically meaningful way around this time.
It’s as simple as that! If we wanted to plot and analyze several different sources of data in separate Rmd files, it would be as easy as connecting those files to our “functions” script with a source() statement and using our functions.
|
[
{
"code": null,
"e": 666,
"s": 172,
"text": "You’ve likely heard the popular guideline that if you find yourself copying and pasting code more than 3 times, you should write it as a function. While you can write and store these functions at the top of your R Markdown files, this approach can get messy and is counterproductive if you end up copying and pasting the functions into multiple files. Often, the best way to stay organized is to write your functions in a script and to call them from any additional files where they’re needed."
},
{
"code": null,
"e": 842,
"s": 666,
"text": "To demonstrate this process, I will use 3 functions to conduct a very simple change point analysis of Google searches containing the words “supreme court” over the past month."
},
{
"code": null,
"e": 1081,
"s": 842,
"text": "In an R script, we write three simple functions. The first plots the Google Trends data, the second performs a simple change point analysis using the bcp() function from the “bcp” package, and the third plots the results of this analysis."
},
{
"code": null,
"e": 2150,
"s": 1081,
"text": "google_graph = function(data, date, observation, graph_title) { data %>% ggplot() + geom_line(aes(x = date, y = observation), color = \"#09557f\", alpha = 0.6, size = 0.6) + labs(x = \"Date (Start of Week)\", y = \"Relative Proportion\", title = graph_title) + theme_minimal() + scale_x_date(date_breaks = \"1 week\") + theme(axis.text.x = element_text(angle = 45)) }bcp_analysis = function(observation, data) { set.seed(100) bcp = bcp(observation) prob = bcp$posterior.prob prob = as.data.frame(prob) bcp_dataframe = cbind(data, prob) %>% select(date, prob) }bcp_plot = function(dataframe){ dataframe %>% ggplot() + geom_line(aes(x = date, y = prob), color = \"#09557f\", alpha = 0.6, size = 0.6) + labs(x = \"\", y = \"Posterior Probability\", title = \"Changepoint Probabilities\") + theme_minimal() + ylim(0, 1) + scale_x_date(date_breaks = \"1 week\") + theme(axis.text.x = element_text(angle = 45)) }"
},
{
"code": null,
"e": 2343,
"s": 2150,
"text": "I’ve also checked this “Source on Save” box. If you check this box, then the file will be sourced automatically to the global environment when you save changes to your functions in the script."
},
{
"code": null,
"e": 2620,
"s": 2343,
"text": "Connecting to functions stored in a script from an R Markdown file is very similar to connecting to functions stored in a package. Instead of using a library() statement, we use a source() statement and indicate the script’s path name. In this case, we use the following code:"
},
{
"code": null,
"e": 2644,
"s": 2620,
"text": "source(\"./functions.R\")"
},
{
"code": null,
"e": 2796,
"s": 2644,
"text": "When we run this line of code, the functions contained within the script automatically appear in the Global Environment. The connection was successful!"
},
{
"code": null,
"e": 3066,
"s": 2796,
"text": "First, we’ll just use the gtrends() function from the “gtrendsR” package to pull Google search volume for searches containing the words “supreme court” in the United States over the past month. A mutate step is also used to convert the “date” variable to a date format:"
},
{
"code": null,
"e": 3209,
"s": 3066,
"text": "data = gtrends(keyword = \"supreme court\", geo = \"US\", time = \"today 1-m\")$interest_over_time %>% mutate(date = as.Date(date))"
},
{
"code": null,
"e": 3369,
"s": 3209,
"text": "Now we have data to use in our functions! We use the google_graph() function the same way we would use any other function, allowing us to easily plot the data:"
},
{
"code": null,
"e": 3449,
"s": 3369,
"text": "google_graph(data, data$date, data$hits, ‘Google Searches for “Supreme Court”’)"
},
{
"code": null,
"e": 3857,
"s": 3449,
"text": "The plot looks good! Unsurprisingly, there is a massive surge in searches containing “supreme court” following the death of Supreme Court Justice Ruth Bader Ginsburg. Let’s use the bcp_analysis() and bcp_plot() functions to see if this spike represents a significant change point in this time-series object. Again, we use the functions the same way we would if we were using functions from a loaded package:"
},
{
"code": null,
"e": 3926,
"s": 3857,
"text": "bcp_dataframe = bcp_analysis(data$hits, data)bcp_plot(bcp_dataframe)"
},
{
"code": null,
"e": 4149,
"s": 3926,
"text": "Several days following the death of Ruth Bader Ginsburg have posterior probabilities of 1.00, indicating that searches containing the words “supreme court” likely changed in a statistically meaningful way around this time."
}
] |
Applications of Pointers in C/C++
|
We can access array elements by using pointers.
Live Demo
#include <stdio.h>
int main() {
int a[] = { 60, 70, 20, 40 };
printf("%d\n", *(a + 1));
return 0;
}
70
Live Demo
#include <iostream>
using namespace std;
int main() {
int a[] = { 60, 70, 20, 40 };
cout<<*(a + 1);
return 0;
}
70
To dynamically allocate memory we use pointers.
Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
*(ptr+0)=1;
*(ptr+1)=2;
*(ptr+2)=3;
printf("Elements are:");
for(i = 0; i < 3; i++) {
printf("%d ", *(ptr + i));
}
free(ptr);
return 0;
}
Elements are:1 2 3
Live Demo
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int i, *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
cout<<"Error! memory not allocated.";
exit(0);
}
*(ptr+0)=1;
*(ptr+1)=2;
*(ptr+2)=3;
cout<<"Elements are:";
for(i = 0; i < 3; i++) {
cout<< *(ptr + i);
}
free(ptr);
return 0;
}
Elements are:1 2 3
We can use pointers to pass arguments by reference in functions to increase efficiency.
Live Demo
#include <stdio.h>
void swap(int* a, int* b) {
int t= *a;
*a= *b;
*b = t;
}
int main() {
int m = 7, n= 6;
swap(&m, &n);
printf("%d %d\n", m, n);
return 0;
}
6 7
Live Demo
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int t= *a;
*a= *b;
*b = t;
}
int main() {
int m = 7, n= 6;
swap(&m, &n);
cout<< m<<n;
return 0;
}
67
To implement data structures like linked list, tree we can use pointers also.
|
[
{
"code": null,
"e": 1110,
"s": 1062,
"text": "We can access array elements by using pointers."
},
{
"code": null,
"e": 1121,
"s": 1110,
"text": " Live Demo"
},
{
"code": null,
"e": 1230,
"s": 1121,
"text": "#include <stdio.h>\nint main() {\n int a[] = { 60, 70, 20, 40 };\n printf(\"%d\\n\", *(a + 1));\n return 0;\n}"
},
{
"code": null,
"e": 1233,
"s": 1230,
"text": "70"
},
{
"code": null,
"e": 1244,
"s": 1233,
"text": " Live Demo"
},
{
"code": null,
"e": 1365,
"s": 1244,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int a[] = { 60, 70, 20, 40 };\n cout<<*(a + 1);\n return 0;\n}"
},
{
"code": null,
"e": 1368,
"s": 1365,
"text": "70"
},
{
"code": null,
"e": 1416,
"s": 1368,
"text": "To dynamically allocate memory we use pointers."
},
{
"code": null,
"e": 1427,
"s": 1416,
"text": " Live Demo"
},
{
"code": null,
"e": 1791,
"s": 1427,
"text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int i, *ptr;\n ptr = (int*) malloc(3 * sizeof(int));\n if(ptr == NULL) {\n printf(\"Error! memory not allocated.\");\n exit(0);\n }\n *(ptr+0)=1;\n *(ptr+1)=2;\n *(ptr+2)=3;\n printf(\"Elements are:\");\n for(i = 0; i < 3; i++) {\n printf(\"%d \", *(ptr + i));\n }\n free(ptr);\n return 0;\n}"
},
{
"code": null,
"e": 1810,
"s": 1791,
"text": "Elements are:1 2 3"
},
{
"code": null,
"e": 1821,
"s": 1810,
"text": " Live Demo"
},
{
"code": null,
"e": 2195,
"s": 1821,
"text": "#include <iostream>\n#include <stdlib.h>\nusing namespace std;\nint main() {\n int i, *ptr;\n ptr = (int*) malloc(3 * sizeof(int));\n if(ptr == NULL) {\n cout<<\"Error! memory not allocated.\";\n exit(0);\n }\n *(ptr+0)=1;\n *(ptr+1)=2;\n *(ptr+2)=3;\n cout<<\"Elements are:\";\n for(i = 0; i < 3; i++) {\n cout<< *(ptr + i);\n }\n free(ptr);\n return 0;\n}"
},
{
"code": null,
"e": 2214,
"s": 2195,
"text": "Elements are:1 2 3"
},
{
"code": null,
"e": 2302,
"s": 2214,
"text": "We can use pointers to pass arguments by reference in functions to increase efficiency."
},
{
"code": null,
"e": 2313,
"s": 2302,
"text": " Live Demo"
},
{
"code": null,
"e": 2491,
"s": 2313,
"text": "#include <stdio.h>\nvoid swap(int* a, int* b) {\n int t= *a;\n *a= *b;\n *b = t;\n}\nint main() {\n int m = 7, n= 6;\n swap(&m, &n);\n printf(\"%d %d\\n\", m, n);\n return 0;\n}"
},
{
"code": null,
"e": 2495,
"s": 2491,
"text": "6 7"
},
{
"code": null,
"e": 2506,
"s": 2495,
"text": " Live Demo"
},
{
"code": null,
"e": 2694,
"s": 2506,
"text": "#include <iostream>\nusing namespace std;\nvoid swap(int* a, int* b) {\n int t= *a;\n *a= *b;\n *b = t;\n}\nint main() {\n int m = 7, n= 6;\n swap(&m, &n);\n cout<< m<<n;\n return 0;\n}"
},
{
"code": null,
"e": 2697,
"s": 2694,
"text": "67"
},
{
"code": null,
"e": 2775,
"s": 2697,
"text": "To implement data structures like linked list, tree we can use pointers also."
}
] |
Convert an Iterator to Stream in Java
|
11 Dec, 2018
Given an Iterator, the task is to convert it into Stream in Java.
Examples:
Input: Iterator = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}
Input: Iterator = {'G', 'e', 'e', 'k', 's'}
Output: {'G', 'e', 'e', 'k', 's'}
Approach:
Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.Return the stream.
Get the Iterator.
Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.
Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
Return the stream.
Below is the implementation of the above approach:
// Java program to get a Stream// from a given Iterator import java.util.*;import java.util.stream.*; class GFG { // Function to get the Stream public static <T> Stream<T> getStreamFromIterator(Iterator<T> iterator) { // Convert the iterator to Spliterator Spliterator<T> spliterator = Spliterators .spliteratorUnknownSize(iterator, 0); // Get a Sequential Stream from spliterator return StreamSupport.stream(spliterator, false); } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Stream from the Iterator Stream<Integer> stream = getStreamFromIterator(iterator); // Print the elements of stream stream.forEach(s -> System.out.println(s)); }}
1
2
3
4
5
Java - util package
Java-Iterator
java-stream
Java-Stream-programs
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": "\n11 Dec, 2018"
},
{
"code": null,
"e": 94,
"s": 28,
"text": "Given an Iterator, the task is to convert it into Stream in Java."
},
{
"code": null,
"e": 104,
"s": 94,
"text": "Examples:"
},
{
"code": null,
"e": 242,
"s": 104,
"text": "Input: Iterator = {1, 2, 3, 4, 5}\nOutput: {1, 2, 3, 4, 5}\n\nInput: Iterator = {'G', 'e', 'e', 'k', 's'}\nOutput: {'G', 'e', 'e', 'k', 's'}\n"
},
{
"code": null,
"e": 252,
"s": 242,
"text": "Approach:"
},
{
"code": null,
"e": 465,
"s": 252,
"text": "Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.Return the stream."
},
{
"code": null,
"e": 483,
"s": 465,
"text": "Get the Iterator."
},
{
"code": null,
"e": 571,
"s": 483,
"text": "Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method."
},
{
"code": null,
"e": 662,
"s": 571,
"text": "Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method."
},
{
"code": null,
"e": 681,
"s": 662,
"text": "Return the stream."
},
{
"code": null,
"e": 732,
"s": 681,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a Stream// from a given Iterator import java.util.*;import java.util.stream.*; class GFG { // Function to get the Stream public static <T> Stream<T> getStreamFromIterator(Iterator<T> iterator) { // Convert the iterator to Spliterator Spliterator<T> spliterator = Spliterators .spliteratorUnknownSize(iterator, 0); // Get a Sequential Stream from spliterator return StreamSupport.stream(spliterator, false); } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Stream from the Iterator Stream<Integer> stream = getStreamFromIterator(iterator); // Print the elements of stream stream.forEach(s -> System.out.println(s)); }}",
"e": 1685,
"s": 732,
"text": null
},
{
"code": null,
"e": 1696,
"s": 1685,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 1716,
"s": 1696,
"text": "Java - util package"
},
{
"code": null,
"e": 1730,
"s": 1716,
"text": "Java-Iterator"
},
{
"code": null,
"e": 1742,
"s": 1730,
"text": "java-stream"
},
{
"code": null,
"e": 1763,
"s": 1742,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 1768,
"s": 1763,
"text": "Java"
},
{
"code": null,
"e": 1773,
"s": 1768,
"text": "Java"
}
] |
Haml | HTML Pre-processor
|
09 Sep, 2021
As its name suggests the pre-processor is the first stage of the whole compiling process it includes removing the comments, expanding the macros, the inclusion of the headers, etc.
In HTML and CSS when it comes to writing it, It is a bit crucial as we have to do the same job again and again like closing the tab and repeating the same attribute for the same element and it will lead to inefficiency. To overcome these problems there exists the Pre-processors. So, The Pre-processors in HTML are nothing but the same as that in other languages, it takes the input in the form of data and it converts in other types of data. In the case of markups like HTML and CSS, the popular preprocessor includes Haml and Sass. HTML preprocessor can also be understood as it is a program that helps the developer to generate the HTML syntax from the syntax of the preprocessor. It will add some unique features which do not present in the pure HTML syntax. As preprocessors are the programs they are always processed in some languages hence the Haml processed in HTML and Sass.HAML Pre-processor: Haml stands for HTML Abstraction Markup Language created by Hampton Catlin and the only objective behind to create it is to make the markup beautiful. It is basically a Ruby-based pre-processor and required Ruby to be installed in your local machine for the Mac OS, Ruby comes preinstalled while for windows user can install it from here. To install the Haml follow the below commands.
For installing the HAML:gem install haml
gem install haml
For converting the HAML to HTML:haml index.haml index.html
haml index.haml index.html
Note: Command should be run inside the same directory where the index file resides.Examples:
Code for the header in Haml Pre-Processor:
html
%body %center %header %h1GeeksforGeeks %section %bA Computer Science Portal for Geeks
HAML code code converted in HTML:
html
<body> <center> <header> <h1>GeeksforGeeks</h1> </header> <section> <b>A Computer Science Portal for Geeks</b> </section> </center></body>
Output : The output of the above HTML or the HAML code.
Note: The Haml code will reduce the code readability for the HTML code but code reduced syntactically and also by line.
ADVANTAGES
The following points for which the HAML pre-processor is considered useful:
Prefer beautiful markup: It facilitates the organised markup of the code with a user-friendly experience & also renders the output in a structured manner.
DRY(Don’t Repeat Yourself) rule: It follows the DRY approach for discarding the unnecessary HTML code that involves major repetition.
HTML
<body>2 3 <!--Heading tags are opened and closed-->4<h2>GeeksforGeeks, A Computer Science portal for geeks.</h2> 56 <!--Body is closed-->7 </body>
HTML preprocessors avoid all of this by relying on indentation, not text, to determine where elements and blocks of code begin and end. It does not only work in large templates but it does result in smaller templates, which makes the code much cleaner to look at.
Output:
%body
%h2 GeeksforGeeks, A Computer Science portal for geeks.
Well-indented markup should be preferred: To improve appearance, markup language should be well-indented which makes it easy to read. It also determines where an element starts and ends.
There should be a clear HTML structure: With some minimum effort, it helps to maintain the markup language with a clear structure & logical understanding of the final result.
akshitsaxenaa09
HTML-Misc
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "As its name suggests the pre-processor is the first stage of the whole compiling process it includes removing the comments, expanding the macros, the inclusion of the headers, etc. "
},
{
"code": null,
"e": 1502,
"s": 211,
"text": "In HTML and CSS when it comes to writing it, It is a bit crucial as we have to do the same job again and again like closing the tab and repeating the same attribute for the same element and it will lead to inefficiency. To overcome these problems there exists the Pre-processors. So, The Pre-processors in HTML are nothing but the same as that in other languages, it takes the input in the form of data and it converts in other types of data. In the case of markups like HTML and CSS, the popular preprocessor includes Haml and Sass. HTML preprocessor can also be understood as it is a program that helps the developer to generate the HTML syntax from the syntax of the preprocessor. It will add some unique features which do not present in the pure HTML syntax. As preprocessors are the programs they are always processed in some languages hence the Haml processed in HTML and Sass.HAML Pre-processor: Haml stands for HTML Abstraction Markup Language created by Hampton Catlin and the only objective behind to create it is to make the markup beautiful. It is basically a Ruby-based pre-processor and required Ruby to be installed in your local machine for the Mac OS, Ruby comes preinstalled while for windows user can install it from here. To install the Haml follow the below commands. "
},
{
"code": null,
"e": 1544,
"s": 1502,
"text": "For installing the HAML:gem install haml "
},
{
"code": null,
"e": 1562,
"s": 1544,
"text": "gem install haml "
},
{
"code": null,
"e": 1621,
"s": 1562,
"text": "For converting the HAML to HTML:haml index.haml index.html"
},
{
"code": null,
"e": 1648,
"s": 1621,
"text": "haml index.haml index.html"
},
{
"code": null,
"e": 1741,
"s": 1648,
"text": "Note: Command should be run inside the same directory where the index file resides.Examples:"
},
{
"code": null,
"e": 1786,
"s": 1741,
"text": "Code for the header in Haml Pre-Processor: "
},
{
"code": null,
"e": 1791,
"s": 1786,
"text": "html"
},
{
"code": "%body %center %header %h1GeeksforGeeks %section %bA Computer Science Portal for Geeks",
"e": 1916,
"s": 1791,
"text": null
},
{
"code": null,
"e": 1952,
"s": 1916,
"text": "HAML code code converted in HTML: "
},
{
"code": null,
"e": 1957,
"s": 1952,
"text": "html"
},
{
"code": "<body> <center> <header> <h1>GeeksforGeeks</h1> </header> <section> <b>A Computer Science Portal for Geeks</b> </section> </center></body>",
"e": 2152,
"s": 1957,
"text": null
},
{
"code": null,
"e": 2210,
"s": 2152,
"text": "Output : The output of the above HTML or the HAML code. "
},
{
"code": null,
"e": 2331,
"s": 2210,
"text": "Note: The Haml code will reduce the code readability for the HTML code but code reduced syntactically and also by line. "
},
{
"code": null,
"e": 2342,
"s": 2331,
"text": "ADVANTAGES"
},
{
"code": null,
"e": 2418,
"s": 2342,
"text": "The following points for which the HAML pre-processor is considered useful:"
},
{
"code": null,
"e": 2573,
"s": 2418,
"text": "Prefer beautiful markup: It facilitates the organised markup of the code with a user-friendly experience & also renders the output in a structured manner."
},
{
"code": null,
"e": 2707,
"s": 2573,
"text": "DRY(Don’t Repeat Yourself) rule: It follows the DRY approach for discarding the unnecessary HTML code that involves major repetition."
},
{
"code": null,
"e": 2712,
"s": 2707,
"text": "HTML"
},
{
"code": "<body>2 3 <!--Heading tags are opened and closed-->4<h2>GeeksforGeeks, A Computer Science portal for geeks.</h2> 56 <!--Body is closed-->7 </body>",
"e": 2868,
"s": 2712,
"text": null
},
{
"code": null,
"e": 3132,
"s": 2868,
"text": "HTML preprocessors avoid all of this by relying on indentation, not text, to determine where elements and blocks of code begin and end. It does not only work in large templates but it does result in smaller templates, which makes the code much cleaner to look at."
},
{
"code": null,
"e": 3140,
"s": 3132,
"text": "Output:"
},
{
"code": null,
"e": 3146,
"s": 3140,
"text": "%body"
},
{
"code": null,
"e": 3202,
"s": 3146,
"text": "%h2 GeeksforGeeks, A Computer Science portal for geeks."
},
{
"code": null,
"e": 3389,
"s": 3202,
"text": "Well-indented markup should be preferred: To improve appearance, markup language should be well-indented which makes it easy to read. It also determines where an element starts and ends."
},
{
"code": null,
"e": 3564,
"s": 3389,
"text": "There should be a clear HTML structure: With some minimum effort, it helps to maintain the markup language with a clear structure & logical understanding of the final result."
},
{
"code": null,
"e": 3580,
"s": 3564,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 3590,
"s": 3580,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3595,
"s": 3590,
"text": "HTML"
},
{
"code": null,
"e": 3612,
"s": 3595,
"text": "Web Technologies"
},
{
"code": null,
"e": 3639,
"s": 3612,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3644,
"s": 3639,
"text": "HTML"
},
{
"code": null,
"e": 3742,
"s": 3644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3766,
"s": 3742,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3805,
"s": 3766,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3844,
"s": 3805,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3864,
"s": 3844,
"text": "Angular File Upload"
},
{
"code": null,
"e": 3893,
"s": 3864,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3926,
"s": 3893,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3987,
"s": 3926,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4030,
"s": 3987,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4102,
"s": 4030,
"text": "Differences between Functional Components and Class Components in React"
}
] |
UDP Client Server using connect | C implementation
|
17 Apr, 2018
UDP is a connection less protocol. There is no connection is established between client and server. Creating Standard UDP Client/Server is discussed here
Prerequisite : Socket Programming in C/CPP | UDP server-client implementation
In UDP, the client does not form a connection with the server like in TCP and instead, It just sends a datagram. Similarly, the server need not to accept a connection and just waits for datagrams to arrive. We can call a function called connect() in UDP but it does not result anything like it does in TCP. There is no 3 way handshake. It just checks for any immediate errors and store the peer’s IP address and port number. connect() is storing peers address so no need to pass server address and server address length arguments in sendto().
Necessary Functions :
int connect(int sockfd, const struct sockaddr *servaddr,
socklen_t addrlen);
returns : 0 if OK -1 on error
arguments :
sockfd : File descriptor of socket to be connected.
struct sockaddr *servaddr : server address structure.
addrlen : length of server address structure.
Below is the implementation showing message transfer between server-client :
UDP Server code :
// server program for udp connection#include <stdio.h>#include <strings.h>#include <sys/types.h>#include <arpa/inet.h>#include <sys/socket.h>#include<netinet/in.h>#define PORT 5000#define MAXLINE 1000 // Driver codeint main(){ char buffer[100]; char *message = "Hello Client"; int listenfd, len; struct sockaddr_in servaddr, cliaddr; bzero(&servaddr, sizeof(servaddr)); // Create a UDP Socket listenfd = socket(AF_INET, SOCK_DGRAM, 0); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); servaddr.sin_family = AF_INET; // bind server address to socket descriptor bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); //receive the datagram len = sizeof(cliaddr); int n = recvfrom(listenfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&cliaddr,&len); //receive message from server buffer[n] = '\0'; puts(buffer); // send the response sendto(listenfd, message, MAXLINE, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));}
UDP Client code :
// udp client driver program#include <stdio.h>#include <strings.h>#include <sys/types.h>#include <arpa/inet.h>#include <sys/socket.h>#include<netinet/in.h>#include<unistd.h>#include<stdlib.h> #define PORT 5000#define MAXLINE 1000 // Driver codeint main(){ char buffer[100]; char *message = "Hello Server"; int sockfd, n; struct sockaddr_in servaddr; // clear servaddr bzero(&servaddr, sizeof(servaddr)); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(PORT); servaddr.sin_family = AF_INET; // create datagram socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); // connect to server if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { printf("\n Error : Connect Failed \n"); exit(0); } // request to send datagram // no need to specify server address in sendto // connect stores the peers IP and port sendto(sockfd, message, MAXLINE, 0, (struct sockaddr*)NULL, sizeof(servaddr)); // waiting for response recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)NULL, NULL); puts(buffer); // close the descriptor close(sockfd);}
Outputs:
C Programs
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Apr, 2018"
},
{
"code": null,
"e": 206,
"s": 52,
"text": "UDP is a connection less protocol. There is no connection is established between client and server. Creating Standard UDP Client/Server is discussed here"
},
{
"code": null,
"e": 284,
"s": 206,
"text": "Prerequisite : Socket Programming in C/CPP | UDP server-client implementation"
},
{
"code": null,
"e": 827,
"s": 284,
"text": "In UDP, the client does not form a connection with the server like in TCP and instead, It just sends a datagram. Similarly, the server need not to accept a connection and just waits for datagrams to arrive. We can call a function called connect() in UDP but it does not result anything like it does in TCP. There is no 3 way handshake. It just checks for any immediate errors and store the peer’s IP address and port number. connect() is storing peers address so no need to pass server address and server address length arguments in sendto()."
},
{
"code": null,
"e": 849,
"s": 827,
"text": "Necessary Functions :"
},
{
"code": null,
"e": 1136,
"s": 849,
"text": "int connect(int sockfd, const struct sockaddr *servaddr,\n socklen_t addrlen);\nreturns : 0 if OK -1 on error\narguments :\nsockfd : File descriptor of socket to be connected.\nstruct sockaddr *servaddr : server address structure.\naddrlen : length of server address structure.\n"
},
{
"code": null,
"e": 1213,
"s": 1136,
"text": "Below is the implementation showing message transfer between server-client :"
},
{
"code": null,
"e": 1231,
"s": 1213,
"text": "UDP Server code :"
},
{
"code": "// server program for udp connection#include <stdio.h>#include <strings.h>#include <sys/types.h>#include <arpa/inet.h>#include <sys/socket.h>#include<netinet/in.h>#define PORT 5000#define MAXLINE 1000 // Driver codeint main(){ char buffer[100]; char *message = \"Hello Client\"; int listenfd, len; struct sockaddr_in servaddr, cliaddr; bzero(&servaddr, sizeof(servaddr)); // Create a UDP Socket listenfd = socket(AF_INET, SOCK_DGRAM, 0); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); servaddr.sin_family = AF_INET; // bind server address to socket descriptor bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); //receive the datagram len = sizeof(cliaddr); int n = recvfrom(listenfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&cliaddr,&len); //receive message from server buffer[n] = '\\0'; puts(buffer); // send the response sendto(listenfd, message, MAXLINE, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));}",
"e": 2299,
"s": 1231,
"text": null
},
{
"code": null,
"e": 2317,
"s": 2299,
"text": "UDP Client code :"
},
{
"code": "// udp client driver program#include <stdio.h>#include <strings.h>#include <sys/types.h>#include <arpa/inet.h>#include <sys/socket.h>#include<netinet/in.h>#include<unistd.h>#include<stdlib.h> #define PORT 5000#define MAXLINE 1000 // Driver codeint main(){ char buffer[100]; char *message = \"Hello Server\"; int sockfd, n; struct sockaddr_in servaddr; // clear servaddr bzero(&servaddr, sizeof(servaddr)); servaddr.sin_addr.s_addr = inet_addr(\"127.0.0.1\"); servaddr.sin_port = htons(PORT); servaddr.sin_family = AF_INET; // create datagram socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); // connect to server if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { printf(\"\\n Error : Connect Failed \\n\"); exit(0); } // request to send datagram // no need to specify server address in sendto // connect stores the peers IP and port sendto(sockfd, message, MAXLINE, 0, (struct sockaddr*)NULL, sizeof(servaddr)); // waiting for response recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)NULL, NULL); puts(buffer); // close the descriptor close(sockfd);}",
"e": 3515,
"s": 2317,
"text": null
},
{
"code": null,
"e": 3524,
"s": 3515,
"text": "Outputs:"
},
{
"code": null,
"e": 3535,
"s": 3524,
"text": "C Programs"
},
{
"code": null,
"e": 3546,
"s": 3535,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3565,
"s": 3546,
"text": "Technical Scripter"
}
] |
Python | Add image on a Tkinter button
|
25 Apr, 2019
Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications with the help of varieties of widgets and functions. Like any other GUI module it also supports images i.e you can use images in the application to make it more attractive.
Image can be added with the help of PhotoImage() method. This is a Tkinter method which means you don’t have to import any other module in order to use it.
Important: If both image and text are given on Button, the text will be dominated and only image will appear on the Button. But if you want to show both image and text then you have to pass compound in button options.
Button(master, text = "Button", image = "image.png", compound=LEFT)
compound = LEFT -> image will be at left side of the buttoncompound = RIGHT -> image will be at right side of buttoncompound = TOP -> image will be at top of buttoncompound = BOTTOM -> image will be at bottom of button
Syntax:
photo = PhotoImage(file = "path_of_file")
path_of_file is any valid path available on your local machine.
Code #1:
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =( 'Verdana', 15)).pack(side = TOP, pady = 10) # Creating a photoimage object to use imagephoto = PhotoImage(file = r"C:\Gfg\circle.png") # here, image option is used to# set image on buttonButton(root, text = 'Click Me !', image = photo).pack(side = TOP) mainloop()
Output:In output observe that only image is shown on the button and the size of the button is also bigger than the usual size it is because we haven’t set the size of the image. Code #2: To show both image and text on Button.
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =( 'Verdana', 15)).pack(side = TOP, pady = 10) # Creating a photoimage object to use imagephoto = PhotoImage(file = r"C:\Gfg\circle.png") # Resizing image to fit on buttonphotoimage = photo.subsample(3, 3) # here, image option is used to# set image on button# compound option is used to align# image on LEFT side of buttonButton(root, text = 'Click Me !', image = photoimage, compound = LEFT).pack(side = TOP) mainloop()
Output:Observe that both text and image are appearing as well as size of the image is also small.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Apr, 2019"
},
{
"code": null,
"e": 320,
"s": 52,
"text": "Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications with the help of varieties of widgets and functions. Like any other GUI module it also supports images i.e you can use images in the application to make it more attractive."
},
{
"code": null,
"e": 476,
"s": 320,
"text": "Image can be added with the help of PhotoImage() method. This is a Tkinter method which means you don’t have to import any other module in order to use it."
},
{
"code": null,
"e": 694,
"s": 476,
"text": "Important: If both image and text are given on Button, the text will be dominated and only image will appear on the Button. But if you want to show both image and text then you have to pass compound in button options."
},
{
"code": null,
"e": 762,
"s": 694,
"text": "Button(master, text = \"Button\", image = \"image.png\", compound=LEFT)"
},
{
"code": null,
"e": 981,
"s": 762,
"text": "compound = LEFT -> image will be at left side of the buttoncompound = RIGHT -> image will be at right side of buttoncompound = TOP -> image will be at top of buttoncompound = BOTTOM -> image will be at bottom of button"
},
{
"code": null,
"e": 989,
"s": 981,
"text": "Syntax:"
},
{
"code": null,
"e": 1031,
"s": 989,
"text": "photo = PhotoImage(file = \"path_of_file\")"
},
{
"code": null,
"e": 1095,
"s": 1031,
"text": "path_of_file is any valid path available on your local machine."
},
{
"code": null,
"e": 1104,
"s": 1095,
"text": "Code #1:"
},
{
"code": "# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =( 'Verdana', 15)).pack(side = TOP, pady = 10) # Creating a photoimage object to use imagephoto = PhotoImage(file = r\"C:\\Gfg\\circle.png\") # here, image option is used to# set image on buttonButton(root, text = 'Click Me !', image = photo).pack(side = TOP) mainloop()",
"e": 1588,
"s": 1104,
"text": null
},
{
"code": null,
"e": 1814,
"s": 1588,
"text": "Output:In output observe that only image is shown on the button and the size of the button is also bigger than the usual size it is because we haven’t set the size of the image. Code #2: To show both image and text on Button."
},
{
"code": "# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =( 'Verdana', 15)).pack(side = TOP, pady = 10) # Creating a photoimage object to use imagephoto = PhotoImage(file = r\"C:\\Gfg\\circle.png\") # Resizing image to fit on buttonphotoimage = photo.subsample(3, 3) # here, image option is used to# set image on button# compound option is used to align# image on LEFT side of buttonButton(root, text = 'Click Me !', image = photoimage, compound = LEFT).pack(side = TOP) mainloop()",
"e": 2472,
"s": 1814,
"text": null
},
{
"code": null,
"e": 2570,
"s": 2472,
"text": "Output:Observe that both text and image are appearing as well as size of the image is also small."
},
{
"code": null,
"e": 2581,
"s": 2570,
"text": "Python-gui"
},
{
"code": null,
"e": 2596,
"s": 2581,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2603,
"s": 2596,
"text": "Python"
}
] |
Fractal using Spirograph in Python
|
17 Nov, 2020
Introduction
Spirograph toy that is used to produce complex patterns using plastic cogs and colored pens. A fractal is a curve, that is developed using a recurring pattern that repeats itself infinitely on a low scale. Fractals are used for modeling structures (such as snowflakes) or for describing partly chaotic phenomena.Spirograph can be used to draw various fractals. Some of them are given below
You can visit benice-equation-blogspot.in for more fractals design with there parametric equation. Some of them are given below
Mathematics behind the curtain
These are the two parametric equation to form a spirograph fractals, to understand these equations you have to consider a generalized figure of spirograph.
For the mathematics part you can refer to Wiki although i’ll try to explain a little of that mathematics in a short here. If we are interested behind the maths then you can check out the referred links. So as of now, these various curve can be drawn by using a parametric equation and varying some values of that equation we can get different fractals. So here’s the parametric equation:
where,
R is a scaling parameter and does not affect the structure of the Spirograph.
and,
So, now let’s try to implement this in code.
#importing the required librariesimport random, argparseimport mathimport turtlefrom PIL import Imagefrom datetime import datetime from fractions import gcd # A class that draws a spirographclass Spiro: # constructor def __init__(self, xc, yc, col, R, r, l): # create own turtle self.t = turtle.Turtle() # set cursor shape self.t.shape('turtle') # set step in degrees self.step = 5 # set drawing complete flag self.drawingComplete = False # set parameters self.setparams(xc, yc, col, R, r, l) # initiatize drawing self.restart() # set parameters def setparams(self, xc, yc, col, R, r, l): # spirograph parameters self.xc = xc self.yc = yc self.R = int(R) self.r = int(r) self.l = l self.col = col # reduce r/R to smallest form by dividing with GCD gcdVal = gcd(self.r, self.R) self.nRot = self.r//gcdVal # get ratio of radii self.k = r/float(R) # set color self.t.color(*col) # current angle self.a = 0 # restart drawing def restart(self): # set flag self.drawingComplete = False # show turtle self.t.showturtle() # go to first point self.t.up() R, k, l = self.R, self.k, self.l a = 0.0 x = R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k)) y = R*((1-k)*math.sin(a) - l*k*math.sin((1-k)*a/k)) self.t.setpos(self.xc + x, self.yc + y) self.t.down() # draw the whole thing def draw(self): # draw rest of points R, k, l = self.R, self.k, self.l for i in range(0, 360*self.nRot + 1, self.step): a = math.radians(i) x = R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k)) y = R*((1-k)*math.sin(a) - l*k*math.sin((1-k)*a/k)) self.t.setpos(self.xc + x, self.yc + y) # done - hide turtle self.t.hideturtle() # update by one step def update(self): # skip if done if self.drawingComplete: return # increment angle self.a += self.step # draw step R, k, l = self.R, self.k, self.l # set angle a = math.radians(self.a) x = self.R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k)) y = self.R*((1-k)*math.sin(a) - l*k*math.sin((1-k)*a/k)) self.t.setpos(self.xc + x, self.yc + y) # check if drawing is complete and set flag if self.a >= 360*self.nRot: self.drawingComplete = True # done - hide turtle self.t.hideturtle() # clear everything def clear(self): self.t.clear() # A class for animating spirographsclass SpiroAnimator: # constructor def __init__(self, N): # timer value in milliseconds self.deltaT = 10 # get window dimensions self.width = turtle.window_width() self.height = turtle.window_height() # create spiro objects self.spiros = [] for i in range(N): # generate random parameters rparams = self.genRandomParams() # set spiro params spiro = Spiro(*rparams) self.spiros.append(spiro) # call timer turtle.ontimer(self.update, self.deltaT) # restart sprio drawing def restart(self): for spiro in self.spiros: # clear spiro.clear() # generate random parameters rparams = self.genRandomParams() # set spiro params spiro.setparams(*rparams) # restart drawing spiro.restart() # generate random parameters def genRandomParams(self): width, height = self.width, self.height R = random.randint(50, min(width, height)//2) r = random.randint(10, 9*R//10) l = random.uniform(0.1, 0.9) xc = random.randint(-width//2, width//2) yc = random.randint(-height//2, height//2) col = (random.random(), random.random(), random.random()) return (xc, yc, col, R, r, l) def update(self): # update all spiros nComplete = 0 for spiro in self.spiros: # update spiro.update() # count completed ones if spiro.drawingComplete: nComplete+= 1 # if all spiros are complete, restart if nComplete == len(self.spiros): self.restart() # call timer turtle.ontimer(self.update, self.deltaT) # toggle turtle on/off def toggleTurtles(self): for spiro in self.spiros: if spiro.t.isvisible(): spiro.t.hideturtle() else: spiro.t.showturtle() # save spiros to imagedef saveDrawing(): # hide turtle turtle.hideturtle() # generate unique file name dateStr = (datetime.now()).strftime("%d%b%Y-%H%M%S") fileName = 'spiro-' + dateStr print('saving drawing to %s.eps/png' % fileName) # get tkinter canvas canvas = turtle.getcanvas() # save postscipt image canvas.postscript(file = fileName + '.eps') # use PIL to convert to PNG img = Image.open(fileName + '.eps') img.save(fileName + '.png', 'png') # show turtle turtle.showturtle() # main() functiondef main(): # use sys.argv if needed print('generating spirograph...') # create parser descStr = """This program draws spirographs using the Turtle module. When run with no arguments, this program draws random spirographs. Terminology: R: radius of outer circle. r: radius of inner circle. l: ratio of hole distance to r. """ parser = argparse.ArgumentParser(description=descStr) # add expected arguments parser.add_argument('--sparams', nargs=3, dest='sparams', required=False, help="The three arguments in sparams: R, r, l.") # parse args args = parser.parse_args() # set to 80% screen width turtle.setup(width=0.8) # set cursor shape turtle.shape('turtle') # set title turtle.title("Spirographs!") # add key handler for saving images turtle.onkey(saveDrawing, "s") # start listening turtle.listen() # hide main turtle cursor turtle.hideturtle() # checks args and draw if args.sparams: params = [float(x) for x in args.sparams] # draw spirograph with given parameters # black by default col = (0.0, 0.0, 0.0) spiro = Spiro(0, 0, col, *params) spiro.draw() else: # create animator object spiroAnim = SpiroAnimator(4) # add key handler to toggle turtle cursor turtle.onkey(spiroAnim.toggleTurtles, "t") # add key handler to restart animation turtle.onkey(spiroAnim.restart, "space") # start turtle main loop turtle.mainloop() # call mainif __name__ == '__main__': main()
Output:
Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/2017-11-01-at-17-28-59.mp400:0000:0000:48Use Up/Down Arrow keys to increase or decrease volume.
The above program draws 4 different kinds of spirograph fractals, try to generate other fractals and then upload your github links in the comment. I’ll be happy to help you out if any error comes up.
This article is contributed by Subhajit Saha. 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.
Fractal
GBlog
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 41,
"s": 28,
"text": "Introduction"
},
{
"code": null,
"e": 431,
"s": 41,
"text": "Spirograph toy that is used to produce complex patterns using plastic cogs and colored pens. A fractal is a curve, that is developed using a recurring pattern that repeats itself infinitely on a low scale. Fractals are used for modeling structures (such as snowflakes) or for describing partly chaotic phenomena.Spirograph can be used to draw various fractals. Some of them are given below"
},
{
"code": null,
"e": 559,
"s": 431,
"text": "You can visit benice-equation-blogspot.in for more fractals design with there parametric equation. Some of them are given below"
},
{
"code": null,
"e": 590,
"s": 559,
"text": "Mathematics behind the curtain"
},
{
"code": null,
"e": 746,
"s": 590,
"text": "These are the two parametric equation to form a spirograph fractals, to understand these equations you have to consider a generalized figure of spirograph."
},
{
"code": null,
"e": 1134,
"s": 746,
"text": "For the mathematics part you can refer to Wiki although i’ll try to explain a little of that mathematics in a short here. If we are interested behind the maths then you can check out the referred links. So as of now, these various curve can be drawn by using a parametric equation and varying some values of that equation we can get different fractals. So here’s the parametric equation:"
},
{
"code": null,
"e": 1141,
"s": 1134,
"text": "where,"
},
{
"code": null,
"e": 1219,
"s": 1141,
"text": "R is a scaling parameter and does not affect the structure of the Spirograph."
},
{
"code": null,
"e": 1224,
"s": 1219,
"text": "and,"
},
{
"code": null,
"e": 1269,
"s": 1224,
"text": "So, now let’s try to implement this in code."
},
{
"code": "#importing the required librariesimport random, argparseimport mathimport turtlefrom PIL import Imagefrom datetime import datetime from fractions import gcd # A class that draws a spirographclass Spiro: # constructor def __init__(self, xc, yc, col, R, r, l): # create own turtle self.t = turtle.Turtle() # set cursor shape self.t.shape('turtle') # set step in degrees self.step = 5 # set drawing complete flag self.drawingComplete = False # set parameters self.setparams(xc, yc, col, R, r, l) # initiatize drawing self.restart() # set parameters def setparams(self, xc, yc, col, R, r, l): # spirograph parameters self.xc = xc self.yc = yc self.R = int(R) self.r = int(r) self.l = l self.col = col # reduce r/R to smallest form by dividing with GCD gcdVal = gcd(self.r, self.R) self.nRot = self.r//gcdVal # get ratio of radii self.k = r/float(R) # set color self.t.color(*col) # current angle self.a = 0 # restart drawing def restart(self): # set flag self.drawingComplete = False # show turtle self.t.showturtle() # go to first point self.t.up() R, k, l = self.R, self.k, self.l a = 0.0 x = R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k)) y = R*((1-k)*math.sin(a) - l*k*math.sin((1-k)*a/k)) self.t.setpos(self.xc + x, self.yc + y) self.t.down() # draw the whole thing def draw(self): # draw rest of points R, k, l = self.R, self.k, self.l for i in range(0, 360*self.nRot + 1, self.step): a = math.radians(i) x = R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k)) y = R*((1-k)*math.sin(a) - l*k*math.sin((1-k)*a/k)) self.t.setpos(self.xc + x, self.yc + y) # done - hide turtle self.t.hideturtle() # update by one step def update(self): # skip if done if self.drawingComplete: return # increment angle self.a += self.step # draw step R, k, l = self.R, self.k, self.l # set angle a = math.radians(self.a) x = self.R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k)) y = self.R*((1-k)*math.sin(a) - l*k*math.sin((1-k)*a/k)) self.t.setpos(self.xc + x, self.yc + y) # check if drawing is complete and set flag if self.a >= 360*self.nRot: self.drawingComplete = True # done - hide turtle self.t.hideturtle() # clear everything def clear(self): self.t.clear() # A class for animating spirographsclass SpiroAnimator: # constructor def __init__(self, N): # timer value in milliseconds self.deltaT = 10 # get window dimensions self.width = turtle.window_width() self.height = turtle.window_height() # create spiro objects self.spiros = [] for i in range(N): # generate random parameters rparams = self.genRandomParams() # set spiro params spiro = Spiro(*rparams) self.spiros.append(spiro) # call timer turtle.ontimer(self.update, self.deltaT) # restart sprio drawing def restart(self): for spiro in self.spiros: # clear spiro.clear() # generate random parameters rparams = self.genRandomParams() # set spiro params spiro.setparams(*rparams) # restart drawing spiro.restart() # generate random parameters def genRandomParams(self): width, height = self.width, self.height R = random.randint(50, min(width, height)//2) r = random.randint(10, 9*R//10) l = random.uniform(0.1, 0.9) xc = random.randint(-width//2, width//2) yc = random.randint(-height//2, height//2) col = (random.random(), random.random(), random.random()) return (xc, yc, col, R, r, l) def update(self): # update all spiros nComplete = 0 for spiro in self.spiros: # update spiro.update() # count completed ones if spiro.drawingComplete: nComplete+= 1 # if all spiros are complete, restart if nComplete == len(self.spiros): self.restart() # call timer turtle.ontimer(self.update, self.deltaT) # toggle turtle on/off def toggleTurtles(self): for spiro in self.spiros: if spiro.t.isvisible(): spiro.t.hideturtle() else: spiro.t.showturtle() # save spiros to imagedef saveDrawing(): # hide turtle turtle.hideturtle() # generate unique file name dateStr = (datetime.now()).strftime(\"%d%b%Y-%H%M%S\") fileName = 'spiro-' + dateStr print('saving drawing to %s.eps/png' % fileName) # get tkinter canvas canvas = turtle.getcanvas() # save postscipt image canvas.postscript(file = fileName + '.eps') # use PIL to convert to PNG img = Image.open(fileName + '.eps') img.save(fileName + '.png', 'png') # show turtle turtle.showturtle() # main() functiondef main(): # use sys.argv if needed print('generating spirograph...') # create parser descStr = \"\"\"This program draws spirographs using the Turtle module. When run with no arguments, this program draws random spirographs. Terminology: R: radius of outer circle. r: radius of inner circle. l: ratio of hole distance to r. \"\"\" parser = argparse.ArgumentParser(description=descStr) # add expected arguments parser.add_argument('--sparams', nargs=3, dest='sparams', required=False, help=\"The three arguments in sparams: R, r, l.\") # parse args args = parser.parse_args() # set to 80% screen width turtle.setup(width=0.8) # set cursor shape turtle.shape('turtle') # set title turtle.title(\"Spirographs!\") # add key handler for saving images turtle.onkey(saveDrawing, \"s\") # start listening turtle.listen() # hide main turtle cursor turtle.hideturtle() # checks args and draw if args.sparams: params = [float(x) for x in args.sparams] # draw spirograph with given parameters # black by default col = (0.0, 0.0, 0.0) spiro = Spiro(0, 0, col, *params) spiro.draw() else: # create animator object spiroAnim = SpiroAnimator(4) # add key handler to toggle turtle cursor turtle.onkey(spiroAnim.toggleTurtles, \"t\") # add key handler to restart animation turtle.onkey(spiroAnim.restart, \"space\") # start turtle main loop turtle.mainloop() # call mainif __name__ == '__main__': main()",
"e": 8230,
"s": 1269,
"text": null
},
{
"code": null,
"e": 8238,
"s": 8230,
"text": "Output:"
},
{
"code": null,
"e": 8401,
"s": 8238,
"text": "\n\nVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/2017-11-01-at-17-28-59.mp400:0000:0000:48Use Up/Down Arrow keys to increase or decrease volume.\n\n"
},
{
"code": null,
"e": 8601,
"s": 8401,
"text": "The above program draws 4 different kinds of spirograph fractals, try to generate other fractals and then upload your github links in the comment. I’ll be happy to help you out if any error comes up."
},
{
"code": null,
"e": 8902,
"s": 8601,
"text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 9027,
"s": 8902,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9035,
"s": 9027,
"text": "Fractal"
},
{
"code": null,
"e": 9041,
"s": 9035,
"text": "GBlog"
},
{
"code": null,
"e": 9048,
"s": 9041,
"text": "Python"
},
{
"code": null,
"e": 9067,
"s": 9048,
"text": "Technical Scripter"
}
] |
Flutter – Stepper Widget
|
18 Nov, 2021
In this article, we will learn about the Stepper widget in Flutter. A stepper widget displays progress through a sequence of steps. Stepper is generally used in filling forms online.
For example, remember filling an online form for applying to any university or passport or driving license. We filled the form step by step like
In step 1 we have filled in our personal details
In step 2 we have entered our residence address
In step 3 we have given our education details
In step 4 we did payment
In step 5 we got registered and print the receipt
This is actually called a Stepper. Performing the task in a step-by-step process.
Now let’s see the practical implementation of our stepper widget:
Step 1: Open a new flutter project in your editor.
Step 2: In scaffold, we initialized Stepper() and inside stepper, we created a method called stepList(). This method is created because we have created the list of steps that are required in the form.
Dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { // Here we have created list of steps that // are required to complete the form List<Step> stepList() => [ const Step(title: Text('Account'), content: Center(child: Text('Account'),)), const Step(title: Text('Address'), content: Center(child: Text('Address'),)), const Step(title: Text('Confirm'), content: Center(child: Text('Confirm'),)) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white), ), ), // Here we have initialized the stepper widget body: Stepper( steps: stepList(), ) ); }}
Output:
Note: Now, this is the basic Stepper widget. If we want we can change the stepper in horizontal form as well. Just type the command in the below picture
Output:
Step 3: Now let’s add properties to this Stepper Widget like –
currentStep: We have created an integer. Its initial value is 0. It actually shows the content of the step on which that particular index is.
onStepContinue: It’s the callback called when the continue button is tapped. When we click on the continue button it takes us to the next step. If null, the ‘continue’ button will be disabled
onStepCancel: It’s the callback called when the cancel button is tapped. When we click on the cancel button then we push back to the previous step. If null, the ‘cancel’ button will be disabled.
onStepTapped: Callback called when the step is tapped. We can go directly to any step by just clicking on that particular step. for eg – if you want to go directly on step2 then just click on it and you will be there.
Step 4: In this step, we had created a form by adding textfields so that the user can input data. So it basically looks more like a form-like structure.
In the first step Account, we had added texfields – Full Name, Email, Password
In the second step Address, we had created textfield – Full house Address, Pin Code.
In the third step Confirm we are displaying data that the user has entered.
Full Source Code:
Dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp());}import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { // we have initialized active step to 0 so that // our stepper widget will start from first step int _activeCurrentStep = 0; TextEditingController name = TextEditingController(); TextEditingController email = TextEditingController(); TextEditingController pass = TextEditingController(); TextEditingController address = TextEditingController(); TextEditingController pincode = TextEditingController(); // Here we have created list of steps // that are required to complete the form List<Step> stepList() => [ // This is step1 which is called Account. // Here we will fill our personal details Step( state: _activeCurrentStep <= 0 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 0, title: const Text('Account'), content: Container( child: Column( children: [ TextField( controller: name, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full Name', ), ), const SizedBox( height: 8, ), TextField( controller: email, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), const SizedBox( height: 8, ), TextField( controller: pass, obscureText: true, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ], ), ), ), // This is Step2 here we will enter our address Step( state: _activeCurrentStep <= 1 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 1, title: const Text('Address'), content: Container( child: Column( children: [ const SizedBox( height: 8, ), TextField( controller: address, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full House Address', ), ), const SizedBox( height: 8, ), TextField( controller: pincode, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Pin Code', ), ), ], ), )), // This is Step3 here we will display all the details // that are entered by the user Step( state: StepState.complete, isActive: _activeCurrentStep >= 2, title: const Text('Confirm'), content: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.start, children: [ Text('Name: ${name.text}'), Text('Email: ${email.text}'), Text('Password: ${pass.text}'), Text('Address : ${address.text}'), Text('PinCode : ${pincode.text}'), ], ))) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white), ), ), // Here we have initialized the stepper widget body: Stepper( type: StepperType.horizontal, currentStep: _activeCurrentStep, steps: stepList(), // onStepContinue takes us to the next step onStepContinue: () { if (_activeCurrentStep < (stepList().length - 1)) { setState(() { _activeCurrentStep += 1; }); } }, // onStepCancel takes us to the previous step onStepCancel: () { if (_activeCurrentStep == 0) { return; } setState(() { _activeCurrentStep -= 1; }); }, // onStepTap allows to directly click on the particular step we want onStepTapped: (int index) { setState(() { _activeCurrentStep = index; }); }, ), ); }} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { int _activeCurrentStep = 0; TextEditingController name = TextEditingController(); TextEditingController email = TextEditingController(); TextEditingController pass = TextEditingController(); TextEditingController address = TextEditingController(); TextEditingController pincode = TextEditingController(); List<Step> stepList() => [ Step( state: _activeCurrentStep <= 0 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 0, title: const Text('Account'), content: Container( child: Column( children: [ TextField( controller: name, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full Name', ), ), const SizedBox( height: 8, ), TextField( controller: email, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), const SizedBox( height: 8, ), TextField( controller: pass, obscureText: true, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ], ), ), ), Step( state: _activeCurrentStep <= 1 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 1, title: const Text('Address'), content: Container( child: Column( children: [ const SizedBox( height: 8, ), TextField( controller: address, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full House Address', ), ), const SizedBox( height: 8, ), TextField( controller: pincode, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Pin Code', ), ), ], ), )), Step( state: StepState.complete, isActive: _activeCurrentStep >= 2, title: const Text('Confirm'), content: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.start, children: [ Text('Name: ${name.text}'), Text('Email: ${email.text}'), Text('Password: ${pass.text}'), Text('Address : ${address.text}'), Text('PinCode : ${pincode.text}'), ], ))) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter Stepper'), ), body: Stepper( type: StepperType.horizontal, currentStep: _activeCurrentStep, steps: stepList(), onStepContinue: () { if (_activeCurrentStep < (stepList().length - 1)) { setState(() { _activeCurrentStep += 1; }); } }, onStepCancel: () { if (_activeCurrentStep == 0) { return; } setState(() { _activeCurrentStep -= 1; }); }, onStepTapped: (int index) { setState(() { _activeCurrentStep = index; }); }, ), ); }}
Output:
Explanation – In this video, we can see that:
When we click on the continue button then we are heading towards the next step which means our onStepContinue property is working.
When we click on the cancel button we are getting back to the previous step which means our onStepCancel property is working.
When we tap on a particular step then we get straight directly to that particular step which means our onStepTapped property is working.
simmytarika5
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "In this article, we will learn about the Stepper widget in Flutter. A stepper widget displays progress through a sequence of steps. Stepper is generally used in filling forms online."
},
{
"code": null,
"e": 356,
"s": 211,
"text": "For example, remember filling an online form for applying to any university or passport or driving license. We filled the form step by step like"
},
{
"code": null,
"e": 405,
"s": 356,
"text": "In step 1 we have filled in our personal details"
},
{
"code": null,
"e": 453,
"s": 405,
"text": "In step 2 we have entered our residence address"
},
{
"code": null,
"e": 500,
"s": 453,
"text": "In step 3 we have given our education details"
},
{
"code": null,
"e": 525,
"s": 500,
"text": "In step 4 we did payment"
},
{
"code": null,
"e": 575,
"s": 525,
"text": "In step 5 we got registered and print the receipt"
},
{
"code": null,
"e": 657,
"s": 575,
"text": "This is actually called a Stepper. Performing the task in a step-by-step process."
},
{
"code": null,
"e": 723,
"s": 657,
"text": "Now let’s see the practical implementation of our stepper widget:"
},
{
"code": null,
"e": 774,
"s": 723,
"text": "Step 1: Open a new flutter project in your editor."
},
{
"code": null,
"e": 976,
"s": 774,
"text": "Step 2: In scaffold, we initialized Stepper() and inside stepper, we created a method called stepList(). This method is created because we have created the list of steps that are required in the form. "
},
{
"code": null,
"e": 981,
"s": 976,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { // Here we have created list of steps that // are required to complete the form List<Step> stepList() => [ const Step(title: Text('Account'), content: Center(child: Text('Account'),)), const Step(title: Text('Address'), content: Center(child: Text('Address'),)), const Step(title: Text('Confirm'), content: Center(child: Text('Confirm'),)) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white), ), ), // Here we have initialized the stepper widget body: Stepper( steps: stepList(), ) ); }}",
"e": 2352,
"s": 981,
"text": null
},
{
"code": null,
"e": 2360,
"s": 2352,
"text": "Output:"
},
{
"code": null,
"e": 2513,
"s": 2360,
"text": "Note: Now, this is the basic Stepper widget. If we want we can change the stepper in horizontal form as well. Just type the command in the below picture"
},
{
"code": null,
"e": 2522,
"s": 2513,
"text": "Output: "
},
{
"code": null,
"e": 2586,
"s": 2522,
"text": "Step 3: Now let’s add properties to this Stepper Widget like – "
},
{
"code": null,
"e": 2728,
"s": 2586,
"text": "currentStep: We have created an integer. Its initial value is 0. It actually shows the content of the step on which that particular index is."
},
{
"code": null,
"e": 2921,
"s": 2728,
"text": "onStepContinue: It’s the callback called when the continue button is tapped. When we click on the continue button it takes us to the next step. If null, the ‘continue’ button will be disabled"
},
{
"code": null,
"e": 3116,
"s": 2921,
"text": "onStepCancel: It’s the callback called when the cancel button is tapped. When we click on the cancel button then we push back to the previous step. If null, the ‘cancel’ button will be disabled."
},
{
"code": null,
"e": 3334,
"s": 3116,
"text": "onStepTapped: Callback called when the step is tapped. We can go directly to any step by just clicking on that particular step. for eg – if you want to go directly on step2 then just click on it and you will be there."
},
{
"code": null,
"e": 3487,
"s": 3334,
"text": "Step 4: In this step, we had created a form by adding textfields so that the user can input data. So it basically looks more like a form-like structure."
},
{
"code": null,
"e": 3566,
"s": 3487,
"text": "In the first step Account, we had added texfields – Full Name, Email, Password"
},
{
"code": null,
"e": 3651,
"s": 3566,
"text": "In the second step Address, we had created textfield – Full house Address, Pin Code."
},
{
"code": null,
"e": 3727,
"s": 3651,
"text": "In the third step Confirm we are displaying data that the user has entered."
},
{
"code": null,
"e": 3746,
"s": 3727,
"text": "Full Source Code: "
},
{
"code": null,
"e": 3751,
"s": 3746,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());}import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { // we have initialized active step to 0 so that // our stepper widget will start from first step int _activeCurrentStep = 0; TextEditingController name = TextEditingController(); TextEditingController email = TextEditingController(); TextEditingController pass = TextEditingController(); TextEditingController address = TextEditingController(); TextEditingController pincode = TextEditingController(); // Here we have created list of steps // that are required to complete the form List<Step> stepList() => [ // This is step1 which is called Account. // Here we will fill our personal details Step( state: _activeCurrentStep <= 0 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 0, title: const Text('Account'), content: Container( child: Column( children: [ TextField( controller: name, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full Name', ), ), const SizedBox( height: 8, ), TextField( controller: email, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), const SizedBox( height: 8, ), TextField( controller: pass, obscureText: true, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ], ), ), ), // This is Step2 here we will enter our address Step( state: _activeCurrentStep <= 1 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 1, title: const Text('Address'), content: Container( child: Column( children: [ const SizedBox( height: 8, ), TextField( controller: address, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full House Address', ), ), const SizedBox( height: 8, ), TextField( controller: pincode, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Pin Code', ), ), ], ), )), // This is Step3 here we will display all the details // that are entered by the user Step( state: StepState.complete, isActive: _activeCurrentStep >= 2, title: const Text('Confirm'), content: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.start, children: [ Text('Name: ${name.text}'), Text('Email: ${email.text}'), Text('Password: ${pass.text}'), Text('Address : ${address.text}'), Text('PinCode : ${pincode.text}'), ], ))) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white), ), ), // Here we have initialized the stepper widget body: Stepper( type: StepperType.horizontal, currentStep: _activeCurrentStep, steps: stepList(), // onStepContinue takes us to the next step onStepContinue: () { if (_activeCurrentStep < (stepList().length - 1)) { setState(() { _activeCurrentStep += 1; }); } }, // onStepCancel takes us to the previous step onStepCancel: () { if (_activeCurrentStep == 0) { return; } setState(() { _activeCurrentStep -= 1; }); }, // onStepTap allows to directly click on the particular step we want onStepTapped: (int index) { setState(() { _activeCurrentStep = index; }); }, ), ); }} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { int _activeCurrentStep = 0; TextEditingController name = TextEditingController(); TextEditingController email = TextEditingController(); TextEditingController pass = TextEditingController(); TextEditingController address = TextEditingController(); TextEditingController pincode = TextEditingController(); List<Step> stepList() => [ Step( state: _activeCurrentStep <= 0 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 0, title: const Text('Account'), content: Container( child: Column( children: [ TextField( controller: name, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full Name', ), ), const SizedBox( height: 8, ), TextField( controller: email, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), const SizedBox( height: 8, ), TextField( controller: pass, obscureText: true, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ], ), ), ), Step( state: _activeCurrentStep <= 1 ? StepState.editing : StepState.complete, isActive: _activeCurrentStep >= 1, title: const Text('Address'), content: Container( child: Column( children: [ const SizedBox( height: 8, ), TextField( controller: address, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Full House Address', ), ), const SizedBox( height: 8, ), TextField( controller: pincode, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Pin Code', ), ), ], ), )), Step( state: StepState.complete, isActive: _activeCurrentStep >= 2, title: const Text('Confirm'), content: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.start, children: [ Text('Name: ${name.text}'), Text('Email: ${email.text}'), Text('Password: ${pass.text}'), Text('Address : ${address.text}'), Text('PinCode : ${pincode.text}'), ], ))) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter Stepper'), ), body: Stepper( type: StepperType.horizontal, currentStep: _activeCurrentStep, steps: stepList(), onStepContinue: () { if (_activeCurrentStep < (stepList().length - 1)) { setState(() { _activeCurrentStep += 1; }); } }, onStepCancel: () { if (_activeCurrentStep == 0) { return; } setState(() { _activeCurrentStep -= 1; }); }, onStepTapped: (int index) { setState(() { _activeCurrentStep = index; }); }, ), ); }}",
"e": 13800,
"s": 3751,
"text": null
},
{
"code": null,
"e": 13809,
"s": 13800,
"text": "Output: "
},
{
"code": null,
"e": 13857,
"s": 13811,
"text": "Explanation – In this video, we can see that:"
},
{
"code": null,
"e": 13988,
"s": 13857,
"text": "When we click on the continue button then we are heading towards the next step which means our onStepContinue property is working."
},
{
"code": null,
"e": 14114,
"s": 13988,
"text": "When we click on the cancel button we are getting back to the previous step which means our onStepCancel property is working."
},
{
"code": null,
"e": 14251,
"s": 14114,
"text": "When we tap on a particular step then we get straight directly to that particular step which means our onStepTapped property is working."
},
{
"code": null,
"e": 14264,
"s": 14251,
"text": "simmytarika5"
},
{
"code": null,
"e": 14280,
"s": 14264,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 14285,
"s": 14280,
"text": "Dart"
},
{
"code": null,
"e": 14293,
"s": 14285,
"text": "Flutter"
}
] |
Run Length Decoding in Linked List
|
21 Jun, 2021
Given an encoded Linked List which is encoded using the Run Length Encoding algorithm. The task is to decode the given linked list and generate the input string.Run Length Encoding: In run length encoding, the input string is encoded by replacing a substring of repeated character in the string by the character followed by its count. If the character is single and is non-repeating than it’s count is not added. For Example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3dex6”Examples:
Input : List = a->5->b->r->3->NULL Output : string = “aaaaabrrr” Explanation : From the linked list, the character is ‘a’ and it’s count is 5 so the character is repeated 5 times. The next character is ‘b’ and the next character to it is not a number hence the character ‘b’ is repeated only once. The next character is ‘r’ and the count is 3 hence the character is repeated 3 times.Input : List = a->b->r->3->a->3->NULL Output : string = “abrrraaa”
Approach:
Traverse through the linked list.
Store the current character in a variable c.
Check if the next node is a number and store the number in count else count is 1.
Append the character c to the list count times.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to decode a linked list#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node { char data; struct Node* next;}; // Utility function to create a new NodeNode* newNode(char data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Function to append nodes to a listvoid append(struct Node* head_ref, char new_data){ struct Node* new_node = new Node; struct Node* last = head_ref; new_node->data = new_data; new_node->next = NULL; if (head_ref == NULL) { head_ref = new_node; return; } while (last->next != NULL) last = last->next; last->next = new_node; return;} // Function to print listvoid printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Function to decode the linked liststring decodeList(Node* head){ Node* p = head; string res = ""; int count; // While there are nodes left while (p) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character char c = p->data; if (p->next) { Node* temp = p->next; // If current node is a digit if (temp && temp->data >= '0' && temp->data <= '9') { // Generate the integer from // the consecutive digits while (temp && temp->data >= '0' && temp->data <= '9') { count = count * 10 + (temp->data - '0'); temp = temp->next; } p = temp; } else { count = 1; p = p->next; } } else { count = 1; p = p->next; } // Repeat the character count times for (int i = 0; i < count; i++) { res += c; } } return res;} // Driver codeint main(){ // Creating the linked list Node* head = newNode('a'); head->next = newNode('5'); head->next->next = newNode('b'); head->next->next->next = newNode('r'); cout << decodeList(head); return 0;}
// Java program to decode a linked listclass GFG { // Linked list node static class Node { char data; Node next; }; // Utility function to create a new Node static Node newNode(char data) { Node temp = new Node(); temp.data = data; temp.next = null; return temp; } // Function to append nodes to a list static void append(Node head_ref, char new_data) { Node new_node = new Node(); Node last = head_ref; new_node.data = new_data; new_node.next = null; if (head_ref == null) { head_ref = new_node; return; } while (last.next != null) last = last.next; last.next = new_node; return; } // Function to print list static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Function to decode the linked list static String decodeList(Node head) { // Pointer used to traverse through all // the nodes in the list Node p = head; // String to store the decoded message String res = ""; int count; // While there are nodes left while (p != null) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character char c = p.data; if (p.next != null) { Node temp = p.next; // If current node is a digit if (temp != null && temp.data >= '0' && temp.data <= '9') { // Generate the integer from // the consecutive digits while (temp != null && temp.data >= '0' && temp.data <= '9') { count = count * 10 + (temp.data - '0'); temp = temp.next; } p = temp; } else { count = 1; p = p.next; } } else { count = 1; p = p.next; } // Repeat the character count times for (int i = 0; i < count; i++) { res += c; } } return res; } // Driver code public static void main(String args[]) { // Creating the linked list Node head = newNode('a'); head.next = newNode('5'); head.next.next = newNode('b'); head.next.next.next = newNode('r'); System.out.println(decodeList(head)); }} /* This code contributed by PrinciRaj1992 */
# Python3 program to decode a linked list # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Utility function to create a Nodedef newNode(data): temp = Node(data); temp.next = None; return temp; # Function to append nodes to a listdef append(head_ref, new_data): new_node = Node; last = head_ref; new_node.data = new_data; new_node.next = None; if (head_ref == None): head_ref = new_node; return; while (last.next != None): last = last.next; last.next = new_node; return; # Function to print listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next; # Function to decode the linked listdef decodeList(head): p = head; res = ""; count = 0 # While there are nodes left while (p != None): # To store the count by which the current # character needs to be repeated count = 0; # Get the current character c = p.data; if (p.next != None): temp = p.next; # If current node is a digit if (temp != None and ord(temp.data) >= ord('0') and ord(temp.data) <= ord('9')): # Generate the integer from # the consecutive digits while (temp != None and ord(temp.data) >= ord('0') and ord(temp.data) <= ord('9')): count = count * 10 + ord(temp.data) - ord('0') temp = temp.next; p = temp; else: count = 1; p = p.next; else: count = 1; p = p.next; # Repeat the character count times for i in range(0, count): res += c; return res; # Driver codeif __name__=='__main__': # Creating the linked list head = newNode('a'); head.next = newNode('5'); head.next.next = newNode('b'); head.next.next.next = newNode('r'); print(decodeList(head)) # This code is contributed by rutvik_56
// C# program to decode a linked listusing System; public class GFG { // Linked list node public class Node { public char data; public Node next; }; // Utility function to create a new Node static Node newNode(char data) { Node temp = new Node(); temp.data = data; temp.next = null; return temp; } // Function to append nodes to a list static void append(Node head_ref, char new_data) { Node new_node = new Node(); Node last = head_ref; new_node.data = new_data; new_node.next = null; if (head_ref == null) { head_ref = new_node; return; } while (last.next != null) last = last.next; last.next = new_node; return; } // Function to print list static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Function to decode the linked list static String decodeList(Node head) { // Pointer used to traverse through all // the nodes in the list Node p = head; // String to store the decoded message String res = ""; int count; // While there are nodes left while (p != null) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character char c = p.data; if (p.next != null) { Node temp = p.next; // If current node is a digit if (temp != null && temp.data >= '0' && temp.data <= '9') { // Generate the integer from // the consecutive digits while (temp != null && temp.data >= '0' && temp.data <= '9') { count = count * 10 + (temp.data - '0'); temp = temp.next; } p = temp; } else { count = 1; p = p.next; } } else { count = 1; p = p.next; } // Repeat the character count times for (int i = 0; i < count; i++) { res += c; } } return res; } // Driver code public static void Main(String[] args) { // Creating the linked list Node head = newNode('a'); head.next = newNode('5'); head.next.next = newNode('b'); head.next.next.next = newNode('r'); Console.WriteLine(decodeList(head)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to decode a linked list // Linked list node class Node { constructor() { this.data = 0; this.next = null; } } // Utility function to create a new Node function newNode(data) { var temp = new Node(); temp.data = data; temp.next = null; return temp; } // Function to append nodes to a list function append(head_ref, new_data) { var new_node = new Node(); var last = head_ref; new_node.data = new_data; new_node.next = null; if (head_ref == null) { head_ref = new_node; return; } while (last.next != null) last = last.next; last.next = new_node; return; } // Function to print list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Function to decode the linked list function decodeList(head) { // Pointer used to traverse through all // the nodes in the list var p = head; // String to store the decoded message var res = ""; var count; // While there are nodes left while (p != null) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character var c = p.data; if (p.next != null) { var temp = p.next; // If current node is a digit if (temp != null && temp.data >= "0" && temp.data <= "9") { // Generate the integer from // the consecutive digits while (temp != null && temp.data >= "0" && temp.data <= "9") { count = count * 10 + (temp.data - "0"); temp = temp.next; } p = temp; } else { count = 1; p = p.next; } } else { count = 1; p = p.next; } // Repeat the character count times for (var i = 0; i < count; i++) { res += c; } } return res; } // Driver code // Creating the linked list var head = newNode("a"); head.next = newNode("5"); head.next.next = newNode("b"); head.next.next.next = newNode("r"); document.write(decodeList(head)); </script>
aaaaabr
princiraj1992
29AjayKumar
ManishKumar85
gp6
rutvik_56
rdtank
encoding-decoding
String-Run Length Encoding
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 550,
"s": 28,
"text": "Given an encoded Linked List which is encoded using the Run Length Encoding algorithm. The task is to decode the given linked list and generate the input string.Run Length Encoding: In run length encoding, the input string is encoded by replacing a substring of repeated character in the string by the character followed by its count. If the character is single and is non-repeating than it’s count is not added. For Example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3dex6”Examples: "
},
{
"code": null,
"e": 1002,
"s": 550,
"text": "Input : List = a->5->b->r->3->NULL Output : string = “aaaaabrrr” Explanation : From the linked list, the character is ‘a’ and it’s count is 5 so the character is repeated 5 times. The next character is ‘b’ and the next character to it is not a number hence the character ‘b’ is repeated only once. The next character is ‘r’ and the count is 3 hence the character is repeated 3 times.Input : List = a->b->r->3->a->3->NULL Output : string = “abrrraaa” "
},
{
"code": null,
"e": 1016,
"s": 1004,
"text": "Approach: "
},
{
"code": null,
"e": 1050,
"s": 1016,
"text": "Traverse through the linked list."
},
{
"code": null,
"e": 1095,
"s": 1050,
"text": "Store the current character in a variable c."
},
{
"code": null,
"e": 1177,
"s": 1095,
"text": "Check if the next node is a number and store the number in count else count is 1."
},
{
"code": null,
"e": 1225,
"s": 1177,
"text": "Append the character c to the list count times."
},
{
"code": null,
"e": 1278,
"s": 1225,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1282,
"s": 1278,
"text": "C++"
},
{
"code": null,
"e": 1287,
"s": 1282,
"text": "Java"
},
{
"code": null,
"e": 1295,
"s": 1287,
"text": "Python3"
},
{
"code": null,
"e": 1298,
"s": 1295,
"text": "C#"
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": "Javascript"
},
{
"code": "// C++ program to decode a linked list#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node { char data; struct Node* next;}; // Utility function to create a new NodeNode* newNode(char data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Function to append nodes to a listvoid append(struct Node* head_ref, char new_data){ struct Node* new_node = new Node; struct Node* last = head_ref; new_node->data = new_data; new_node->next = NULL; if (head_ref == NULL) { head_ref = new_node; return; } while (last->next != NULL) last = last->next; last->next = new_node; return;} // Function to print listvoid printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Function to decode the linked liststring decodeList(Node* head){ Node* p = head; string res = \"\"; int count; // While there are nodes left while (p) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character char c = p->data; if (p->next) { Node* temp = p->next; // If current node is a digit if (temp && temp->data >= '0' && temp->data <= '9') { // Generate the integer from // the consecutive digits while (temp && temp->data >= '0' && temp->data <= '9') { count = count * 10 + (temp->data - '0'); temp = temp->next; } p = temp; } else { count = 1; p = p->next; } } else { count = 1; p = p->next; } // Repeat the character count times for (int i = 0; i < count; i++) { res += c; } } return res;} // Driver codeint main(){ // Creating the linked list Node* head = newNode('a'); head->next = newNode('5'); head->next->next = newNode('b'); head->next->next->next = newNode('r'); cout << decodeList(head); return 0;}",
"e": 3544,
"s": 1309,
"text": null
},
{
"code": "// Java program to decode a linked listclass GFG { // Linked list node static class Node { char data; Node next; }; // Utility function to create a new Node static Node newNode(char data) { Node temp = new Node(); temp.data = data; temp.next = null; return temp; } // Function to append nodes to a list static void append(Node head_ref, char new_data) { Node new_node = new Node(); Node last = head_ref; new_node.data = new_data; new_node.next = null; if (head_ref == null) { head_ref = new_node; return; } while (last.next != null) last = last.next; last.next = new_node; return; } // Function to print list static void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } // Function to decode the linked list static String decodeList(Node head) { // Pointer used to traverse through all // the nodes in the list Node p = head; // String to store the decoded message String res = \"\"; int count; // While there are nodes left while (p != null) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character char c = p.data; if (p.next != null) { Node temp = p.next; // If current node is a digit if (temp != null && temp.data >= '0' && temp.data <= '9') { // Generate the integer from // the consecutive digits while (temp != null && temp.data >= '0' && temp.data <= '9') { count = count * 10 + (temp.data - '0'); temp = temp.next; } p = temp; } else { count = 1; p = p.next; } } else { count = 1; p = p.next; } // Repeat the character count times for (int i = 0; i < count; i++) { res += c; } } return res; } // Driver code public static void main(String args[]) { // Creating the linked list Node head = newNode('a'); head.next = newNode('5'); head.next.next = newNode('b'); head.next.next.next = newNode('r'); System.out.println(decodeList(head)); }} /* This code contributed by PrinciRaj1992 */",
"e": 6320,
"s": 3544,
"text": null
},
{
"code": "# Python3 program to decode a linked list # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Utility function to create a Nodedef newNode(data): temp = Node(data); temp.next = None; return temp; # Function to append nodes to a listdef append(head_ref, new_data): new_node = Node; last = head_ref; new_node.data = new_data; new_node.next = None; if (head_ref == None): head_ref = new_node; return; while (last.next != None): last = last.next; last.next = new_node; return; # Function to print listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next; # Function to decode the linked listdef decodeList(head): p = head; res = \"\"; count = 0 # While there are nodes left while (p != None): # To store the count by which the current # character needs to be repeated count = 0; # Get the current character c = p.data; if (p.next != None): temp = p.next; # If current node is a digit if (temp != None and ord(temp.data) >= ord('0') and ord(temp.data) <= ord('9')): # Generate the integer from # the consecutive digits while (temp != None and ord(temp.data) >= ord('0') and ord(temp.data) <= ord('9')): count = count * 10 + ord(temp.data) - ord('0') temp = temp.next; p = temp; else: count = 1; p = p.next; else: count = 1; p = p.next; # Repeat the character count times for i in range(0, count): res += c; return res; # Driver codeif __name__=='__main__': # Creating the linked list head = newNode('a'); head.next = newNode('5'); head.next.next = newNode('b'); head.next.next.next = newNode('r'); print(decodeList(head)) # This code is contributed by rutvik_56",
"e": 8491,
"s": 6320,
"text": null
},
{
"code": "// C# program to decode a linked listusing System; public class GFG { // Linked list node public class Node { public char data; public Node next; }; // Utility function to create a new Node static Node newNode(char data) { Node temp = new Node(); temp.data = data; temp.next = null; return temp; } // Function to append nodes to a list static void append(Node head_ref, char new_data) { Node new_node = new Node(); Node last = head_ref; new_node.data = new_data; new_node.next = null; if (head_ref == null) { head_ref = new_node; return; } while (last.next != null) last = last.next; last.next = new_node; return; } // Function to print list static void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Function to decode the linked list static String decodeList(Node head) { // Pointer used to traverse through all // the nodes in the list Node p = head; // String to store the decoded message String res = \"\"; int count; // While there are nodes left while (p != null) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character char c = p.data; if (p.next != null) { Node temp = p.next; // If current node is a digit if (temp != null && temp.data >= '0' && temp.data <= '9') { // Generate the integer from // the consecutive digits while (temp != null && temp.data >= '0' && temp.data <= '9') { count = count * 10 + (temp.data - '0'); temp = temp.next; } p = temp; } else { count = 1; p = p.next; } } else { count = 1; p = p.next; } // Repeat the character count times for (int i = 0; i < count; i++) { res += c; } } return res; } // Driver code public static void Main(String[] args) { // Creating the linked list Node head = newNode('a'); head.next = newNode('5'); head.next.next = newNode('b'); head.next.next.next = newNode('r'); Console.WriteLine(decodeList(head)); }} // This code is contributed by 29AjayKumar",
"e": 11294,
"s": 8491,
"text": null
},
{
"code": "<script> // JavaScript program to decode a linked list // Linked list node class Node { constructor() { this.data = 0; this.next = null; } } // Utility function to create a new Node function newNode(data) { var temp = new Node(); temp.data = data; temp.next = null; return temp; } // Function to append nodes to a list function append(head_ref, new_data) { var new_node = new Node(); var last = head_ref; new_node.data = new_data; new_node.next = null; if (head_ref == null) { head_ref = new_node; return; } while (last.next != null) last = last.next; last.next = new_node; return; } // Function to print list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } // Function to decode the linked list function decodeList(head) { // Pointer used to traverse through all // the nodes in the list var p = head; // String to store the decoded message var res = \"\"; var count; // While there are nodes left while (p != null) { // To store the count by which the current // character needs to be repeated count = 0; // Get the current character var c = p.data; if (p.next != null) { var temp = p.next; // If current node is a digit if (temp != null && temp.data >= \"0\" && temp.data <= \"9\") { // Generate the integer from // the consecutive digits while (temp != null && temp.data >= \"0\" && temp.data <= \"9\") { count = count * 10 + (temp.data - \"0\"); temp = temp.next; } p = temp; } else { count = 1; p = p.next; } } else { count = 1; p = p.next; } // Repeat the character count times for (var i = 0; i < count; i++) { res += c; } } return res; } // Driver code // Creating the linked list var head = newNode(\"a\"); head.next = newNode(\"5\"); head.next.next = newNode(\"b\"); head.next.next.next = newNode(\"r\"); document.write(decodeList(head)); </script>",
"e": 13820,
"s": 11294,
"text": null
},
{
"code": null,
"e": 13828,
"s": 13820,
"text": "aaaaabr"
},
{
"code": null,
"e": 13844,
"s": 13830,
"text": "princiraj1992"
},
{
"code": null,
"e": 13856,
"s": 13844,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13870,
"s": 13856,
"text": "ManishKumar85"
},
{
"code": null,
"e": 13874,
"s": 13870,
"text": "gp6"
},
{
"code": null,
"e": 13884,
"s": 13874,
"text": "rutvik_56"
},
{
"code": null,
"e": 13891,
"s": 13884,
"text": "rdtank"
},
{
"code": null,
"e": 13909,
"s": 13891,
"text": "encoding-decoding"
},
{
"code": null,
"e": 13936,
"s": 13909,
"text": "String-Run Length Encoding"
},
{
"code": null,
"e": 13948,
"s": 13936,
"text": "Linked List"
},
{
"code": null,
"e": 13960,
"s": 13948,
"text": "Linked List"
}
] |
logical_or in C++
|
05 Sep, 2018
logical_or in C++ is a binary function object class which returns the result of the logical “or” operation between its two arguments (as returned by operator ||).
Syntax:
template struct logical_or : binary_function
{
T operator() (const T& a, const T& b) const {return a||b;}
};
Parameters: (T)Type of the arguments and return type of the function call. The type shall support the operation (binary operator||).
Member types:
a: Type of the first argument in member operator()
b: Type of the second argument in member operator()
result_type: Type returned by member operator()
Below is the program to implement logical_and using std::transform():
#include <bits/stdc++.h>using namespace std; int main(){ // First array int z[] = { 1, 0, 1, 0 }; // Second array int y[] = { 1, 1, 0, 0 }; int n = 4; // Result array int result[n]; // transform applies logical_or // on both the array transform(z, z + n, y, result, logical_or<int>()); cout<< "Logical OR:\n"; for (int i = 0; i < n; i++) // Printing the result array cout << z[i] << " OR " << y[i] << " = " << result[i] << "\n"; return 0;}
Logical OR:
1 OR 1 = 1
0 OR 1 = 1
1 OR 0 = 1
0 OR 0 = 0
CPP-Functions
CPP-Library
C++
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++
Unordered Sets in C++ Standard Template Library
Pair in C++ Standard Template Library (STL)
std::string class in C++
Friend class and function in C++
Queue in C++ Standard Template Library (STL)
List in C++ Standard Template Library (STL)
Inline Functions in C++
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2018"
},
{
"code": null,
"e": 191,
"s": 28,
"text": "logical_or in C++ is a binary function object class which returns the result of the logical “or” operation between its two arguments (as returned by operator ||)."
},
{
"code": null,
"e": 199,
"s": 191,
"text": "Syntax:"
},
{
"code": null,
"e": 314,
"s": 199,
"text": "template struct logical_or : binary_function \n{\n T operator() (const T& a, const T& b) const {return a||b;}\n};\n"
},
{
"code": null,
"e": 447,
"s": 314,
"text": "Parameters: (T)Type of the arguments and return type of the function call. The type shall support the operation (binary operator||)."
},
{
"code": null,
"e": 461,
"s": 447,
"text": "Member types:"
},
{
"code": null,
"e": 512,
"s": 461,
"text": "a: Type of the first argument in member operator()"
},
{
"code": null,
"e": 564,
"s": 512,
"text": "b: Type of the second argument in member operator()"
},
{
"code": null,
"e": 612,
"s": 564,
"text": "result_type: Type returned by member operator()"
},
{
"code": null,
"e": 682,
"s": 612,
"text": "Below is the program to implement logical_and using std::transform():"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ // First array int z[] = { 1, 0, 1, 0 }; // Second array int y[] = { 1, 1, 0, 0 }; int n = 4; // Result array int result[n]; // transform applies logical_or // on both the array transform(z, z + n, y, result, logical_or<int>()); cout<< \"Logical OR:\\n\"; for (int i = 0; i < n; i++) // Printing the result array cout << z[i] << \" OR \" << y[i] << \" = \" << result[i] << \"\\n\"; return 0;}",
"e": 1208,
"s": 682,
"text": null
},
{
"code": null,
"e": 1265,
"s": 1208,
"text": "Logical OR:\n1 OR 1 = 1\n0 OR 1 = 1\n1 OR 0 = 1\n0 OR 0 = 0\n"
},
{
"code": null,
"e": 1279,
"s": 1265,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1291,
"s": 1279,
"text": "CPP-Library"
},
{
"code": null,
"e": 1295,
"s": 1291,
"text": "C++"
},
{
"code": null,
"e": 1299,
"s": 1295,
"text": "CPP"
},
{
"code": null,
"e": 1397,
"s": 1299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1421,
"s": 1397,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1441,
"s": 1421,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1489,
"s": 1441,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1533,
"s": 1489,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1558,
"s": 1533,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1591,
"s": 1558,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1636,
"s": 1591,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1680,
"s": 1636,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1704,
"s": 1680,
"text": "Inline Functions in C++"
}
] |
Python program to solve quadratic equation
|
29 Aug, 2020
Given a quadratic equation the task is solve the equation or find out the roots of the equation. Standard form of quadratic equation is –
ax2 + bx + c
where,
a, b, and c are coefficient and real numbers and also a ≠ 0.
If a is equal to 0 that equation is not valid quadratic equation.
Examples:
Input :a = 1, b = 2, c = 1
Output :
Roots are real and same
-1.0
Input :a = 2, b = 2, c = 1
Output :
Roots are complex
-0.5 + i 2.0
-0.5 - i 2.0
Input :a = 1, b = 10, c = -24
Output :
Roots are real and different
2.0
-12.0
Method 1: Using the direct formula
Using the below quadratic formula we can find the root of the quadratic equation.
There are following important cases.
If b*b < 4*a*c, then roots are complex
(not real).
For example roots of x2 + x + 1, roots are
-0.5 + i1.73205 and -0.5 - i1.73205
If b*b == 4*a*c, then roots are real
and both roots are same.
For example, roots of x2 - 2x + 1 are 1 and 1
If b*b > 4*a*c, then roots are real
and different.
For example, roots of x2 - 7x - 12 are 3 and 4
# Python program to find roots of quadratic equation
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print(" real and different roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print(" real and same roots")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
# Driver Program
a = 1
b = 10
c = -24
# If a is 0, then incorrect equation
if a == 0:
print("Input correct quadratic equation")
else:
equationroots(a, b, c)
Output:
real and different roots
2.0
-12.0
Method 2: Using the complex math module
First, we have to calculate the discriminant and then find two solution of quadratic equation using cmath module.
# import complex math module
import cmath
a = 1
b = 4
c = 2
# calculating the discriminant
dis = (b**2) - (4 * a*c)
# find two results
ans1 = (-b-cmath.sqrt(dis))/(2 * a)
ans2 = (-b + cmath.sqrt(dis))/(2 * a)
# printing the results
print('The roots are')
print(ans1)
print(ans2)
Output:
The roots are
(-3.414213562373095+0j)
(-0.5857864376269049+0j)
Python Cmath-library
Python math-library
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 58,
"s": 27,
"text": " \n29 Aug, 2020\n"
},
{
"code": null,
"e": 196,
"s": 58,
"text": "Given a quadratic equation the task is solve the equation or find out the roots of the equation. Standard form of quadratic equation is –"
},
{
"code": null,
"e": 345,
"s": 196,
"text": "ax2 + bx + c\nwhere,\na, b, and c are coefficient and real numbers and also a ≠ 0.\nIf a is equal to 0 that equation is not valid quadratic equation.\n"
},
{
"code": null,
"e": 355,
"s": 345,
"text": "Examples:"
},
{
"code": null,
"e": 587,
"s": 355,
"text": "Input :a = 1, b = 2, c = 1 \nOutput : \nRoots are real and same\n-1.0\n\nInput :a = 2, b = 2, c = 1\nOutput :\nRoots are complex\n-0.5 + i 2.0\n-0.5 - i 2.0\n\nInput :a = 1, b = 10, c = -24 \nOutput : \nRoots are real and different\n2.0\n-12.0\n"
},
{
"code": null,
"e": 623,
"s": 587,
"text": "Method 1: Using the direct formula "
},
{
"code": null,
"e": 705,
"s": 623,
"text": "Using the below quadratic formula we can find the root of the quadratic equation."
},
{
"code": null,
"e": 742,
"s": 705,
"text": "There are following important cases."
},
{
"code": null,
"e": 1082,
"s": 742,
"text": "If b*b < 4*a*c, then roots are complex\n(not real).\nFor example roots of x2 + x + 1, roots are\n-0.5 + i1.73205 and -0.5 - i1.73205\n\nIf b*b == 4*a*c, then roots are real \nand both roots are same.\nFor example, roots of x2 - 2x + 1 are 1 and 1\n\nIf b*b > 4*a*c, then roots are real \nand different.\nFor example, roots of x2 - 7x - 12 are 3 and 4"
},
{
"code": "\n\n\n\n\n\n\n# Python program to find roots of quadratic equation \nimport math \n \n \n# function for finding roots \ndef equationroots( a, b, c): \n \n # calculating discriminant using formula \n dis = b * b - 4 * a * c \n sqrt_val = math.sqrt(abs(dis)) \n \n # checking condition for discriminant \n if dis > 0: \n print(\" real and different roots \") \n print((-b + sqrt_val)/(2 * a)) \n print((-b - sqrt_val)/(2 * a)) \n \n elif dis == 0: \n print(\" real and same roots\") \n print(-b / (2 * a)) \n \n # when discriminant is less than 0 \n else: \n print(\"Complex Roots\") \n print(- b / (2 * a), \" + i\", sqrt_val) \n print(- b / (2 * a), \" - i\", sqrt_val) \n \n# Driver Program \na = 1\nb = 10\nc = -24\n \n# If a is 0, then incorrect equation \nif a == 0: \n print(\"Input correct quadratic equation\") \n \nelse: \n equationroots(a, b, c) \n\n\n\n\n\n",
"e": 2026,
"s": 1092,
"text": null
},
{
"code": null,
"e": 2034,
"s": 2026,
"text": "Output:"
},
{
"code": null,
"e": 2070,
"s": 2034,
"text": "real and different roots\n2.0\n-12.0\n"
},
{
"code": null,
"e": 2110,
"s": 2070,
"text": "Method 2: Using the complex math module"
},
{
"code": null,
"e": 2224,
"s": 2110,
"text": "First, we have to calculate the discriminant and then find two solution of quadratic equation using cmath module."
},
{
"code": "\n\n\n\n\n\n\n# import complex math module \nimport cmath \n \na = 1\nb = 4\nc = 2\n \n# calculating the discriminant \ndis = (b**2) - (4 * a*c) \n \n# find two results \nans1 = (-b-cmath.sqrt(dis))/(2 * a) \nans2 = (-b + cmath.sqrt(dis))/(2 * a) \n \n# printing the results \nprint('The roots are') \nprint(ans1) \nprint(ans2) \n\n\n\n\n\n",
"e": 2550,
"s": 2234,
"text": null
},
{
"code": null,
"e": 2558,
"s": 2550,
"text": "Output:"
},
{
"code": null,
"e": 2622,
"s": 2558,
"text": "The roots are\n(-3.414213562373095+0j)\n(-0.5857864376269049+0j)\n"
},
{
"code": null,
"e": 2645,
"s": 2622,
"text": "\nPython Cmath-library\n"
},
{
"code": null,
"e": 2667,
"s": 2645,
"text": "\nPython math-library\n"
},
{
"code": null,
"e": 2676,
"s": 2667,
"text": "\nPython\n"
},
{
"code": null,
"e": 2694,
"s": 2676,
"text": "\nPython Programs\n"
}
] |
Java Program to Check Whether the Character is Vowel or Consonant
|
17 Mar, 2021
For any given character, we need to check if it is a vowel or a consonant. As we know, vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ and all the other characters (i.e. ‘b’, ‘c’, ‘d’, ‘f’ .....) are consonants.
Examples:
Input : char = 'r'
Output : Consonant
Input : char = 'e'
Output : Vowel
Here, in the below implementation we will check if the stated character corresponds to any of the five vowels. And if it matches, “Vowel” is printed, else “Consonant” is printed.
Example 1:
Java
// java program to check whether input
// character is a vowel or consonant
import java.io.*;
public class geek {
// Function to find whether an input
// character is vowel or not
static void Vowel_Or_Consonant(char y)
{
if (y == 'a' || y == 'e' || y == 'i' || y == 'o'
|| y == 'u')
System.out.println("It is a Vowel.");
else
System.out.println("It is a Consonant.");
}
// The Driver code
static public void main(String[] args)
{
Vowel_Or_Consonant('b');
Vowel_Or_Consonant('u');
}
}
It is a Consonant.
It is a Vowel.
Example 2:
Alteration for capital letters.
Java
// java program to check whether input
// character is a vowel or consonant
import java.io.*;
public class geek {
// Function to find whether an input
// character is vowel or not
static void Vowel_Or_Consonant(char y)
{
if (y == 'a' || y == 'e' || y == 'i' || y == 'o'
|| y == 'u' || y == 'A' || y == 'E' || y == 'I'
|| y == 'O' || y == 'U')
System.out.println("It is a Vowel.");
else
System.out.println("It is a Consonant.");
}
// The Driver code
static public void main(String[] args)
{
Vowel_Or_Consonant('W');
Vowel_Or_Consonant('I');
}
}
It is a Consonant.
It is a Vowel.
Example 3:
indexOf() Method
Java
// java program to check whether input
// character is a vowel or consonant
import java.io.*;
class GFG {
// Function to find whether an input
// character is vowel or not
static String isVowel(char ch)
{
// Make the list of vowels
String str = "aeiouAEIOU";
return (str.indexOf(ch) != -1) ? "Vowel"
: "Consonant";
}
// Driver Code
public static void main(String[] args)
{
System.out.println("It is a " + isVowel('a'));
System.out.println("It is a " + isVowel('x'));
}
}
It is a Vowel
It is a Consonant
java-basics
Java
Java Programs
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 58,
"s": 27,
"text": " \n17 Mar, 2021\n"
},
{
"code": null,
"e": 257,
"s": 58,
"text": "For any given character, we need to check if it is a vowel or a consonant. As we know, vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ and all the other characters (i.e. ‘b’, ‘c’, ‘d’, ‘f’ .....) are consonants."
},
{
"code": null,
"e": 269,
"s": 257,
"text": "Examples: "
},
{
"code": null,
"e": 342,
"s": 269,
"text": "Input : char = 'r'\nOutput : Consonant\n\nInput : char = 'e'\nOutput : Vowel"
},
{
"code": null,
"e": 521,
"s": 342,
"text": "Here, in the below implementation we will check if the stated character corresponds to any of the five vowels. And if it matches, “Vowel” is printed, else “Consonant” is printed."
},
{
"code": null,
"e": 532,
"s": 521,
"text": "Example 1:"
},
{
"code": null,
"e": 537,
"s": 532,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// java program to check whether input \n// character is a vowel or consonant \n \nimport java.io.*; \n \npublic class geek { \n \n // Function to find whether an input \n // character is vowel or not \n static void Vowel_Or_Consonant(char y) \n { \n if (y == 'a' || y == 'e' || y == 'i' || y == 'o'\n || y == 'u') \n System.out.println(\"It is a Vowel.\"); \n else\n System.out.println(\"It is a Consonant.\"); \n } \n \n // The Driver code \n static public void main(String[] args) \n { \n Vowel_Or_Consonant('b'); \n Vowel_Or_Consonant('u'); \n } \n}\n\n\n\n\n\n",
"e": 1178,
"s": 547,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1178,
"text": "It is a Consonant.\nIt is a Vowel."
},
{
"code": null,
"e": 1223,
"s": 1212,
"text": "Example 2:"
},
{
"code": null,
"e": 1255,
"s": 1223,
"text": "Alteration for capital letters."
},
{
"code": null,
"e": 1260,
"s": 1255,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// java program to check whether input \n// character is a vowel or consonant \n \nimport java.io.*; \n \npublic class geek { \n \n // Function to find whether an input \n // character is vowel or not \n static void Vowel_Or_Consonant(char y) \n { \n if (y == 'a' || y == 'e' || y == 'i' || y == 'o'\n || y == 'u' || y == 'A' || y == 'E' || y == 'I'\n || y == 'O' || y == 'U') \n System.out.println(\"It is a Vowel.\"); \n else\n System.out.println(\"It is a Consonant.\"); \n } \n \n // The Driver code \n static public void main(String[] args) \n { \n Vowel_Or_Consonant('W'); \n Vowel_Or_Consonant('I'); \n } \n}\n\n\n\n\n\n",
"e": 1973,
"s": 1270,
"text": null
},
{
"code": null,
"e": 2007,
"s": 1973,
"text": "It is a Consonant.\nIt is a Vowel."
},
{
"code": null,
"e": 2018,
"s": 2007,
"text": "Example 3:"
},
{
"code": null,
"e": 2035,
"s": 2018,
"text": "indexOf() Method"
},
{
"code": null,
"e": 2040,
"s": 2035,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// java program to check whether input \n// character is a vowel or consonant \n \nimport java.io.*; \n \nclass GFG { \n // Function to find whether an input \n // character is vowel or not \n static String isVowel(char ch) \n { \n // Make the list of vowels \n String str = \"aeiouAEIOU\"; \n return (str.indexOf(ch) != -1) ? \"Vowel\"\n : \"Consonant\"; \n } \n \n // Driver Code \n public static void main(String[] args) \n { \n System.out.println(\"It is a \" + isVowel('a')); \n System.out.println(\"It is a \" + isVowel('x')); \n } \n}\n\n\n\n\n\n",
"e": 2676,
"s": 2050,
"text": null
},
{
"code": null,
"e": 2709,
"s": 2676,
"text": "It is a Vowel\nIt is a Consonant\n"
},
{
"code": null,
"e": 2723,
"s": 2709,
"text": "\njava-basics\n"
},
{
"code": null,
"e": 2730,
"s": 2723,
"text": "\nJava\n"
},
{
"code": null,
"e": 2746,
"s": 2730,
"text": "\nJava Programs\n"
},
{
"code": null,
"e": 2756,
"s": 2746,
"text": "\nStrings\n"
},
{
"code": null,
"e": 2764,
"s": 2756,
"text": "Strings"
},
{
"code": null,
"e": 2769,
"s": 2764,
"text": "Java"
}
] |
Data Visualization using Seaborn. I am back with the seaborn tutorial... | by Mohit Sharma | Towards Data Science
|
I am back with the seaborn tutorial. Last time we learn about Data Visualization using Matplotlib.
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
Seaborn is a statistical plotting library
It has beautiful default styles
It also is designed to work very well with Pandas dataframe objects.
To install the latest release of seaborn, you can use pip:
pip install seaborn
It’s also possible to install the released version using conda:
conda install seaborn
Alternatively, you can use pip to install the development version directly from github:
pip install git+https://github.com/mwaskom/seaborn.git
Another option would be to to clone the github repository and install from your local copy:
pip install . Dependencies Python 2.7 or 3.5+
numpy (>= 1.9.3)scipy (>= 0.14.0)matplotlib (>= 1.4.3)pandas (>= 0.15.2)
statsmodels (>= 0.5.0)
TestingTo test seaborn, run make test in the root directory of the source distribution. This runs the unit test suite (using pytest, but many older tests use nose asserts). It also runs the example code in function docstrings to smoke-test a broader and more realistic range of example usage.The full set of tests requires an internet connection to download the example datasets (if they haven’t been previously cached), but the unit tests should be possible to run offline.
Bugs
Please report any bugs you encounter through the github issue tracker. It will be most helpful to include a reproducible example on one of the example datasets (accessed through load_dataset()). It is difficult debug any issues without knowing the versions of seaborn and matplotlib you are using, as well as what matplotlib backend you are using to draw the plots, so please include those in your bug report.
Note: This article assumes you are familiar with python basic and data visualization. Still, face any problem do comment or email me your query.
Refer Our — Data Visualization Using Matplotlib
www.amazon.in
www.amazon.in
In [1]:
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline
In [2]:
census_data = pd.read_csv('census_data.csv')census_data.describe()
Out[2]:
In [3]:
census_data.head()
Out[3]:
In [4]:
census_data.info()
Out[4]:
Statistical analysis is a process of understanding how variables in a dataset relate to each other and how those relationships depend on other variables. Visualization can be a core component of this process because, when data are visualized properly, the human visual system can see trends and patterns that indicate a relationship.
We will discuss most of the seaborn functions today-
The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two variables using a cloud of points, where each point represents an observation in the dataset. This depiction allows the eye to infer a substantial amount of information about whether there is any meaningful relationship between them.
There are several ways to draw a scatter plot in seaborn. The most basic, which should be used when both variables are numeric, is the scatterplot() function.
In [5]:
sns.scatterplot(x='capital_loss',y='capital_gain',data=census_data)
Out[5]:
<matplotlib.axes._subplots.AxesSubplot at 0xaafb2b0>
In [6]:
sns.set(style="darkgrid")tips = sns.load_dataset("tips") #tips is inbuild dataset in seabornsns.relplot(x="total_bill", y="tip", data=tips);
Note: The scatterplot() is the default kind in relplot() (it can also be forced by setting kind=”scatter”):
In [7]:
# adding some additional parameterssns.scatterplot(x='capital_loss',y='capital_gain',hue='marital_status',data=census_data)# hue: Can be either categorical or numeric, although color mapping will# behave differently in latter case.
Out[7]:
<matplotlib.axes._subplots.AxesSubplot at 0xac406a0>
In [8]:
sns.scatterplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',data=census_data)
Out[8]:
<matplotlib.axes._subplots.AxesSubplot at 0xadc95c0>
In [9]:
# As I said above the scatterplot() is the default kind in relplot() (it can also be forced by setting kind="scatter"):# see differencesns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',data=census_data)
Out[9]:
<seaborn.axisgrid.FacetGrid at 0xacdeb70>
Scatter plots are highly effective, but there is no universally optimal type of visualization. Instead, the visual representation should be adapted for the specifics of the dataset and to the question you are trying to answer with the plot.
With some datasets, you may want to understand changes in one variable as a function of time, or a similarly continuous variable. In this situation, a good choice is to draw a line plot. In Seaborn, this can be accomplished by the lineplot() function, either directly or with relplot() by setting kind=” line”:
In [10]:
df = pd.DataFrame(dict(time=np.arange(500), value=np.random.randn(500).cumsum()))g = sns.relplot(x="time", y="value", kind="line", data=df)g.fig.autofmt_xdate()"""Figure-level interface for drawing relational plots onto a FacetGrid.This function provides access to several different axes-level functionsthat show the relationship between two variables with semantic mappingsof subsets. The ``kind`` parameter selects the underlying axes-levelfunction to use:- :func:`scatterplot` (with ``kind="scatter"``; the default)- :func:`lineplot` (with ``kind="line"``)"""
Out[10]:
In [11]:
age_vs_hours_per_week = sns.relplot(x="age", y="hours_per_week", kind="line", data=census_data
Out[11]:
In [12]:
age_vs_hours_per_week = sns.relplot(x="age", y="hours_per_week", kind="line",sort=False, data=census_data)
Out[12]:
Lineplot() assumes that you are most often trying to draw y as a function of x, the default behavior is to sort the data by the x values before plotting. However, this can be disabled:
We’ve emphasized in this tutorial that, while these functions can show several semantic variables at once, it’s not always effective to do so. But what about when you do want to understand how a relationship between two variables depends on more than one other variable?
The best approach may be to make more than one plot. Because relplot() is based on the FacetGrid, this is easy to do. To show the influence of an additional variable, instead of assigning it to one of the semantic roles in the plot, use it to “facet” the visualization. This means that you make multiple axes and plot subsets of the data on each of them:
In [13]:
sns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',col='gender',data=census_data)
Out[13]:
<seaborn.axisgrid.FacetGrid at 0xc8a1240>
In [14]:
sns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',col='income_bracket',data=census_data)
Out[14]:
<seaborn.axisgrid.FacetGrid at 0xcdc25c0>
You can also show the influence two variables this way: one by faceting on the columns and one by faceting on the rows. As you start adding more variables to the grid, you may want to decrease the figure size. Remember that the size FacetGrid is parameterized by the height and aspect ratio of each facet:
In [15]:
sns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',col='income_bracket',row='race',height=5,data=census_data)
Out[15]:
<seaborn.axisgrid.FacetGrid at 0xcdc2320>
In the relational plot tutorial we saw how to use different visual representations to show the relationship between multiple variables in a dataset. In the examples, we focused on cases where the main relationship was between two numerical variables. If one of the main variables is “categorical” (divided into discrete groups) it may be helpful to use a more specialized approach to visualization.
In seaborn, there are several different ways to visualize a relationship involving categorical data. Similar to the relationship between relplot() and either scatterplot() or lineplot(), there are two ways to make these plots. There are a number of axes-level functions for plotting categorical data in different ways and a figure-level interface, catplot(), that gives unified higher-level access to them.
It’s helpful to think of the different categorical plot kinds as belonging to three different families, which we’ll discuss in detail below. They are:
Categorical scatterplots:
stripplot() (with kind=”strip”; the default)swarmplot() (with kind=”swarm”)
Categorical distribution plots:
boxplot() (with kind=”box”)violinplot() (with kind=”violin”)boxenplot() (with kind=”boxen”)
Categorical estimate plots:
pointplot() (with kind=”point”)barplot() (with kind=”bar”)countplot() (with kind=”count”)
These families represent the data using different levels of granularity.
The default representation of the data in catplot() uses a scatterplot. There are actually two different categorical scatter plots in seaborn. They take different approaches to resolving the main challenge in representing categorical data with a scatter plot, which is that all of the points belonging to one category would fall on the same position along the axis corresponding to the categorical variable. The approach used by stripplot(), which is the default “kind” in catplot() is to adjust the positions of points on the categorical axis with a small amount of random “jitter”:
In [16]:
sns.catplot(x="age",y="marital_status",data=census_data)
Out[16]:
<seaborn.axisgrid.FacetGrid at 0xdb18470>
The second approach adjusts the points along the categorical axis using an algorithm that prevents them from overlapping. It can give a better representation of the distribution of observations, although it only works well for relatively small datasets. This kind of plot is sometimes called a “beeswarm” and is drawn in seaborn by swarmplot(), which is activated by setting kind=”swarm” in catplot():
In [27]:
#sns.catplot(x="age",y="relationship",kind='swarm',data=census_data)# or#sns.swarmplot(x="relationship",y="age",data=census_data)sns.catplot(x="day", y="total_bill", kind="swarm", data=tips);
Out[27]:
Similar to the relational plots, it’s possible to add another dimension to a categorical plot by using a hue semantic. (The categorical plots do not currently support size or style semantics). Each different categorical plotting function handles the hue semantic differently. For the scatter plots, it is only necessary to change the color of the points:
In [29]:
sns.catplot(x="day", y="total_bill", hue="sex", kind="swarm", data=tips);
Out[29]:
The first is the familiar boxplot(). This kind of plot shows the three quartile values of the distribution along with extreme values. The “whiskers” extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. This means that each value in the boxplot corresponds to an actual observation in the data.
In [32]:
sns.catplot(x="age",y="marital_status",kind='box',data=census_data)
Out[32]:
<seaborn.axisgrid.FacetGrid at 0xd411860>
When adding a hue semantic, the box for each level of the semantic variable is moved along the categorical axis so they don’t overlap:
In [37]:
sns.catplot(x="age",y="marital_status",kind='box',hue='gender',data=census_data)
Out[37]:
<seaborn.axisgrid.FacetGrid at 0xde8a8d0>
A different approach is a violinplot(), which combines a boxplot with the kernel density estimation procedure described in the distributions tutorial:
In [38]:
sns.catplot(x="age",y="marital_status",kind='violin',data=census_data)
Out[38]:
<seaborn.axisgrid.FacetGrid at 0x184c4080>
This approach uses the kernel density estimate to provide a richer description of the distribution of values. Additionally, the quartile and whikser values from the boxplot are shown inside the violin. The downside is that, because the violinplot uses a KDE, there are some other parameters that may need tweaking, adding some complexity relative to the straightforward boxplot:
In [41]:
sns.catplot(x="age",y="marital_status",kind='violin',bw=.15, cut=0,data=census_data)
Out[41]:
<seaborn.axisgrid.FacetGrid at 0xfdea320>
For other applications, rather than showing the distribution within each category, you might want to show an estimate of the central tendency of the values. Seaborn has two main ways to show this information. Importantly, the basic API for these functions is identical to that for the ones discussed above.
A familiar style of plot that accomplishes this goal is a bar plot. In seaborn, the barplot() function operates on a full dataset and applies a function to obtain the estimate (taking the mean by default). When there are multiple observations in each category, it also uses bootstrapping to compute a confidence interval around the estimate and plots that using error bars:
In [46]:
sns.catplot(x="income_bracket",y="age",kind='bar',data=census_data)
Out[46]:
<seaborn.axisgrid.FacetGrid at 0x160588d0>
In [47]:
sns.catplot(x="income_bracket",y="age",kind='bar',hue='gender',data=census_data)
Out[47]:
<seaborn.axisgrid.FacetGrid at 0xdf262e8>
A special case for the bar plot is when you want to show the number of observations in each category rather than computing a statistic for a second variable. This is similar to a histogram over a categorical, rather than quantitative, variable. In seaborn, it’s easy to do so with the countplot() function:
In [61]:
ax = sns.catplot(x='marital_status',kind='count',data=census_data,orient="h")ax.fig.autofmt_xdate()
Out[61]:
An alternative style for visualizing the same information is offered by the pointplot() function. This function also encodes the value of the estimate with height on the other axis, but rather than showing a full bar, it plots the point estimate and confidence interval. Additionally, pointplot() connects points from the same hue category. This makes it easy to see how the main relationship is changing as a function of the hue semantic because your eyes are quite good at picking up on differences of slopes:
In [67]:
ax = sns.catplot(x='marital_status',y='age',hue='relationship',kind='point',data=census_data)ax.fig.autofmt_xdate()
Out[67]:
Just like relplot(), the fact that catplot() is built on a FacetGrid means that it is easy to add faceting variables to visualize higher-dimensional relationships:
In [78]:
sns.catplot(x="age", y="marital_status", hue="income_bracket", col="gender", aspect=.6, kind="box", data=census_data);
out[78]:
www.amazon.in
www.amazon.in
www.amazon.in
To fork, this notebook goes to GitHub.
If you like this article, do share with others.
|
[
{
"code": null,
"e": 270,
"s": 171,
"text": "I am back with the seaborn tutorial. Last time we learn about Data Visualization using Matplotlib."
},
{
"code": null,
"e": 434,
"s": 270,
"text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics."
},
{
"code": null,
"e": 476,
"s": 434,
"text": "Seaborn is a statistical plotting library"
},
{
"code": null,
"e": 508,
"s": 476,
"text": "It has beautiful default styles"
},
{
"code": null,
"e": 577,
"s": 508,
"text": "It also is designed to work very well with Pandas dataframe objects."
},
{
"code": null,
"e": 636,
"s": 577,
"text": "To install the latest release of seaborn, you can use pip:"
},
{
"code": null,
"e": 656,
"s": 636,
"text": "pip install seaborn"
},
{
"code": null,
"e": 720,
"s": 656,
"text": "It’s also possible to install the released version using conda:"
},
{
"code": null,
"e": 742,
"s": 720,
"text": "conda install seaborn"
},
{
"code": null,
"e": 830,
"s": 742,
"text": "Alternatively, you can use pip to install the development version directly from github:"
},
{
"code": null,
"e": 885,
"s": 830,
"text": "pip install git+https://github.com/mwaskom/seaborn.git"
},
{
"code": null,
"e": 977,
"s": 885,
"text": "Another option would be to to clone the github repository and install from your local copy:"
},
{
"code": null,
"e": 1023,
"s": 977,
"text": "pip install . Dependencies Python 2.7 or 3.5+"
},
{
"code": null,
"e": 1096,
"s": 1023,
"text": "numpy (>= 1.9.3)scipy (>= 0.14.0)matplotlib (>= 1.4.3)pandas (>= 0.15.2)"
},
{
"code": null,
"e": 1119,
"s": 1096,
"text": "statsmodels (>= 0.5.0)"
},
{
"code": null,
"e": 1594,
"s": 1119,
"text": "TestingTo test seaborn, run make test in the root directory of the source distribution. This runs the unit test suite (using pytest, but many older tests use nose asserts). It also runs the example code in function docstrings to smoke-test a broader and more realistic range of example usage.The full set of tests requires an internet connection to download the example datasets (if they haven’t been previously cached), but the unit tests should be possible to run offline."
},
{
"code": null,
"e": 1599,
"s": 1594,
"text": "Bugs"
},
{
"code": null,
"e": 2009,
"s": 1599,
"text": "Please report any bugs you encounter through the github issue tracker. It will be most helpful to include a reproducible example on one of the example datasets (accessed through load_dataset()). It is difficult debug any issues without knowing the versions of seaborn and matplotlib you are using, as well as what matplotlib backend you are using to draw the plots, so please include those in your bug report."
},
{
"code": null,
"e": 2154,
"s": 2009,
"text": "Note: This article assumes you are familiar with python basic and data visualization. Still, face any problem do comment or email me your query."
},
{
"code": null,
"e": 2202,
"s": 2154,
"text": "Refer Our — Data Visualization Using Matplotlib"
},
{
"code": null,
"e": 2216,
"s": 2202,
"text": "www.amazon.in"
},
{
"code": null,
"e": 2230,
"s": 2216,
"text": "www.amazon.in"
},
{
"code": null,
"e": 2238,
"s": 2230,
"text": "In [1]:"
},
{
"code": null,
"e": 2346,
"s": 2238,
"text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 2354,
"s": 2346,
"text": "In [2]:"
},
{
"code": null,
"e": 2421,
"s": 2354,
"text": "census_data = pd.read_csv('census_data.csv')census_data.describe()"
},
{
"code": null,
"e": 2429,
"s": 2421,
"text": "Out[2]:"
},
{
"code": null,
"e": 2437,
"s": 2429,
"text": "In [3]:"
},
{
"code": null,
"e": 2456,
"s": 2437,
"text": "census_data.head()"
},
{
"code": null,
"e": 2464,
"s": 2456,
"text": "Out[3]:"
},
{
"code": null,
"e": 2472,
"s": 2464,
"text": "In [4]:"
},
{
"code": null,
"e": 2491,
"s": 2472,
"text": "census_data.info()"
},
{
"code": null,
"e": 2499,
"s": 2491,
"text": "Out[4]:"
},
{
"code": null,
"e": 2833,
"s": 2499,
"text": "Statistical analysis is a process of understanding how variables in a dataset relate to each other and how those relationships depend on other variables. Visualization can be a core component of this process because, when data are visualized properly, the human visual system can see trends and patterns that indicate a relationship."
},
{
"code": null,
"e": 2886,
"s": 2833,
"text": "We will discuss most of the seaborn functions today-"
},
{
"code": null,
"e": 3222,
"s": 2886,
"text": "The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two variables using a cloud of points, where each point represents an observation in the dataset. This depiction allows the eye to infer a substantial amount of information about whether there is any meaningful relationship between them."
},
{
"code": null,
"e": 3381,
"s": 3222,
"text": "There are several ways to draw a scatter plot in seaborn. The most basic, which should be used when both variables are numeric, is the scatterplot() function."
},
{
"code": null,
"e": 3389,
"s": 3381,
"text": "In [5]:"
},
{
"code": null,
"e": 3457,
"s": 3389,
"text": "sns.scatterplot(x='capital_loss',y='capital_gain',data=census_data)"
},
{
"code": null,
"e": 3465,
"s": 3457,
"text": "Out[5]:"
},
{
"code": null,
"e": 3518,
"s": 3465,
"text": "<matplotlib.axes._subplots.AxesSubplot at 0xaafb2b0>"
},
{
"code": null,
"e": 3526,
"s": 3518,
"text": "In [6]:"
},
{
"code": null,
"e": 3680,
"s": 3526,
"text": "sns.set(style=\"darkgrid\")tips = sns.load_dataset(\"tips\") #tips is inbuild dataset in seabornsns.relplot(x=\"total_bill\", y=\"tip\", data=tips);"
},
{
"code": null,
"e": 3788,
"s": 3680,
"text": "Note: The scatterplot() is the default kind in relplot() (it can also be forced by setting kind=”scatter”):"
},
{
"code": null,
"e": 3796,
"s": 3788,
"text": "In [7]:"
},
{
"code": null,
"e": 4038,
"s": 3796,
"text": "# adding some additional parameterssns.scatterplot(x='capital_loss',y='capital_gain',hue='marital_status',data=census_data)# hue: Can be either categorical or numeric, although color mapping will# behave differently in latter case."
},
{
"code": null,
"e": 4046,
"s": 4038,
"text": "Out[7]:"
},
{
"code": null,
"e": 4099,
"s": 4046,
"text": "<matplotlib.axes._subplots.AxesSubplot at 0xac406a0>"
},
{
"code": null,
"e": 4107,
"s": 4099,
"text": "In [8]:"
},
{
"code": null,
"e": 4207,
"s": 4107,
"text": "sns.scatterplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',data=census_data)"
},
{
"code": null,
"e": 4215,
"s": 4207,
"text": "Out[8]:"
},
{
"code": null,
"e": 4268,
"s": 4215,
"text": "<matplotlib.axes._subplots.AxesSubplot at 0xadc95c0>"
},
{
"code": null,
"e": 4276,
"s": 4268,
"text": "In [9]:"
},
{
"code": null,
"e": 4507,
"s": 4276,
"text": "# As I said above the scatterplot() is the default kind in relplot() (it can also be forced by setting kind=\"scatter\"):# see differencesns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',data=census_data)"
},
{
"code": null,
"e": 4515,
"s": 4507,
"text": "Out[9]:"
},
{
"code": null,
"e": 4557,
"s": 4515,
"text": "<seaborn.axisgrid.FacetGrid at 0xacdeb70>"
},
{
"code": null,
"e": 4798,
"s": 4557,
"text": "Scatter plots are highly effective, but there is no universally optimal type of visualization. Instead, the visual representation should be adapted for the specifics of the dataset and to the question you are trying to answer with the plot."
},
{
"code": null,
"e": 5109,
"s": 4798,
"text": "With some datasets, you may want to understand changes in one variable as a function of time, or a similarly continuous variable. In this situation, a good choice is to draw a line plot. In Seaborn, this can be accomplished by the lineplot() function, either directly or with relplot() by setting kind=” line”:"
},
{
"code": null,
"e": 5118,
"s": 5109,
"text": "In [10]:"
},
{
"code": null,
"e": 5703,
"s": 5118,
"text": "df = pd.DataFrame(dict(time=np.arange(500), value=np.random.randn(500).cumsum()))g = sns.relplot(x=\"time\", y=\"value\", kind=\"line\", data=df)g.fig.autofmt_xdate()\"\"\"Figure-level interface for drawing relational plots onto a FacetGrid.This function provides access to several different axes-level functionsthat show the relationship between two variables with semantic mappingsof subsets. The ``kind`` parameter selects the underlying axes-levelfunction to use:- :func:`scatterplot` (with ``kind=\"scatter\"``; the default)- :func:`lineplot` (with ``kind=\"line\"``)\"\"\""
},
{
"code": null,
"e": 5712,
"s": 5703,
"text": "Out[10]:"
},
{
"code": null,
"e": 5721,
"s": 5712,
"text": "In [11]:"
},
{
"code": null,
"e": 5816,
"s": 5721,
"text": "age_vs_hours_per_week = sns.relplot(x=\"age\", y=\"hours_per_week\", kind=\"line\", data=census_data"
},
{
"code": null,
"e": 5825,
"s": 5816,
"text": "Out[11]:"
},
{
"code": null,
"e": 5834,
"s": 5825,
"text": "In [12]:"
},
{
"code": null,
"e": 5941,
"s": 5834,
"text": "age_vs_hours_per_week = sns.relplot(x=\"age\", y=\"hours_per_week\", kind=\"line\",sort=False, data=census_data)"
},
{
"code": null,
"e": 5950,
"s": 5941,
"text": "Out[12]:"
},
{
"code": null,
"e": 6135,
"s": 5950,
"text": "Lineplot() assumes that you are most often trying to draw y as a function of x, the default behavior is to sort the data by the x values before plotting. However, this can be disabled:"
},
{
"code": null,
"e": 6406,
"s": 6135,
"text": "We’ve emphasized in this tutorial that, while these functions can show several semantic variables at once, it’s not always effective to do so. But what about when you do want to understand how a relationship between two variables depends on more than one other variable?"
},
{
"code": null,
"e": 6761,
"s": 6406,
"text": "The best approach may be to make more than one plot. Because relplot() is based on the FacetGrid, this is easy to do. To show the influence of an additional variable, instead of assigning it to one of the semantic roles in the plot, use it to “facet” the visualization. This means that you make multiple axes and plot subsets of the data on each of them:"
},
{
"code": null,
"e": 6770,
"s": 6761,
"text": "In [13]:"
},
{
"code": null,
"e": 6879,
"s": 6770,
"text": "sns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',col='gender',data=census_data)"
},
{
"code": null,
"e": 6888,
"s": 6879,
"text": "Out[13]:"
},
{
"code": null,
"e": 6930,
"s": 6888,
"text": "<seaborn.axisgrid.FacetGrid at 0xc8a1240>"
},
{
"code": null,
"e": 6939,
"s": 6930,
"text": "In [14]:"
},
{
"code": null,
"e": 7056,
"s": 6939,
"text": "sns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',col='income_bracket',data=census_data)"
},
{
"code": null,
"e": 7065,
"s": 7056,
"text": "Out[14]:"
},
{
"code": null,
"e": 7107,
"s": 7065,
"text": "<seaborn.axisgrid.FacetGrid at 0xcdc25c0>"
},
{
"code": null,
"e": 7413,
"s": 7107,
"text": "You can also show the influence two variables this way: one by faceting on the columns and one by faceting on the rows. As you start adding more variables to the grid, you may want to decrease the figure size. Remember that the size FacetGrid is parameterized by the height and aspect ratio of each facet:"
},
{
"code": null,
"e": 7422,
"s": 7413,
"text": "In [15]:"
},
{
"code": null,
"e": 7559,
"s": 7422,
"text": "sns.relplot(x='capital_loss',y='capital_gain',hue='marital_status',size='age',col='income_bracket',row='race',height=5,data=census_data)"
},
{
"code": null,
"e": 7568,
"s": 7559,
"text": "Out[15]:"
},
{
"code": null,
"e": 7610,
"s": 7568,
"text": "<seaborn.axisgrid.FacetGrid at 0xcdc2320>"
},
{
"code": null,
"e": 8009,
"s": 7610,
"text": "In the relational plot tutorial we saw how to use different visual representations to show the relationship between multiple variables in a dataset. In the examples, we focused on cases where the main relationship was between two numerical variables. If one of the main variables is “categorical” (divided into discrete groups) it may be helpful to use a more specialized approach to visualization."
},
{
"code": null,
"e": 8416,
"s": 8009,
"text": "In seaborn, there are several different ways to visualize a relationship involving categorical data. Similar to the relationship between relplot() and either scatterplot() or lineplot(), there are two ways to make these plots. There are a number of axes-level functions for plotting categorical data in different ways and a figure-level interface, catplot(), that gives unified higher-level access to them."
},
{
"code": null,
"e": 8567,
"s": 8416,
"text": "It’s helpful to think of the different categorical plot kinds as belonging to three different families, which we’ll discuss in detail below. They are:"
},
{
"code": null,
"e": 8593,
"s": 8567,
"text": "Categorical scatterplots:"
},
{
"code": null,
"e": 8669,
"s": 8593,
"text": "stripplot() (with kind=”strip”; the default)swarmplot() (with kind=”swarm”)"
},
{
"code": null,
"e": 8701,
"s": 8669,
"text": "Categorical distribution plots:"
},
{
"code": null,
"e": 8793,
"s": 8701,
"text": "boxplot() (with kind=”box”)violinplot() (with kind=”violin”)boxenplot() (with kind=”boxen”)"
},
{
"code": null,
"e": 8821,
"s": 8793,
"text": "Categorical estimate plots:"
},
{
"code": null,
"e": 8911,
"s": 8821,
"text": "pointplot() (with kind=”point”)barplot() (with kind=”bar”)countplot() (with kind=”count”)"
},
{
"code": null,
"e": 8984,
"s": 8911,
"text": "These families represent the data using different levels of granularity."
},
{
"code": null,
"e": 9568,
"s": 8984,
"text": "The default representation of the data in catplot() uses a scatterplot. There are actually two different categorical scatter plots in seaborn. They take different approaches to resolving the main challenge in representing categorical data with a scatter plot, which is that all of the points belonging to one category would fall on the same position along the axis corresponding to the categorical variable. The approach used by stripplot(), which is the default “kind” in catplot() is to adjust the positions of points on the categorical axis with a small amount of random “jitter”:"
},
{
"code": null,
"e": 9577,
"s": 9568,
"text": "In [16]:"
},
{
"code": null,
"e": 9634,
"s": 9577,
"text": "sns.catplot(x=\"age\",y=\"marital_status\",data=census_data)"
},
{
"code": null,
"e": 9643,
"s": 9634,
"text": "Out[16]:"
},
{
"code": null,
"e": 9685,
"s": 9643,
"text": "<seaborn.axisgrid.FacetGrid at 0xdb18470>"
},
{
"code": null,
"e": 10087,
"s": 9685,
"text": "The second approach adjusts the points along the categorical axis using an algorithm that prevents them from overlapping. It can give a better representation of the distribution of observations, although it only works well for relatively small datasets. This kind of plot is sometimes called a “beeswarm” and is drawn in seaborn by swarmplot(), which is activated by setting kind=”swarm” in catplot():"
},
{
"code": null,
"e": 10096,
"s": 10087,
"text": "In [27]:"
},
{
"code": null,
"e": 10289,
"s": 10096,
"text": "#sns.catplot(x=\"age\",y=\"relationship\",kind='swarm',data=census_data)# or#sns.swarmplot(x=\"relationship\",y=\"age\",data=census_data)sns.catplot(x=\"day\", y=\"total_bill\", kind=\"swarm\", data=tips);"
},
{
"code": null,
"e": 10298,
"s": 10289,
"text": "Out[27]:"
},
{
"code": null,
"e": 10653,
"s": 10298,
"text": "Similar to the relational plots, it’s possible to add another dimension to a categorical plot by using a hue semantic. (The categorical plots do not currently support size or style semantics). Each different categorical plotting function handles the hue semantic differently. For the scatter plots, it is only necessary to change the color of the points:"
},
{
"code": null,
"e": 10662,
"s": 10653,
"text": "In [29]:"
},
{
"code": null,
"e": 10736,
"s": 10662,
"text": "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"sex\", kind=\"swarm\", data=tips);"
},
{
"code": null,
"e": 10745,
"s": 10736,
"text": "Out[29]:"
},
{
"code": null,
"e": 11141,
"s": 10745,
"text": "The first is the familiar boxplot(). This kind of plot shows the three quartile values of the distribution along with extreme values. The “whiskers” extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. This means that each value in the boxplot corresponds to an actual observation in the data."
},
{
"code": null,
"e": 11150,
"s": 11141,
"text": "In [32]:"
},
{
"code": null,
"e": 11218,
"s": 11150,
"text": "sns.catplot(x=\"age\",y=\"marital_status\",kind='box',data=census_data)"
},
{
"code": null,
"e": 11227,
"s": 11218,
"text": "Out[32]:"
},
{
"code": null,
"e": 11269,
"s": 11227,
"text": "<seaborn.axisgrid.FacetGrid at 0xd411860>"
},
{
"code": null,
"e": 11404,
"s": 11269,
"text": "When adding a hue semantic, the box for each level of the semantic variable is moved along the categorical axis so they don’t overlap:"
},
{
"code": null,
"e": 11413,
"s": 11404,
"text": "In [37]:"
},
{
"code": null,
"e": 11494,
"s": 11413,
"text": "sns.catplot(x=\"age\",y=\"marital_status\",kind='box',hue='gender',data=census_data)"
},
{
"code": null,
"e": 11503,
"s": 11494,
"text": "Out[37]:"
},
{
"code": null,
"e": 11545,
"s": 11503,
"text": "<seaborn.axisgrid.FacetGrid at 0xde8a8d0>"
},
{
"code": null,
"e": 11696,
"s": 11545,
"text": "A different approach is a violinplot(), which combines a boxplot with the kernel density estimation procedure described in the distributions tutorial:"
},
{
"code": null,
"e": 11705,
"s": 11696,
"text": "In [38]:"
},
{
"code": null,
"e": 11776,
"s": 11705,
"text": "sns.catplot(x=\"age\",y=\"marital_status\",kind='violin',data=census_data)"
},
{
"code": null,
"e": 11785,
"s": 11776,
"text": "Out[38]:"
},
{
"code": null,
"e": 11828,
"s": 11785,
"text": "<seaborn.axisgrid.FacetGrid at 0x184c4080>"
},
{
"code": null,
"e": 12207,
"s": 11828,
"text": "This approach uses the kernel density estimate to provide a richer description of the distribution of values. Additionally, the quartile and whikser values from the boxplot are shown inside the violin. The downside is that, because the violinplot uses a KDE, there are some other parameters that may need tweaking, adding some complexity relative to the straightforward boxplot:"
},
{
"code": null,
"e": 12216,
"s": 12207,
"text": "In [41]:"
},
{
"code": null,
"e": 12301,
"s": 12216,
"text": "sns.catplot(x=\"age\",y=\"marital_status\",kind='violin',bw=.15, cut=0,data=census_data)"
},
{
"code": null,
"e": 12310,
"s": 12301,
"text": "Out[41]:"
},
{
"code": null,
"e": 12352,
"s": 12310,
"text": "<seaborn.axisgrid.FacetGrid at 0xfdea320>"
},
{
"code": null,
"e": 12659,
"s": 12352,
"text": "For other applications, rather than showing the distribution within each category, you might want to show an estimate of the central tendency of the values. Seaborn has two main ways to show this information. Importantly, the basic API for these functions is identical to that for the ones discussed above."
},
{
"code": null,
"e": 13033,
"s": 12659,
"text": "A familiar style of plot that accomplishes this goal is a bar plot. In seaborn, the barplot() function operates on a full dataset and applies a function to obtain the estimate (taking the mean by default). When there are multiple observations in each category, it also uses bootstrapping to compute a confidence interval around the estimate and plots that using error bars:"
},
{
"code": null,
"e": 13042,
"s": 13033,
"text": "In [46]:"
},
{
"code": null,
"e": 13110,
"s": 13042,
"text": "sns.catplot(x=\"income_bracket\",y=\"age\",kind='bar',data=census_data)"
},
{
"code": null,
"e": 13119,
"s": 13110,
"text": "Out[46]:"
},
{
"code": null,
"e": 13162,
"s": 13119,
"text": "<seaborn.axisgrid.FacetGrid at 0x160588d0>"
},
{
"code": null,
"e": 13171,
"s": 13162,
"text": "In [47]:"
},
{
"code": null,
"e": 13252,
"s": 13171,
"text": "sns.catplot(x=\"income_bracket\",y=\"age\",kind='bar',hue='gender',data=census_data)"
},
{
"code": null,
"e": 13261,
"s": 13252,
"text": "Out[47]:"
},
{
"code": null,
"e": 13303,
"s": 13261,
"text": "<seaborn.axisgrid.FacetGrid at 0xdf262e8>"
},
{
"code": null,
"e": 13610,
"s": 13303,
"text": "A special case for the bar plot is when you want to show the number of observations in each category rather than computing a statistic for a second variable. This is similar to a histogram over a categorical, rather than quantitative, variable. In seaborn, it’s easy to do so with the countplot() function:"
},
{
"code": null,
"e": 13619,
"s": 13610,
"text": "In [61]:"
},
{
"code": null,
"e": 13719,
"s": 13619,
"text": "ax = sns.catplot(x='marital_status',kind='count',data=census_data,orient=\"h\")ax.fig.autofmt_xdate()"
},
{
"code": null,
"e": 13728,
"s": 13719,
"text": "Out[61]:"
},
{
"code": null,
"e": 14240,
"s": 13728,
"text": "An alternative style for visualizing the same information is offered by the pointplot() function. This function also encodes the value of the estimate with height on the other axis, but rather than showing a full bar, it plots the point estimate and confidence interval. Additionally, pointplot() connects points from the same hue category. This makes it easy to see how the main relationship is changing as a function of the hue semantic because your eyes are quite good at picking up on differences of slopes:"
},
{
"code": null,
"e": 14249,
"s": 14240,
"text": "In [67]:"
},
{
"code": null,
"e": 14365,
"s": 14249,
"text": "ax = sns.catplot(x='marital_status',y='age',hue='relationship',kind='point',data=census_data)ax.fig.autofmt_xdate()"
},
{
"code": null,
"e": 14374,
"s": 14365,
"text": "Out[67]:"
},
{
"code": null,
"e": 14538,
"s": 14374,
"text": "Just like relplot(), the fact that catplot() is built on a FacetGrid means that it is easy to add faceting variables to visualize higher-dimensional relationships:"
},
{
"code": null,
"e": 14547,
"s": 14538,
"text": "In [78]:"
},
{
"code": null,
"e": 14688,
"s": 14547,
"text": "sns.catplot(x=\"age\", y=\"marital_status\", hue=\"income_bracket\", col=\"gender\", aspect=.6, kind=\"box\", data=census_data);"
},
{
"code": null,
"e": 14697,
"s": 14688,
"text": "out[78]:"
},
{
"code": null,
"e": 14711,
"s": 14697,
"text": "www.amazon.in"
},
{
"code": null,
"e": 14725,
"s": 14711,
"text": "www.amazon.in"
},
{
"code": null,
"e": 14739,
"s": 14725,
"text": "www.amazon.in"
},
{
"code": null,
"e": 14778,
"s": 14739,
"text": "To fork, this notebook goes to GitHub."
}
] |
Getting Started with Data Collection Using Twitter API v2 in Less than an Hour | by Laura O’Mahony | Towards Data Science
|
IntroductionWhat is an API?Twitter APIGetting Access to the Twitter APIMaking a Basic Request with the Twitter APIAltering a Request with the Twitter APIConclusion
Introduction
What is an API?
Twitter API
Getting Access to the Twitter API
Making a Basic Request with the Twitter API
Altering a Request with the Twitter API
Conclusion
Social media’s ubiquity has made various social media platforms more and more popular as a source of data. With this rise of social media as a data source, data collection using APIs is becoming a very sought-after skill in many data science roles. Today we will use the Twitter API v2 to collect social media posts from the microblogging and social networking service Twitter.
Twitter now has almost 400 million active monthly users [1], meaning a huge volume of data is available to collect, most of which is public. In addition to this, the Twitter developer team recently rebuilt the Twitter API from the ground up, releasing the Twitter API v2 in the second half of 2020. This API is really well documented and easy to use making it easier than ever to utilize this rich data source.
This article introduces what an API is and documents the process of using the Twitter API v2, from gaining access to the API, to connecting to a search endpoint and collecting data relating to some keywords of interest. No familiarity with the Twitter API or any knowledge of APIs at all is required to follow this piece.
An Application Programming Interface (API) is a software intermediary that allows two applications to communicate with each other to access data. APIs are frequently used for every action you take on your phone, e.g. sending a private message or checking the score of a football game. Both of these use an API to access and deliver that information to your phone. An API is basically a messenger that takes your requests, translates them, and returns the response. Essentially, developers plug into APIs to access certain assets for end users. Of course, to ensure data security, an API only provides select data that the application programmers have made public. APIs generally require an API key to authenticate a request. The API documentation generally contains the necessary information for access instructions and requirements. Many APIs are even free to use. Oftentimes, developers can follow existing API documentation to build a URL in order to pull the data within a browser.
The Twitter API is a well-documented API that enables programmers to access Twitter in advanced ways. It can be used to analyze, learn from, and even interact with Tweets. It also allows interactions with direct messages, users, and other Twitter resources. Twitter’s API also allows developers access to all kinds of user profile information, like user searches, block lists, real-time tweets, and more. Information on API products, use cases, and docs are available on the Developer Platform. Details on the Twitter developer policy are available here.
There are various APIs developed by Twitter that developers can use. These APIs benefit researchers and companies by drawing insights from Twitter data. However, it’s also suitable for smaller-scale projects such as small-scale data analysis, creating bots, and even creating fully automated systems that can interact with Twitter. In this post, we will use the Twitter API to pull some recent public Tweets matching a specified search query. The API product track we will use is freely available to anyone and allows up to 100 thousand tweets a month to be pulled.
Before using the Twitter API, one must already have a Twitter account. It is then required to apply for access to the Twitter API in order to obtain credentials. The API endpoint we will look at is GET /2/tweets/search/recent. This returns public Tweets from the last seven days that match a search query and is available to users approved to use the Twitter API with the standard product track or any other product track.
For the purposes of this article, we will use the recent search endpoint, meaning we will only need access to the standard product track. The standard product track is the default product track for those just getting started, building something for fun, etc. The alternative product tracks are academic and business and have greater capabilities for those who qualify or are willing to pay respectfully.
The process of applying for the standard product track and obtaining the necessary credentials involves first having a Twitter account. One must then apply for a developer account by filling out the forms on this page. Note that the recent search endpoint returns Tweets matching the search criteria from only the last 7 days. A similar archive search endpoint GET /2/tweets/search/all has greater capabilities. It allows the user to return public Tweets matching a search query from as far back as Twitter’s first post in 2006. However, this endpoint is only available to those users who have been approved for the Academic Research product track. The academic research product track is an exciting addition to the Twitter API v2 which allows users to use the widest range of endpoints and pull up to 10 million tweets each month! A full list of the Twitter API v2 endpoints is available here. More details about features that can be used for academic research can be found here. It is possible to check eligibility for this product track here. The process for applying for an academic product track license is similar, but the application form is more detailed and must be approved by the Twitter developer team.
Once the application has been approved, one can finally use various API endpoints with the standard product track. To go about this, one must set up an app by opening the developer portal and choosing ‘create a new project’, filling out the required details, and lastly give the new app a name.
Once this is done, you will be navigated to a keys and tokens page. After you name your app, you will receive your API Keys and the Bearer Token (hidden in the screenshot below). These are necessary to connect to the endpoints in the Twitter API v2.
Make a note of your API key, API secret key and Bearer token. Once you leave this page you will not be able to see these again. However, if you lose these keys and tokens it is still possible to regenerate them. These are used to authenticate the app that is using the Twitter API, and also authenticate the user, depending on the endpoint. Note that all of these keys should be treated like passwords, and not shared or written in your code in plain text.
Now that all API access keys should be sorted, there is nothing left to do but test out the API! The first step here is to load your credentials. One way of doing this is using the command prompt (or another similar tool) to pass through the bearer token as an environment variable and a Juptyer Notebook (Available by installing Anaconda) for making requests and showing responses. Begin by opening up a command prompt and changing the directory to wherever you wish to save your script. In the command prompt, pass through the “Bearer Token” just created by the app set up by typing:
set BEARER_TOKEN=YOUR_BEARER_TOKEN
Next open Jupyter Notebook with the command:
Jupyter Notebook
Create a new Python 3 Jupyter Notebook file. Next, the first thing we will need to do is import some libraries.
Following this, we need to set up a connection to the Twitter API and access our credentials. For this, we will create a connect_to_twitter() function which retrieves the bearer token from the environment variable. In this step, we also pass the bearer token for authorization and return headers which will be used to access the API.
Now we are all set up to use the API! Twitter recently launched a new #ExtremeWeather Mini-Site [2]. This gives a great idea of the data insights available on Twitter. Therefore, in this example, we will pull some recent Tweets relating to the #ExtremeWeather conversation on Twitter. To do this, we must build the appropriate URL request for the endpoint and the parameters we want to pass.
The ‘recent’ part of the URL here is the endpoint and the query ‘ExtremeWeather’ is the keyword searched for. Equivalently, one can write the URL and separate out the query parameters like so:
The response from the Twitter API is the response data returned in JavaScript Object Notation (JSON) format. The response is effectively read as a Python dictionary where the keys either contain data or contain more dictionaries. The top two keys as seen in this response are ‘data’ and ‘meta’. The tweets are contained within ‘data’ as a list of dictionaries. Meta is a dictionary of attributes about the corresponding request, it gives the oldest and newest tweet ID, the result count as the ‘next_token’ field I will discuss at a later stage.
{ "data": [ { "id": "144557134867XXXXXXX", "text": "Tweet text 1" }, { "id": "144557110192XXXXXXX", "text": "Tweet text 2" },... { "id": "144555630795XXXXXXX", "text": "Tweet text 10" } ], "meta": { "newest_id": "144557134867XXXXXXX", "next_token": "b26v89c19zqg8o3fpds84gm0395pkbbjlh482vwacby4d", "oldest_id": "144555630795XXXXXXX", "result_count": 10 }}
The Tweets can be made into a data frame using the following code:
We can easily save it to CSV format if we wish:
Altering the query parameters the endpoint offers allows us to customize the request we wish to send. The endpoint’s API reference document details this in the ‘Query parameters’ section. A basic set of operators and can be used to alter queries. We can amend the query, start and end times for the widow of time we are interested in and the maximum number of results, we can also pull many additional fields to give further information about the tweet, author, place, etc. The following pulls 15 Tweets containing the keyword “ExtremeWeather”, which aren’t retweets and were created on October 12th, 2021 (within a week of the date the request was made).
The recent search endpoint can deliver up to max_results=100 Tweets per request in reverse-chronological order. Pagination tokens are used if there are more than the ‘max_results’ matching Tweets. The next page of results can be retrieved by amending the request by copying and pasting the ‘next_token’ field given in the previous result into the ‘next_token’ field instead of leaving it blank as above. A loop could be created to make requests to pull Tweets until all matching Tweets have been collected. There is a limit to the number of requests that can be made which is detailed here.
This article details a step-by-step process for collecting Tweets from Twitter API v2 using the recent search endpoint using Python. Steps from getting access to the Twitter API, making a basic request, formating and saving the response, and finally amending query parameters are discussed. This should enable you to get up and running with making search requests with the Twitter v2 API.
If you found this article helpful, feel free to share it with friends and colleagues who may be interested. I am on LinkedIn and Twitter if you wish to connect.
Happy data collection!
All images are my own created on diagrams.net or screenshots of my own application on the Twitter Developer Platform.
[1] Statista: Most popular social networks worldwide as of July 2021, ranked by number of active users (Accessed 04–10–21).
[2] Visualizing the global #ExtremeWeather conversation on Twitter (Accessed 04–10–21).
|
[
{
"code": null,
"e": 336,
"s": 172,
"text": "IntroductionWhat is an API?Twitter APIGetting Access to the Twitter APIMaking a Basic Request with the Twitter APIAltering a Request with the Twitter APIConclusion"
},
{
"code": null,
"e": 349,
"s": 336,
"text": "Introduction"
},
{
"code": null,
"e": 365,
"s": 349,
"text": "What is an API?"
},
{
"code": null,
"e": 377,
"s": 365,
"text": "Twitter API"
},
{
"code": null,
"e": 411,
"s": 377,
"text": "Getting Access to the Twitter API"
},
{
"code": null,
"e": 455,
"s": 411,
"text": "Making a Basic Request with the Twitter API"
},
{
"code": null,
"e": 495,
"s": 455,
"text": "Altering a Request with the Twitter API"
},
{
"code": null,
"e": 506,
"s": 495,
"text": "Conclusion"
},
{
"code": null,
"e": 884,
"s": 506,
"text": "Social media’s ubiquity has made various social media platforms more and more popular as a source of data. With this rise of social media as a data source, data collection using APIs is becoming a very sought-after skill in many data science roles. Today we will use the Twitter API v2 to collect social media posts from the microblogging and social networking service Twitter."
},
{
"code": null,
"e": 1295,
"s": 884,
"text": "Twitter now has almost 400 million active monthly users [1], meaning a huge volume of data is available to collect, most of which is public. In addition to this, the Twitter developer team recently rebuilt the Twitter API from the ground up, releasing the Twitter API v2 in the second half of 2020. This API is really well documented and easy to use making it easier than ever to utilize this rich data source."
},
{
"code": null,
"e": 1617,
"s": 1295,
"text": "This article introduces what an API is and documents the process of using the Twitter API v2, from gaining access to the API, to connecting to a search endpoint and collecting data relating to some keywords of interest. No familiarity with the Twitter API or any knowledge of APIs at all is required to follow this piece."
},
{
"code": null,
"e": 2603,
"s": 1617,
"text": "An Application Programming Interface (API) is a software intermediary that allows two applications to communicate with each other to access data. APIs are frequently used for every action you take on your phone, e.g. sending a private message or checking the score of a football game. Both of these use an API to access and deliver that information to your phone. An API is basically a messenger that takes your requests, translates them, and returns the response. Essentially, developers plug into APIs to access certain assets for end users. Of course, to ensure data security, an API only provides select data that the application programmers have made public. APIs generally require an API key to authenticate a request. The API documentation generally contains the necessary information for access instructions and requirements. Many APIs are even free to use. Oftentimes, developers can follow existing API documentation to build a URL in order to pull the data within a browser."
},
{
"code": null,
"e": 3158,
"s": 2603,
"text": "The Twitter API is a well-documented API that enables programmers to access Twitter in advanced ways. It can be used to analyze, learn from, and even interact with Tweets. It also allows interactions with direct messages, users, and other Twitter resources. Twitter’s API also allows developers access to all kinds of user profile information, like user searches, block lists, real-time tweets, and more. Information on API products, use cases, and docs are available on the Developer Platform. Details on the Twitter developer policy are available here."
},
{
"code": null,
"e": 3724,
"s": 3158,
"text": "There are various APIs developed by Twitter that developers can use. These APIs benefit researchers and companies by drawing insights from Twitter data. However, it’s also suitable for smaller-scale projects such as small-scale data analysis, creating bots, and even creating fully automated systems that can interact with Twitter. In this post, we will use the Twitter API to pull some recent public Tweets matching a specified search query. The API product track we will use is freely available to anyone and allows up to 100 thousand tweets a month to be pulled."
},
{
"code": null,
"e": 4147,
"s": 3724,
"text": "Before using the Twitter API, one must already have a Twitter account. It is then required to apply for access to the Twitter API in order to obtain credentials. The API endpoint we will look at is GET /2/tweets/search/recent. This returns public Tweets from the last seven days that match a search query and is available to users approved to use the Twitter API with the standard product track or any other product track."
},
{
"code": null,
"e": 4551,
"s": 4147,
"text": "For the purposes of this article, we will use the recent search endpoint, meaning we will only need access to the standard product track. The standard product track is the default product track for those just getting started, building something for fun, etc. The alternative product tracks are academic and business and have greater capabilities for those who qualify or are willing to pay respectfully."
},
{
"code": null,
"e": 5766,
"s": 4551,
"text": "The process of applying for the standard product track and obtaining the necessary credentials involves first having a Twitter account. One must then apply for a developer account by filling out the forms on this page. Note that the recent search endpoint returns Tweets matching the search criteria from only the last 7 days. A similar archive search endpoint GET /2/tweets/search/all has greater capabilities. It allows the user to return public Tweets matching a search query from as far back as Twitter’s first post in 2006. However, this endpoint is only available to those users who have been approved for the Academic Research product track. The academic research product track is an exciting addition to the Twitter API v2 which allows users to use the widest range of endpoints and pull up to 10 million tweets each month! A full list of the Twitter API v2 endpoints is available here. More details about features that can be used for academic research can be found here. It is possible to check eligibility for this product track here. The process for applying for an academic product track license is similar, but the application form is more detailed and must be approved by the Twitter developer team."
},
{
"code": null,
"e": 6061,
"s": 5766,
"text": "Once the application has been approved, one can finally use various API endpoints with the standard product track. To go about this, one must set up an app by opening the developer portal and choosing ‘create a new project’, filling out the required details, and lastly give the new app a name."
},
{
"code": null,
"e": 6311,
"s": 6061,
"text": "Once this is done, you will be navigated to a keys and tokens page. After you name your app, you will receive your API Keys and the Bearer Token (hidden in the screenshot below). These are necessary to connect to the endpoints in the Twitter API v2."
},
{
"code": null,
"e": 6768,
"s": 6311,
"text": "Make a note of your API key, API secret key and Bearer token. Once you leave this page you will not be able to see these again. However, if you lose these keys and tokens it is still possible to regenerate them. These are used to authenticate the app that is using the Twitter API, and also authenticate the user, depending on the endpoint. Note that all of these keys should be treated like passwords, and not shared or written in your code in plain text."
},
{
"code": null,
"e": 7354,
"s": 6768,
"text": "Now that all API access keys should be sorted, there is nothing left to do but test out the API! The first step here is to load your credentials. One way of doing this is using the command prompt (or another similar tool) to pass through the bearer token as an environment variable and a Juptyer Notebook (Available by installing Anaconda) for making requests and showing responses. Begin by opening up a command prompt and changing the directory to wherever you wish to save your script. In the command prompt, pass through the “Bearer Token” just created by the app set up by typing:"
},
{
"code": null,
"e": 7389,
"s": 7354,
"text": "set BEARER_TOKEN=YOUR_BEARER_TOKEN"
},
{
"code": null,
"e": 7434,
"s": 7389,
"text": "Next open Jupyter Notebook with the command:"
},
{
"code": null,
"e": 7451,
"s": 7434,
"text": "Jupyter Notebook"
},
{
"code": null,
"e": 7563,
"s": 7451,
"text": "Create a new Python 3 Jupyter Notebook file. Next, the first thing we will need to do is import some libraries."
},
{
"code": null,
"e": 7897,
"s": 7563,
"text": "Following this, we need to set up a connection to the Twitter API and access our credentials. For this, we will create a connect_to_twitter() function which retrieves the bearer token from the environment variable. In this step, we also pass the bearer token for authorization and return headers which will be used to access the API."
},
{
"code": null,
"e": 8289,
"s": 7897,
"text": "Now we are all set up to use the API! Twitter recently launched a new #ExtremeWeather Mini-Site [2]. This gives a great idea of the data insights available on Twitter. Therefore, in this example, we will pull some recent Tweets relating to the #ExtremeWeather conversation on Twitter. To do this, we must build the appropriate URL request for the endpoint and the parameters we want to pass."
},
{
"code": null,
"e": 8482,
"s": 8289,
"text": "The ‘recent’ part of the URL here is the endpoint and the query ‘ExtremeWeather’ is the keyword searched for. Equivalently, one can write the URL and separate out the query parameters like so:"
},
{
"code": null,
"e": 9028,
"s": 8482,
"text": "The response from the Twitter API is the response data returned in JavaScript Object Notation (JSON) format. The response is effectively read as a Python dictionary where the keys either contain data or contain more dictionaries. The top two keys as seen in this response are ‘data’ and ‘meta’. The tweets are contained within ‘data’ as a list of dictionaries. Meta is a dictionary of attributes about the corresponding request, it gives the oldest and newest tweet ID, the result count as the ‘next_token’ field I will discuss at a later stage."
},
{
"code": null,
"e": 9532,
"s": 9028,
"text": "{ \"data\": [ { \"id\": \"144557134867XXXXXXX\", \"text\": \"Tweet text 1\" }, { \"id\": \"144557110192XXXXXXX\", \"text\": \"Tweet text 2\" },... { \"id\": \"144555630795XXXXXXX\", \"text\": \"Tweet text 10\" } ], \"meta\": { \"newest_id\": \"144557134867XXXXXXX\", \"next_token\": \"b26v89c19zqg8o3fpds84gm0395pkbbjlh482vwacby4d\", \"oldest_id\": \"144555630795XXXXXXX\", \"result_count\": 10 }}"
},
{
"code": null,
"e": 9599,
"s": 9532,
"text": "The Tweets can be made into a data frame using the following code:"
},
{
"code": null,
"e": 9647,
"s": 9599,
"text": "We can easily save it to CSV format if we wish:"
},
{
"code": null,
"e": 10303,
"s": 9647,
"text": "Altering the query parameters the endpoint offers allows us to customize the request we wish to send. The endpoint’s API reference document details this in the ‘Query parameters’ section. A basic set of operators and can be used to alter queries. We can amend the query, start and end times for the widow of time we are interested in and the maximum number of results, we can also pull many additional fields to give further information about the tweet, author, place, etc. The following pulls 15 Tweets containing the keyword “ExtremeWeather”, which aren’t retweets and were created on October 12th, 2021 (within a week of the date the request was made)."
},
{
"code": null,
"e": 10894,
"s": 10303,
"text": "The recent search endpoint can deliver up to max_results=100 Tweets per request in reverse-chronological order. Pagination tokens are used if there are more than the ‘max_results’ matching Tweets. The next page of results can be retrieved by amending the request by copying and pasting the ‘next_token’ field given in the previous result into the ‘next_token’ field instead of leaving it blank as above. A loop could be created to make requests to pull Tweets until all matching Tweets have been collected. There is a limit to the number of requests that can be made which is detailed here."
},
{
"code": null,
"e": 11283,
"s": 10894,
"text": "This article details a step-by-step process for collecting Tweets from Twitter API v2 using the recent search endpoint using Python. Steps from getting access to the Twitter API, making a basic request, formating and saving the response, and finally amending query parameters are discussed. This should enable you to get up and running with making search requests with the Twitter v2 API."
},
{
"code": null,
"e": 11444,
"s": 11283,
"text": "If you found this article helpful, feel free to share it with friends and colleagues who may be interested. I am on LinkedIn and Twitter if you wish to connect."
},
{
"code": null,
"e": 11467,
"s": 11444,
"text": "Happy data collection!"
},
{
"code": null,
"e": 11585,
"s": 11467,
"text": "All images are my own created on diagrams.net or screenshots of my own application on the Twitter Developer Platform."
},
{
"code": null,
"e": 11709,
"s": 11585,
"text": "[1] Statista: Most popular social networks worldwide as of July 2021, ranked by number of active users (Accessed 04–10–21)."
}
] |
Collaborative Filtering in Pyspark | by Kieran Tan Kah Wang | Towards Data Science
|
Have you ever wonder how Spotify is able to put up a list of songs every week in “Discover Weekly” and you ended up adding some of these songs to your playlists because you like them? What about the those shows recommended for you by Netflix because you watched a particular show yesterday? How are these tech giants so smart? The answer is Recommender System.
A Recommender System makes prediction based on users’ historical behaviours like view, search or purchase histories. Two common approaches of recommender system are Content Based and Collaborative Filtering, and this article will dive deeper into the latter.
Collaborative Filtering is a mathematical method to find the predictions about how users can rate a particular item based on ratings of other similar users. Typical Collaborative Filtering involves 4 different stages:
Data Collection — Collecting user behaviours and associated data itemsData Processing — Processing the collected dataRecommendation Calculation — Calculate referrals based on processed dataResult Derivation — Extract the similarity and return the top N results
Data Collection — Collecting user behaviours and associated data items
Data Processing — Processing the collected data
Recommendation Calculation — Calculate referrals based on processed data
Result Derivation — Extract the similarity and return the top N results
So what type of data are being collected in the first stage of Collaborative Filtering? There’s two different categories of data (referred as feedbacks), which can be Explicit or Implicit.
An example of Explicit Feedback is the ratings given by users, which Netflix is collecting to make recommendations to their customers after they provide ratings to the movies they have watched. Implicit Feedback is less straightforward as it’s based on the users’ interactions with the platform, ranging from clicks, views, likes and purchases. Spotify makes use of Implicit Feedbacks to implement it’s recommendation system.
Once the data has been collected and processed, some mathematical formula is needed to make the similarity calculation. The two most common measures are:
Euclidean Distance — Distance of the preference between two users. If the distance is small, similarity between both users is highPearson Correlation — If the cosine values (angle of incidence) between two users coincide, similarity between both users is high
Euclidean Distance — Distance of the preference between two users. If the distance is small, similarity between both users is high
Pearson Correlation — If the cosine values (angle of incidence) between two users coincide, similarity between both users is high
The library package spark.ml currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to make predictions. It uses the Alternating Least Squares (ALS) algorithm to learn these latent factors.
We will use the dataset from https://www.last.fm/api/ which contains 3 files:
user_artist_data.txt 3 columns: userid artistid playcount
artist_data.txt 2 columns: artistid artist_name
artist_alias.txt 2 columns: badid, goodid [known incorrectly spelt artists and the correct artist id]
Firstly, we set up Spark with the following.
# import librariesfrom pyspark import SparkContextfrom pyspark.ml.recommendation import ALSfrom pyspark.sql import SparkSession ,RowappName="Collaborative Filtering with PySpark"# initialize the spark sessionspark = SparkSession.builder.appName(appName).getOrCreate()# get sparkcontext from the sparksessionsc = spark.sparkContext
Then, we define the data structures and convert the Resilient Distributed Dataframe (RDDs) into dataframes.
from pyspark.sql.types import StructType,StructField,IntegerType,StringType,LongTypefrom pyspark.sql.functions import col#Define the schema for the datasetsschema_artist = StructType([StructField("artistId",StringType(),True),StructField("artistName",StringType(),True)])schema_user_artist = StructType([StructField("userId",StringType(),True),StructField("artistId",StringType(),True),StructField("playCount",StringType(),True)])schema_alias = StructType([StructField("badId",StringType(),True),StructField("goodId",StringType(),True)])#Convert RDDs into DataframesartistRDD = rawArtistData.map(lambda k: k.split("\t"))artist_df = spark.createDataFrame(artistRDD,schema_artist,['artistId','artistName'])userArtistRDD = rawUserArtistData.map(lambda k: k.split())user_artist_df = spark.createDataFrame(userArtistRDD,['userId','artistId','playCount'])aliasRDD = rawArtistAlias.map(lambda k: k.split())alias_df = spark.createDataFrame(aliasRDD,['badId', 'goodId'])#First for convenience, we can create aliases for each dataframesua = user_artist_df.alias('ua')ub = artist_df.alias('ub')
Once the datasets have been processed, we can proceed train our ALS model. Before that, we should split our dataset into training and testing data so that we will know how well our model has performed.
# dataset split into training and testing set(training, test) = ua.randomSplit([0.8, 0.2])# training the modelals = ALS(maxIter=5, implicitPrefs=True,userCol="userId", itemCol="artistId", ratingCol="playCount",coldStartStrategy="drop")model = als.fit(training)# predict using the testing datatsetpredictions = model.transform(test)predictions.show()
We can try using the model to find Top Artists recommended for each user. We can use the recommendForAllUsers function available in the ALS model to get the list of top recommendations for each users.
The function below takes userId and limit as the input. For the given userId, it gets the list of current top liked artists (based on the playcount). Let’s try to display the top liked artists for user (2062243).
def currentLikes(ua,ub,userId,limit): df = ua.join(ub,ua.artistId==ub.artistId)\ .filter(ua.userId==userId)\ .sort(ua.playCount.desc())\ .select(ua.userId,ua.playCount,ub.artistName)\ .limit(limit) return df# display top 10 liked artists for user 2062243currentLikes(ua,ub,2062243,10).show(truncate=False)
The following function then uses the model to give top recommendations of artists for each users. Let’s try to display the recommended artists for the same user (2062243).
def recommendedArtists(userId,limit): test = model.recommendForAllUsers(limit).filter(col('userId')==userId).select("recommendations").collect() topArtists = [] for item in test[0][0]: topArtists.append(item.artistId) schema = StructType([StructField("artistId",IntegerType(),True)])artists = spark.createDataFrame(topArtists,IntegerType())final=artists.join(ub,artists.value==ub.artistId).select(ub.artistId,ub.artistName)return final# display top 10 recommended artists for user 2062243recommendedArtists(2062243,10).show(truncate=False)
In this article, we have introduced what’s Collaborative Filtering is about and it’s 4 different stages. The two categories of data collected for Collaborative Filtering, mainly Implicit and Explicit Feedbacks, and calculating the similarity using Euclidean Distance or Pearson Coefficient. Finally, a brief walkthrough of implementing Collaborative Filtering was introducted in Pyspark using inbuilt Alternating Least Squares (ALS) algorithm in Spark. Hope you guys have a brief idea of how Recommendation System works and don’t be surprised to see good recommendations for you next time you surf the net and use Spotify/Amazon, cheers!
|
[
{
"code": null,
"e": 532,
"s": 171,
"text": "Have you ever wonder how Spotify is able to put up a list of songs every week in “Discover Weekly” and you ended up adding some of these songs to your playlists because you like them? What about the those shows recommended for you by Netflix because you watched a particular show yesterday? How are these tech giants so smart? The answer is Recommender System."
},
{
"code": null,
"e": 791,
"s": 532,
"text": "A Recommender System makes prediction based on users’ historical behaviours like view, search or purchase histories. Two common approaches of recommender system are Content Based and Collaborative Filtering, and this article will dive deeper into the latter."
},
{
"code": null,
"e": 1009,
"s": 791,
"text": "Collaborative Filtering is a mathematical method to find the predictions about how users can rate a particular item based on ratings of other similar users. Typical Collaborative Filtering involves 4 different stages:"
},
{
"code": null,
"e": 1270,
"s": 1009,
"text": "Data Collection — Collecting user behaviours and associated data itemsData Processing — Processing the collected dataRecommendation Calculation — Calculate referrals based on processed dataResult Derivation — Extract the similarity and return the top N results"
},
{
"code": null,
"e": 1341,
"s": 1270,
"text": "Data Collection — Collecting user behaviours and associated data items"
},
{
"code": null,
"e": 1389,
"s": 1341,
"text": "Data Processing — Processing the collected data"
},
{
"code": null,
"e": 1462,
"s": 1389,
"text": "Recommendation Calculation — Calculate referrals based on processed data"
},
{
"code": null,
"e": 1534,
"s": 1462,
"text": "Result Derivation — Extract the similarity and return the top N results"
},
{
"code": null,
"e": 1723,
"s": 1534,
"text": "So what type of data are being collected in the first stage of Collaborative Filtering? There’s two different categories of data (referred as feedbacks), which can be Explicit or Implicit."
},
{
"code": null,
"e": 2149,
"s": 1723,
"text": "An example of Explicit Feedback is the ratings given by users, which Netflix is collecting to make recommendations to their customers after they provide ratings to the movies they have watched. Implicit Feedback is less straightforward as it’s based on the users’ interactions with the platform, ranging from clicks, views, likes and purchases. Spotify makes use of Implicit Feedbacks to implement it’s recommendation system."
},
{
"code": null,
"e": 2303,
"s": 2149,
"text": "Once the data has been collected and processed, some mathematical formula is needed to make the similarity calculation. The two most common measures are:"
},
{
"code": null,
"e": 2563,
"s": 2303,
"text": "Euclidean Distance — Distance of the preference between two users. If the distance is small, similarity between both users is highPearson Correlation — If the cosine values (angle of incidence) between two users coincide, similarity between both users is high"
},
{
"code": null,
"e": 2694,
"s": 2563,
"text": "Euclidean Distance — Distance of the preference between two users. If the distance is small, similarity between both users is high"
},
{
"code": null,
"e": 2824,
"s": 2694,
"text": "Pearson Correlation — If the cosine values (angle of incidence) between two users coincide, similarity between both users is high"
},
{
"code": null,
"e": 3107,
"s": 2824,
"text": "The library package spark.ml currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to make predictions. It uses the Alternating Least Squares (ALS) algorithm to learn these latent factors."
},
{
"code": null,
"e": 3185,
"s": 3107,
"text": "We will use the dataset from https://www.last.fm/api/ which contains 3 files:"
},
{
"code": null,
"e": 3243,
"s": 3185,
"text": "user_artist_data.txt 3 columns: userid artistid playcount"
},
{
"code": null,
"e": 3291,
"s": 3243,
"text": "artist_data.txt 2 columns: artistid artist_name"
},
{
"code": null,
"e": 3393,
"s": 3291,
"text": "artist_alias.txt 2 columns: badid, goodid [known incorrectly spelt artists and the correct artist id]"
},
{
"code": null,
"e": 3438,
"s": 3393,
"text": "Firstly, we set up Spark with the following."
},
{
"code": null,
"e": 3769,
"s": 3438,
"text": "# import librariesfrom pyspark import SparkContextfrom pyspark.ml.recommendation import ALSfrom pyspark.sql import SparkSession ,RowappName=\"Collaborative Filtering with PySpark\"# initialize the spark sessionspark = SparkSession.builder.appName(appName).getOrCreate()# get sparkcontext from the sparksessionsc = spark.sparkContext"
},
{
"code": null,
"e": 3877,
"s": 3769,
"text": "Then, we define the data structures and convert the Resilient Distributed Dataframe (RDDs) into dataframes."
},
{
"code": null,
"e": 4961,
"s": 3877,
"text": "from pyspark.sql.types import StructType,StructField,IntegerType,StringType,LongTypefrom pyspark.sql.functions import col#Define the schema for the datasetsschema_artist = StructType([StructField(\"artistId\",StringType(),True),StructField(\"artistName\",StringType(),True)])schema_user_artist = StructType([StructField(\"userId\",StringType(),True),StructField(\"artistId\",StringType(),True),StructField(\"playCount\",StringType(),True)])schema_alias = StructType([StructField(\"badId\",StringType(),True),StructField(\"goodId\",StringType(),True)])#Convert RDDs into DataframesartistRDD = rawArtistData.map(lambda k: k.split(\"\\t\"))artist_df = spark.createDataFrame(artistRDD,schema_artist,['artistId','artistName'])userArtistRDD = rawUserArtistData.map(lambda k: k.split())user_artist_df = spark.createDataFrame(userArtistRDD,['userId','artistId','playCount'])aliasRDD = rawArtistAlias.map(lambda k: k.split())alias_df = spark.createDataFrame(aliasRDD,['badId', 'goodId'])#First for convenience, we can create aliases for each dataframesua = user_artist_df.alias('ua')ub = artist_df.alias('ub')"
},
{
"code": null,
"e": 5163,
"s": 4961,
"text": "Once the datasets have been processed, we can proceed train our ALS model. Before that, we should split our dataset into training and testing data so that we will know how well our model has performed."
},
{
"code": null,
"e": 5513,
"s": 5163,
"text": "# dataset split into training and testing set(training, test) = ua.randomSplit([0.8, 0.2])# training the modelals = ALS(maxIter=5, implicitPrefs=True,userCol=\"userId\", itemCol=\"artistId\", ratingCol=\"playCount\",coldStartStrategy=\"drop\")model = als.fit(training)# predict using the testing datatsetpredictions = model.transform(test)predictions.show()"
},
{
"code": null,
"e": 5714,
"s": 5513,
"text": "We can try using the model to find Top Artists recommended for each user. We can use the recommendForAllUsers function available in the ALS model to get the list of top recommendations for each users."
},
{
"code": null,
"e": 5927,
"s": 5714,
"text": "The function below takes userId and limit as the input. For the given userId, it gets the list of current top liked artists (based on the playcount). Let’s try to display the top liked artists for user (2062243)."
},
{
"code": null,
"e": 6233,
"s": 5927,
"text": "def currentLikes(ua,ub,userId,limit): df = ua.join(ub,ua.artistId==ub.artistId)\\ .filter(ua.userId==userId)\\ .sort(ua.playCount.desc())\\ .select(ua.userId,ua.playCount,ub.artistName)\\ .limit(limit) return df# display top 10 liked artists for user 2062243currentLikes(ua,ub,2062243,10).show(truncate=False)"
},
{
"code": null,
"e": 6405,
"s": 6233,
"text": "The following function then uses the model to give top recommendations of artists for each users. Let’s try to display the recommended artists for the same user (2062243)."
},
{
"code": null,
"e": 6947,
"s": 6405,
"text": "def recommendedArtists(userId,limit): test = model.recommendForAllUsers(limit).filter(col('userId')==userId).select(\"recommendations\").collect() topArtists = [] for item in test[0][0]: topArtists.append(item.artistId) schema = StructType([StructField(\"artistId\",IntegerType(),True)])artists = spark.createDataFrame(topArtists,IntegerType())final=artists.join(ub,artists.value==ub.artistId).select(ub.artistId,ub.artistName)return final# display top 10 recommended artists for user 2062243recommendedArtists(2062243,10).show(truncate=False)"
}
] |
How to add a list item in HTML?
|
The HTML <li> tag is used to add a list item is ordered, unordered, directory, and menu lists. The tag also supports the following additional attributes −
You can try to run the following code to add a list item in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML li Tag</title>
</head>
<body>
<p>Rank</p>
<ul>
<li>India</li>
<li>Australia</li>
<li>South Africa</li>
</ul>
</body>
</html>
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "The HTML <li> tag is used to add a list item is ordered, unordered, directory, and menu lists. The tag also supports the following additional attributes −"
},
{
"code": null,
"e": 1284,
"s": 1217,
"text": "You can try to run the following code to add a list item in HTML −"
},
{
"code": null,
"e": 1514,
"s": 1284,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML li Tag</title>\n </head>\n <body>\n <p>Rank</p>\n <ul>\n <li>India</li>\n <li>Australia</li>\n <li>South Africa</li>\n </ul>\n </body>\n</html>"
}
] |
Lodash _.toString() Method - GeeksforGeeks
|
06 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.toString() method is used to convert the given value to a string. An empty string is returned for null and undefined values. The sign of the value -0 is preserved.
Syntax:
_.toString( value )
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to convert.
Return Value: This method returns the converted string.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.toString() method console.log(_.toString(-0)); console.log(_.toString(['html', 'css', 'javascript']));
Output:
'-0'
'html,css,javascript'
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.toString() method // Will print an empty stringconsole.log(_.toString(null)); console.log(_.toString([1, 2, 3]));
Output:
''
'1,2,3'
JavaScript-Lodash
JavaScript
Web Technologies
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24205,
"s": 24177,
"text": "\n06 Sep, 2020"
},
{
"code": null,
"e": 24345,
"s": 24205,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 24515,
"s": 24345,
"text": "The _.toString() method is used to convert the given value to a string. An empty string is returned for null and undefined values. The sign of the value -0 is preserved."
},
{
"code": null,
"e": 24523,
"s": 24515,
"text": "Syntax:"
},
{
"code": null,
"e": 24543,
"s": 24523,
"text": "_.toString( value )"
},
{
"code": null,
"e": 24634,
"s": 24543,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 24684,
"s": 24634,
"text": "value: This parameter holds the value to convert."
},
{
"code": null,
"e": 24740,
"s": 24684,
"text": "Return Value: This method returns the converted string."
},
{
"code": null,
"e": 24751,
"s": 24740,
"text": "Example 1:"
},
{
"code": null,
"e": 24762,
"s": 24751,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.toString() method console.log(_.toString(-0)); console.log(_.toString(['html', 'css', 'javascript']));",
"e": 24946,
"s": 24762,
"text": null
},
{
"code": null,
"e": 24954,
"s": 24946,
"text": "Output:"
},
{
"code": null,
"e": 24982,
"s": 24954,
"text": "'-0'\n'html,css,javascript'\n"
},
{
"code": null,
"e": 24995,
"s": 24982,
"text": "Example 2: "
},
{
"code": null,
"e": 25006,
"s": 24995,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.toString() method // Will print an empty stringconsole.log(_.toString(null)); console.log(_.toString([1, 2, 3]));",
"e": 25202,
"s": 25006,
"text": null
},
{
"code": null,
"e": 25211,
"s": 25202,
"text": " Output:"
},
{
"code": null,
"e": 25223,
"s": 25211,
"text": "''\n'1,2,3'\n"
},
{
"code": null,
"e": 25241,
"s": 25223,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 25252,
"s": 25241,
"text": "JavaScript"
},
{
"code": null,
"e": 25269,
"s": 25252,
"text": "Web Technologies"
},
{
"code": null,
"e": 25367,
"s": 25269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25376,
"s": 25367,
"text": "Comments"
},
{
"code": null,
"e": 25389,
"s": 25376,
"text": "Old Comments"
},
{
"code": null,
"e": 25450,
"s": 25389,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 25495,
"s": 25450,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25567,
"s": 25495,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 25613,
"s": 25567,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 25661,
"s": 25613,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 25717,
"s": 25661,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 25750,
"s": 25717,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25812,
"s": 25750,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25855,
"s": 25812,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Customer Reviews Analysis using NLP — The Netflix Use Case | by Salih Boutadghart | Towards Data Science
|
In the era of digitalization, most companies have various sources of customer feedback, social media, call logs, mobile apps, to name a few. Therefore, analyzing such feedback to come up with actionable insights, is becoming essential for any business with an online presence.
Some of the challenges businesses face while analyzing customers' feedback is the qualitative nature of the data and sometimes the huge amount of feedback they get. Ratings are quantitative and hence can be easily analyzed, however analyzing textual feedback, reviews, and free text is challenging. Likely, today we have Natural Language Processing and Machine Learning to efficiently process a large amount of text without human intervention.
There are mainly two approaches that can be used to find topics in text data, Topic Modeling, or Text Clustering. In this tutorial, we will go through some techniques and ideas about the two approaches and try to understand what people are talking about in mobile app reviews. We will start by fetching some reviews data, taking as an example the Netflix's mobile app, then we will apply a series of preprocessing techniques to prepare the data for topic detection.
In the following analysis, I used a dataset of 5000 recent reviews from the Netflix mobile app on Google Play. The following figure shows the daily number of reviews with a score of 1, it gives us an idea about the amount of data we are dealing with.
We can also look at the review length distribution. As we can see, usually people submit short to medium size reviews (under 50 words).
I used a maximum length of 48 words for all reviews, longer reviews are discarded from the dataset.
Text preprocessing is an important step for natural language processing. It transforms text into a more digestible and usable form so that machine learning algorithms can perform better.
In our case, I applied the following transformation:
Remove URLs, emails, phone numbers & punctuations.
Remove tags, emojis, symbols & pictographs.
Remove stop words.
Convert to lowercase and lemmatization.
Duplicates removal.
Spell checking.
Non-English reviews removal.
Once preprocessing is done, we can look at a random review example.
Original review: {'It has all the boring movies and episodes'}Preprocessed review: {'boring movie episode'}
In topic modeling, a topic is defined by a cluster of words with their respective probabilities of occurrence in the cluster. The goal is to find the topics in a set of documents, without having prior knowledge about those topics. In most cases, we only need to specify the number of topics and leave the rest of the algorithms.
Probably the most popular topic modeling approach, it treats each document (text) as a mixture of topics, and each word in a document is considered randomly drawn from the document’s topics. The topics are considered hidden (thus the ‘Latent’ in the name) which must be uncovered through analyzing joint distribution to compute the conditional distribution of hidden variables (topics) given the observed variables, words in documents. This takes into consideration the fact that documents can have an overlap of topics which is somehow a typical case in the natural language.
I performed LDA for topic modeling using the amazing library gensim, and also use it to tokenize the data and prepare dictionary and bag-of-words features.
In order to have a good LDA model, we need to find a suitable number of topics that give good quality topics. One of the commonly used approaches to evaluate topics is measuring the Topic Coherence, it’s a single score by topic where it measures the degree of semantic similarity between high scoring words in the topic. These measurements help distinguish between topics that are semantically interpretable and topics that are artifacts of statistical inference. I used C_v measure which is based on a sliding window, one-set segmentation of the top words, and an indirect confirmation measurement that uses normalized pointwise mutual information (NPMI) and the cosine similarity. Read more about coherence measures here.
I ran multiple LDA models with different numbers of topics and picked the one with the highest score. We could also finetune other hyperparameters like document-topic density (alpha) or word-topic density (beta), however, I keep it simple and only finetune the number of topics.
We pick the number of topics with the highest coherence score: K=30
As we can see, we got many topics related to technical issues about the app, controversies, and people not satisfied with the app. we will dig deeper into the clusters in the next approaches.
Despite its popularity and usefulness in the context of medium and large documents, LDA generally performs poorly with short documents. In our case, reviews are generally short texts (> 50 word) with typically one topic, which is not necessary LDA’s assumption. In order to solve this issue, we will try out a Short Text Topic Modeling.
In order to model topics in short texts, we use an altered LDA approach called Gibbs Sampling Dirichlet Mixture Model (GSDMM) where the main assumptions are :
Each document corresponds to only one topic.
The words in a document are generated using one unique topic.
The GSDMM model can be explained with a process called the Movie Group Process, where a professor is leading a film class and students are randomly seated at K table. Students are asked to make a shortlist of their favorite movies and each time a student is called, he or she must select a new table regarding the two following conditions:
The new table has more students than the current table.
The new table has students with similar lists of favorite movies.
After repeating this process consistently, we expect that the students eventually arrive at an optimal table configuration. where some tables will disappear and others to grow larger to form clusters of students with similar movies’ interests.
We adapt rwalk’s implementation for our STTM.
we start with a K = 30 number of topics and let GSDMM find the optimal number of topics.
Similar to LDA, STTM did a good job in highlighting the main topics.
In this section, we will look into how Text Clustering can help with detecting topics and categorizing reviews. In clustering, the idea is to group documents, with potentially semantic similarities, into different groups. First, we represent each document with a numerical vector in a way similar documents should have closer vectors in the space (using a similarity metric). We will test out different approaches, from classic ones like tf-idf to recent and advanced ones around the idea of documents embedding.
TF-IDF stands for Term Frequency — Inverse Document Frequency and is have been explained in many articles and tutorials in the data science community, but I will remaind you of the main formula :
tfidf(w,d,D)=tf(w,d)∗idf(w,D)tfidf(w,d,D)=tf(w,d)∗idf(w,D)
with : tf(w,d)=log(1+f(w,d))tf(w,d)=log(1+f(w,d)) and idf(w,D)=log(N/f(w,D))idf(w,D)=log(N/f(w,D))
where :
f(w,d) is the frequency of word w in document d.
d is a document from our dataset
w is a word in a document
D is the collection of all documents
N is the number of documents we have in our dataset
An other way to vectorize document is to use LDA features where each vector represent the probabilities of belonging to a topic. We fix number of topics to 20, for example, to have 20-dim vector for each review text item.
Sklearn made it easy to calculate TFIDF and LDA features.
Embeddings are low-dimensional learned continuous vector representations for words, sentences, or documents. They can be used in many use cases like finding similar documents, do machine learning on text, and visualizing text and relationships.
For our use case, we want to represent reviews as vectors representation to be able to apply clustering algorithms to detect topics. Reviews are usually short sentences, thus, we should look for a suitable embedding approach for this situation.
Here is the list of the approaches I have tested :
Sentence Transformers using BERT.
Vanilla BERT: CLS token as an embedding, Averaging last hidden layer outputs as an embedding, Averaging the concatenation of last hidden layers outputs as an embedding
Facebook’s InferSent: using GloVe or using FastText
We will use the first approach with the model bert-large-nli-stsb-mean-tokens, as it showed the best performance in general.
In order to visualize the chosen embeddings, we should use a dimensionality reduction approach to represent reviews in the 2D space. We have many options like PCA, t-SNE, TriMap, AutoEncoders, and UMAP. I tried most of those techniques, but I will stick with UMAP as it’s is a dimension reduction technique that is gaining a lot of popularity recently.
We reduced the embeddings to 16 for better clustering, and we will use a 2-dimension reduction for the visualization.
Once features are ready, we can proceed with applying clustering algorithms to hopefully detect relevant topics in our reviews dataset. As we don’t know the number of topics, we will avoid using k-means, where it’s always programmatically difficult to find the best K, and usually performs poorly if the assumptions on the shape of the clusters aren't met.
As an alternative, we will use HDBSCAN (Hierarchical Density-Based Spatial Clustering of Applications with Noise) which is a density-based clustering algorithm. HDBSCAN extends DBSCAN by converting it into a hierarchical clustering algorithm and then using a technique to extract a flat clustering based on the stability of clusters.
We can summarize how HDBSCAN algorithm works in the following steps:
Transform the space according to the density/sparsity via building the minimum spanning tree from the mutual reachability distances.Construct a cluster hierarchy of connected componentsCondense and extract the stable clusters from the condensed tree
Transform the space according to the density/sparsity via building the minimum spanning tree from the mutual reachability distances.
Construct a cluster hierarchy of connected components
Condense and extract the stable clusters from the condensed tree
To learn more about HDBSCAN, check this detailed article. Likely, we have a high performing implementation of HDBSCAN clustering that we can use to do our clustering.
HDBSCAN has a couple of major parameters that we need to tune to get good clusters. we will focus on two main parameters, min_cluster_size which should be set to the smallest cluster size that we wish to consider, and min_samples measures how clusters are conservative to the noisy points. You can read more about parameter selection for HDBSAN here.
Let’s fix those parameters and run the HDBSCAN on the embeddings. We choose min_cluster_size = 40 and min_samples = 10.
Now we can visualize the embeddings in a 2D space with their associated clusters to have an idea of how the clusters are dense.
In order to better evaluate clusters and highlight the best coherent ones, we will sort them by size (i.e, the number of reviews in a cluster), and the median outlier score for the items in the clusters. this score can be found in the attribute outlier_scores_ in the clusterer object. it provides a value for each sample in the original dataset that was fit with the clusterer. The higher the score, the more likely the point is to be an outlier. Let’s explore the results! we remove the clustering representing the noisy points and order the clusters by their size or how dense they are.
The figure shows the word cloud for each cluster detected by HDBSCAN, the title contains the cluster/topic number, the percentage, and the number of reviews belonging to that topic.
Few insights from the clusters :
The biggest two clusters, (Topics 20,22) representing around 16% of all reviews, are related to the topic of boycott and controversy around the French movie ‘Cuties’.
Another prominent cluster (Topic 35) is related to people experiencing issues when they open the Netflix app, especially after installing some updates.
Topic 18 is mainly about people leaving negative reviews about the content on Netflix.
Another recurrent issue reported many times is when the video freezes after a certain number of seconds.
A lot of reviews are related to hurting Hindu sentiments and promoting propaganda. Apparently, it's about another controversy caused by Netflix.
In some clusters, people are asking about more movies that aren't currently available on Netflix, many of them are related to Bollywood movies.
We can see many topics related to technical issues about the app: Issues with login, a black screen when playing a video, app crashing after the start, payments can’t be processed, people requesting other payment methods (Rupay), video/audio isn’t working properly...
As we have seen, Natural language processing can be very useful when it comes to customer feedback understanding. We have used topic modeling and text clustering to detect relevant topics in Netflix Android app reviews from Google Play. All mentioned approaches can be improved further via more hyperparameters finetuning. If you have any questions or comments, feel free to connect with me on LinkedIn.
Originally published here.
|
[
{
"code": null,
"e": 448,
"s": 171,
"text": "In the era of digitalization, most companies have various sources of customer feedback, social media, call logs, mobile apps, to name a few. Therefore, analyzing such feedback to come up with actionable insights, is becoming essential for any business with an online presence."
},
{
"code": null,
"e": 892,
"s": 448,
"text": "Some of the challenges businesses face while analyzing customers' feedback is the qualitative nature of the data and sometimes the huge amount of feedback they get. Ratings are quantitative and hence can be easily analyzed, however analyzing textual feedback, reviews, and free text is challenging. Likely, today we have Natural Language Processing and Machine Learning to efficiently process a large amount of text without human intervention."
},
{
"code": null,
"e": 1358,
"s": 892,
"text": "There are mainly two approaches that can be used to find topics in text data, Topic Modeling, or Text Clustering. In this tutorial, we will go through some techniques and ideas about the two approaches and try to understand what people are talking about in mobile app reviews. We will start by fetching some reviews data, taking as an example the Netflix's mobile app, then we will apply a series of preprocessing techniques to prepare the data for topic detection."
},
{
"code": null,
"e": 1609,
"s": 1358,
"text": "In the following analysis, I used a dataset of 5000 recent reviews from the Netflix mobile app on Google Play. The following figure shows the daily number of reviews with a score of 1, it gives us an idea about the amount of data we are dealing with."
},
{
"code": null,
"e": 1745,
"s": 1609,
"text": "We can also look at the review length distribution. As we can see, usually people submit short to medium size reviews (under 50 words)."
},
{
"code": null,
"e": 1845,
"s": 1745,
"text": "I used a maximum length of 48 words for all reviews, longer reviews are discarded from the dataset."
},
{
"code": null,
"e": 2032,
"s": 1845,
"text": "Text preprocessing is an important step for natural language processing. It transforms text into a more digestible and usable form so that machine learning algorithms can perform better."
},
{
"code": null,
"e": 2085,
"s": 2032,
"text": "In our case, I applied the following transformation:"
},
{
"code": null,
"e": 2136,
"s": 2085,
"text": "Remove URLs, emails, phone numbers & punctuations."
},
{
"code": null,
"e": 2180,
"s": 2136,
"text": "Remove tags, emojis, symbols & pictographs."
},
{
"code": null,
"e": 2199,
"s": 2180,
"text": "Remove stop words."
},
{
"code": null,
"e": 2239,
"s": 2199,
"text": "Convert to lowercase and lemmatization."
},
{
"code": null,
"e": 2259,
"s": 2239,
"text": "Duplicates removal."
},
{
"code": null,
"e": 2275,
"s": 2259,
"text": "Spell checking."
},
{
"code": null,
"e": 2304,
"s": 2275,
"text": "Non-English reviews removal."
},
{
"code": null,
"e": 2372,
"s": 2304,
"text": "Once preprocessing is done, we can look at a random review example."
},
{
"code": null,
"e": 2480,
"s": 2372,
"text": "Original review: {'It has all the boring movies and episodes'}Preprocessed review: {'boring movie episode'}"
},
{
"code": null,
"e": 2809,
"s": 2480,
"text": "In topic modeling, a topic is defined by a cluster of words with their respective probabilities of occurrence in the cluster. The goal is to find the topics in a set of documents, without having prior knowledge about those topics. In most cases, we only need to specify the number of topics and leave the rest of the algorithms."
},
{
"code": null,
"e": 3386,
"s": 2809,
"text": "Probably the most popular topic modeling approach, it treats each document (text) as a mixture of topics, and each word in a document is considered randomly drawn from the document’s topics. The topics are considered hidden (thus the ‘Latent’ in the name) which must be uncovered through analyzing joint distribution to compute the conditional distribution of hidden variables (topics) given the observed variables, words in documents. This takes into consideration the fact that documents can have an overlap of topics which is somehow a typical case in the natural language."
},
{
"code": null,
"e": 3542,
"s": 3386,
"text": "I performed LDA for topic modeling using the amazing library gensim, and also use it to tokenize the data and prepare dictionary and bag-of-words features."
},
{
"code": null,
"e": 4266,
"s": 3542,
"text": "In order to have a good LDA model, we need to find a suitable number of topics that give good quality topics. One of the commonly used approaches to evaluate topics is measuring the Topic Coherence, it’s a single score by topic where it measures the degree of semantic similarity between high scoring words in the topic. These measurements help distinguish between topics that are semantically interpretable and topics that are artifacts of statistical inference. I used C_v measure which is based on a sliding window, one-set segmentation of the top words, and an indirect confirmation measurement that uses normalized pointwise mutual information (NPMI) and the cosine similarity. Read more about coherence measures here."
},
{
"code": null,
"e": 4545,
"s": 4266,
"text": "I ran multiple LDA models with different numbers of topics and picked the one with the highest score. We could also finetune other hyperparameters like document-topic density (alpha) or word-topic density (beta), however, I keep it simple and only finetune the number of topics."
},
{
"code": null,
"e": 4613,
"s": 4545,
"text": "We pick the number of topics with the highest coherence score: K=30"
},
{
"code": null,
"e": 4805,
"s": 4613,
"text": "As we can see, we got many topics related to technical issues about the app, controversies, and people not satisfied with the app. we will dig deeper into the clusters in the next approaches."
},
{
"code": null,
"e": 5142,
"s": 4805,
"text": "Despite its popularity and usefulness in the context of medium and large documents, LDA generally performs poorly with short documents. In our case, reviews are generally short texts (> 50 word) with typically one topic, which is not necessary LDA’s assumption. In order to solve this issue, we will try out a Short Text Topic Modeling."
},
{
"code": null,
"e": 5301,
"s": 5142,
"text": "In order to model topics in short texts, we use an altered LDA approach called Gibbs Sampling Dirichlet Mixture Model (GSDMM) where the main assumptions are :"
},
{
"code": null,
"e": 5346,
"s": 5301,
"text": "Each document corresponds to only one topic."
},
{
"code": null,
"e": 5408,
"s": 5346,
"text": "The words in a document are generated using one unique topic."
},
{
"code": null,
"e": 5748,
"s": 5408,
"text": "The GSDMM model can be explained with a process called the Movie Group Process, where a professor is leading a film class and students are randomly seated at K table. Students are asked to make a shortlist of their favorite movies and each time a student is called, he or she must select a new table regarding the two following conditions:"
},
{
"code": null,
"e": 5804,
"s": 5748,
"text": "The new table has more students than the current table."
},
{
"code": null,
"e": 5870,
"s": 5804,
"text": "The new table has students with similar lists of favorite movies."
},
{
"code": null,
"e": 6114,
"s": 5870,
"text": "After repeating this process consistently, we expect that the students eventually arrive at an optimal table configuration. where some tables will disappear and others to grow larger to form clusters of students with similar movies’ interests."
},
{
"code": null,
"e": 6160,
"s": 6114,
"text": "We adapt rwalk’s implementation for our STTM."
},
{
"code": null,
"e": 6249,
"s": 6160,
"text": "we start with a K = 30 number of topics and let GSDMM find the optimal number of topics."
},
{
"code": null,
"e": 6318,
"s": 6249,
"text": "Similar to LDA, STTM did a good job in highlighting the main topics."
},
{
"code": null,
"e": 6831,
"s": 6318,
"text": "In this section, we will look into how Text Clustering can help with detecting topics and categorizing reviews. In clustering, the idea is to group documents, with potentially semantic similarities, into different groups. First, we represent each document with a numerical vector in a way similar documents should have closer vectors in the space (using a similarity metric). We will test out different approaches, from classic ones like tf-idf to recent and advanced ones around the idea of documents embedding."
},
{
"code": null,
"e": 7027,
"s": 6831,
"text": "TF-IDF stands for Term Frequency — Inverse Document Frequency and is have been explained in many articles and tutorials in the data science community, but I will remaind you of the main formula :"
},
{
"code": null,
"e": 7086,
"s": 7027,
"text": "tfidf(w,d,D)=tf(w,d)∗idf(w,D)tfidf(w,d,D)=tf(w,d)∗idf(w,D)"
},
{
"code": null,
"e": 7185,
"s": 7086,
"text": "with : tf(w,d)=log(1+f(w,d))tf(w,d)=log(1+f(w,d)) and idf(w,D)=log(N/f(w,D))idf(w,D)=log(N/f(w,D))"
},
{
"code": null,
"e": 7193,
"s": 7185,
"text": "where :"
},
{
"code": null,
"e": 7242,
"s": 7193,
"text": "f(w,d) is the frequency of word w in document d."
},
{
"code": null,
"e": 7275,
"s": 7242,
"text": "d is a document from our dataset"
},
{
"code": null,
"e": 7301,
"s": 7275,
"text": "w is a word in a document"
},
{
"code": null,
"e": 7338,
"s": 7301,
"text": "D is the collection of all documents"
},
{
"code": null,
"e": 7390,
"s": 7338,
"text": "N is the number of documents we have in our dataset"
},
{
"code": null,
"e": 7612,
"s": 7390,
"text": "An other way to vectorize document is to use LDA features where each vector represent the probabilities of belonging to a topic. We fix number of topics to 20, for example, to have 20-dim vector for each review text item."
},
{
"code": null,
"e": 7670,
"s": 7612,
"text": "Sklearn made it easy to calculate TFIDF and LDA features."
},
{
"code": null,
"e": 7915,
"s": 7670,
"text": "Embeddings are low-dimensional learned continuous vector representations for words, sentences, or documents. They can be used in many use cases like finding similar documents, do machine learning on text, and visualizing text and relationships."
},
{
"code": null,
"e": 8160,
"s": 7915,
"text": "For our use case, we want to represent reviews as vectors representation to be able to apply clustering algorithms to detect topics. Reviews are usually short sentences, thus, we should look for a suitable embedding approach for this situation."
},
{
"code": null,
"e": 8211,
"s": 8160,
"text": "Here is the list of the approaches I have tested :"
},
{
"code": null,
"e": 8245,
"s": 8211,
"text": "Sentence Transformers using BERT."
},
{
"code": null,
"e": 8413,
"s": 8245,
"text": "Vanilla BERT: CLS token as an embedding, Averaging last hidden layer outputs as an embedding, Averaging the concatenation of last hidden layers outputs as an embedding"
},
{
"code": null,
"e": 8465,
"s": 8413,
"text": "Facebook’s InferSent: using GloVe or using FastText"
},
{
"code": null,
"e": 8590,
"s": 8465,
"text": "We will use the first approach with the model bert-large-nli-stsb-mean-tokens, as it showed the best performance in general."
},
{
"code": null,
"e": 8943,
"s": 8590,
"text": "In order to visualize the chosen embeddings, we should use a dimensionality reduction approach to represent reviews in the 2D space. We have many options like PCA, t-SNE, TriMap, AutoEncoders, and UMAP. I tried most of those techniques, but I will stick with UMAP as it’s is a dimension reduction technique that is gaining a lot of popularity recently."
},
{
"code": null,
"e": 9061,
"s": 8943,
"text": "We reduced the embeddings to 16 for better clustering, and we will use a 2-dimension reduction for the visualization."
},
{
"code": null,
"e": 9418,
"s": 9061,
"text": "Once features are ready, we can proceed with applying clustering algorithms to hopefully detect relevant topics in our reviews dataset. As we don’t know the number of topics, we will avoid using k-means, where it’s always programmatically difficult to find the best K, and usually performs poorly if the assumptions on the shape of the clusters aren't met."
},
{
"code": null,
"e": 9752,
"s": 9418,
"text": "As an alternative, we will use HDBSCAN (Hierarchical Density-Based Spatial Clustering of Applications with Noise) which is a density-based clustering algorithm. HDBSCAN extends DBSCAN by converting it into a hierarchical clustering algorithm and then using a technique to extract a flat clustering based on the stability of clusters."
},
{
"code": null,
"e": 9821,
"s": 9752,
"text": "We can summarize how HDBSCAN algorithm works in the following steps:"
},
{
"code": null,
"e": 10071,
"s": 9821,
"text": "Transform the space according to the density/sparsity via building the minimum spanning tree from the mutual reachability distances.Construct a cluster hierarchy of connected componentsCondense and extract the stable clusters from the condensed tree"
},
{
"code": null,
"e": 10204,
"s": 10071,
"text": "Transform the space according to the density/sparsity via building the minimum spanning tree from the mutual reachability distances."
},
{
"code": null,
"e": 10258,
"s": 10204,
"text": "Construct a cluster hierarchy of connected components"
},
{
"code": null,
"e": 10323,
"s": 10258,
"text": "Condense and extract the stable clusters from the condensed tree"
},
{
"code": null,
"e": 10490,
"s": 10323,
"text": "To learn more about HDBSCAN, check this detailed article. Likely, we have a high performing implementation of HDBSCAN clustering that we can use to do our clustering."
},
{
"code": null,
"e": 10841,
"s": 10490,
"text": "HDBSCAN has a couple of major parameters that we need to tune to get good clusters. we will focus on two main parameters, min_cluster_size which should be set to the smallest cluster size that we wish to consider, and min_samples measures how clusters are conservative to the noisy points. You can read more about parameter selection for HDBSAN here."
},
{
"code": null,
"e": 10961,
"s": 10841,
"text": "Let’s fix those parameters and run the HDBSCAN on the embeddings. We choose min_cluster_size = 40 and min_samples = 10."
},
{
"code": null,
"e": 11089,
"s": 10961,
"text": "Now we can visualize the embeddings in a 2D space with their associated clusters to have an idea of how the clusters are dense."
},
{
"code": null,
"e": 11679,
"s": 11089,
"text": "In order to better evaluate clusters and highlight the best coherent ones, we will sort them by size (i.e, the number of reviews in a cluster), and the median outlier score for the items in the clusters. this score can be found in the attribute outlier_scores_ in the clusterer object. it provides a value for each sample in the original dataset that was fit with the clusterer. The higher the score, the more likely the point is to be an outlier. Let’s explore the results! we remove the clustering representing the noisy points and order the clusters by their size or how dense they are."
},
{
"code": null,
"e": 11861,
"s": 11679,
"text": "The figure shows the word cloud for each cluster detected by HDBSCAN, the title contains the cluster/topic number, the percentage, and the number of reviews belonging to that topic."
},
{
"code": null,
"e": 11894,
"s": 11861,
"text": "Few insights from the clusters :"
},
{
"code": null,
"e": 12061,
"s": 11894,
"text": "The biggest two clusters, (Topics 20,22) representing around 16% of all reviews, are related to the topic of boycott and controversy around the French movie ‘Cuties’."
},
{
"code": null,
"e": 12213,
"s": 12061,
"text": "Another prominent cluster (Topic 35) is related to people experiencing issues when they open the Netflix app, especially after installing some updates."
},
{
"code": null,
"e": 12300,
"s": 12213,
"text": "Topic 18 is mainly about people leaving negative reviews about the content on Netflix."
},
{
"code": null,
"e": 12405,
"s": 12300,
"text": "Another recurrent issue reported many times is when the video freezes after a certain number of seconds."
},
{
"code": null,
"e": 12550,
"s": 12405,
"text": "A lot of reviews are related to hurting Hindu sentiments and promoting propaganda. Apparently, it's about another controversy caused by Netflix."
},
{
"code": null,
"e": 12694,
"s": 12550,
"text": "In some clusters, people are asking about more movies that aren't currently available on Netflix, many of them are related to Bollywood movies."
},
{
"code": null,
"e": 12962,
"s": 12694,
"text": "We can see many topics related to technical issues about the app: Issues with login, a black screen when playing a video, app crashing after the start, payments can’t be processed, people requesting other payment methods (Rupay), video/audio isn’t working properly..."
},
{
"code": null,
"e": 13366,
"s": 12962,
"text": "As we have seen, Natural language processing can be very useful when it comes to customer feedback understanding. We have used topic modeling and text clustering to detect relevant topics in Netflix Android app reviews from Google Play. All mentioned approaches can be improved further via more hyperparameters finetuning. If you have any questions or comments, feel free to connect with me on LinkedIn."
}
] |
Program to find HCF iteratively - GeeksforGeeks
|
26 Nov, 2021
HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them.
For example, GCD of 20 and 28 is 4, and GCD of 98 and 56 is 14.
We have discussed the recursive solution in the below post. Recursive program to find GCD or HCF of two numbersBelow is the iterative implementation of Euclid’s algorithm
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find HCF of two// numbers iteratively.#include <bits/stdc++.h>using namespace std; int hcf(int a, int b){ if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a;} // Driver codeint main(){ int a = 60, b = 96; cout << hcf(a, b) << endl; return 0;} // This code is contributed by shubhamsingh10
// C program to find HCF of two// numbers iteratively.#include <stdio.h> int hcf(int a, int b){ if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a;}int main(){ int a = 60, b = 96; printf("%d\n", hcf(a, b)); return 0;}
// JAVA Code for Program to find// HCF iterativelyimport java.util.*; class GFG { static int hcf(int a, int b) { if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a; } /* Driver program */ public static void main(String[] args) { int a = 60, b = 96; System.out.println(hcf(a, b)); }} // This code is contributed by Arnav Kr. Mandal.
// Python program to find HCF of two// numbers iteratively. def hcf(a, b): if(a == 0): return b else if(b == 0): return a while (a != b): if (a > b): a = a - b else: b = b - a return a a = 60b = 96print(hcf(a, b))
// C# Code for Program to find// HCF iterativelyusing System; class GFG { static int hcf(int a, int b) { if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a; } // Driver program public static void Main() { int a = 60, b = 96; Console.WriteLine(hcf(a, b)); }} // This code is contributed by vt_m.
<?php//PHP program to find HCF of two// numbers iteratively. function hcf($a, $b){ if($a==0) return $b; else if($b==0) return $a; while ($a != $b) { if ($a > $b) $a = $a - $b; else $b = $b - $a; } return $a;} // Driver code$a = 60; $b = 96;echo hcf($a, $b), "\n"; // This code is contributed by ajit?>
<script> //Javascript program to find HCF of two// numbers iteratively. function hcf(a, b){ if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a;} // Driver code let a = 60, b = 96; document.write(hcf(a, b) + "<br>"); // This code is contributed by Mayank Tyagi </script>
Output:
12
Time Complexity: O(max(a, b))
Auxiliary Space: O(1)
jit_t
SHUBHAMSINGH10
mayanktyagi1709
kajal mohite
samim2000
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Find all factors of a natural number | Set 1
Modulo 10^9+7 (1000000007)
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Operators in C / C++
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 24244,
"s": 24216,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 24371,
"s": 24244,
"text": "HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them. "
},
{
"code": null,
"e": 24436,
"s": 24371,
"text": "For example, GCD of 20 and 28 is 4, and GCD of 98 and 56 is 14. "
},
{
"code": null,
"e": 24609,
"s": 24436,
"text": "We have discussed the recursive solution in the below post. Recursive program to find GCD or HCF of two numbersBelow is the iterative implementation of Euclid’s algorithm "
},
{
"code": null,
"e": 24613,
"s": 24609,
"text": "C++"
},
{
"code": null,
"e": 24615,
"s": 24613,
"text": "C"
},
{
"code": null,
"e": 24620,
"s": 24615,
"text": "Java"
},
{
"code": null,
"e": 24628,
"s": 24620,
"text": "Python3"
},
{
"code": null,
"e": 24631,
"s": 24628,
"text": "C#"
},
{
"code": null,
"e": 24635,
"s": 24631,
"text": "PHP"
},
{
"code": null,
"e": 24646,
"s": 24635,
"text": "Javascript"
},
{
"code": "// C++ program to find HCF of two// numbers iteratively.#include <bits/stdc++.h>using namespace std; int hcf(int a, int b){ if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a;} // Driver codeint main(){ int a = 60, b = 96; cout << hcf(a, b) << endl; return 0;} // This code is contributed by shubhamsingh10",
"e": 25091,
"s": 24646,
"text": null
},
{
"code": "// C program to find HCF of two// numbers iteratively.#include <stdio.h> int hcf(int a, int b){ if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a;}int main(){ int a = 60, b = 96; printf(\"%d\\n\", hcf(a, b)); return 0;}",
"e": 25447,
"s": 25091,
"text": null
},
{
"code": "// JAVA Code for Program to find// HCF iterativelyimport java.util.*; class GFG { static int hcf(int a, int b) { if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a; } /* Driver program */ public static void main(String[] args) { int a = 60, b = 96; System.out.println(hcf(a, b)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 25989,
"s": 25447,
"text": null
},
{
"code": "// Python program to find HCF of two// numbers iteratively. def hcf(a, b): if(a == 0): return b else if(b == 0): return a while (a != b): if (a > b): a = a - b else: b = b - a return a a = 60b = 96print(hcf(a, b))",
"e": 26263,
"s": 25989,
"text": null
},
{
"code": "// C# Code for Program to find// HCF iterativelyusing System; class GFG { static int hcf(int a, int b) { if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a; } // Driver program public static void Main() { int a = 60, b = 96; Console.WriteLine(hcf(a, b)); }} // This code is contributed by vt_m.",
"e": 26768,
"s": 26263,
"text": null
},
{
"code": "<?php//PHP program to find HCF of two// numbers iteratively. function hcf($a, $b){ if($a==0) return $b; else if($b==0) return $a; while ($a != $b) { if ($a > $b) $a = $a - $b; else $b = $b - $a; } return $a;} // Driver code$a = 60; $b = 96;echo hcf($a, $b), \"\\n\"; // This code is contributed by ajit?>",
"e": 27150,
"s": 26768,
"text": null
},
{
"code": "<script> //Javascript program to find HCF of two// numbers iteratively. function hcf(a, b){ if (a == 0) return b; else if (b == 0) return a; while (a != b) { if (a > b) a = a - b; else b = b - a; } return a;} // Driver code let a = 60, b = 96; document.write(hcf(a, b) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>",
"e": 27576,
"s": 27150,
"text": null
},
{
"code": null,
"e": 27585,
"s": 27576,
"text": "Output: "
},
{
"code": null,
"e": 27588,
"s": 27585,
"text": "12"
},
{
"code": null,
"e": 27618,
"s": 27588,
"text": "Time Complexity: O(max(a, b))"
},
{
"code": null,
"e": 27640,
"s": 27618,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27646,
"s": 27640,
"text": "jit_t"
},
{
"code": null,
"e": 27661,
"s": 27646,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 27677,
"s": 27661,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 27690,
"s": 27677,
"text": "kajal mohite"
},
{
"code": null,
"e": 27700,
"s": 27690,
"text": "samim2000"
},
{
"code": null,
"e": 27708,
"s": 27700,
"text": "GCD-LCM"
},
{
"code": null,
"e": 27721,
"s": 27708,
"text": "Mathematical"
},
{
"code": null,
"e": 27734,
"s": 27721,
"text": "Mathematical"
},
{
"code": null,
"e": 27832,
"s": 27734,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27841,
"s": 27832,
"text": "Comments"
},
{
"code": null,
"e": 27854,
"s": 27841,
"text": "Old Comments"
},
{
"code": null,
"e": 27878,
"s": 27854,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 27892,
"s": 27878,
"text": "Prime Numbers"
},
{
"code": null,
"e": 27935,
"s": 27892,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 27980,
"s": 27935,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 28007,
"s": 27980,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 28056,
"s": 28007,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28099,
"s": 28056,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 28133,
"s": 28099,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 28154,
"s": 28133,
"text": "Operators in C / C++"
}
] |
How to detect click event outside Angular component ? - GeeksforGeeks
|
05 Nov, 2020
In angular, clicks are detected by different ways. As click is an event, thus inside a component it is detected by simple event binding. A simple click via event binding for detection within the component is given as follows:
@Component({ selector: "geeks", template: `<h1 (click)="clicked()">{{ some_text }}</h1> `})export class GeeksComponent { constructor() {} some_text = "Click Here"; clicked() { this.some_text = "Event Triggered"; }}
To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs.
Approach: Here the approach is to use @HostListener decorator. In angular, it is a decorator that helps in capturing any kind of event happening inside the DOM and gives the developer flexibility to perform any action based on that event. Here, on the simple click event, the handler will be referring the click event onto the component and for click on allover the DOM, it will capture using document:click.
The syntax for using HostListener is given as follows:
Syntax:
@HostListener(events, args)
handler_name(args){
// Do something
}
There are three things to note in the syntax of HostListener:
eventName: As the name suggests, this takes in the name of the event in the DOM, that needs to be listened.args: These are set of arguments to pass to the handler method when the event occurs. It takes input in list format.handlen_name: Here comes the method definition that will be called when event is triggered. It is called by the HostListener automatically.
eventName: As the name suggests, this takes in the name of the event in the DOM, that needs to be listened.
args: These are set of arguments to pass to the handler method when the event occurs. It takes input in list format.
handlen_name: Here comes the method definition that will be called when event is triggered. It is called by the HostListener automatically.
Example: Bind with click within component For binding the click within the component, the eventName that will go inside the hostListener will be simply ‘click’. The above code in such a case will be written as :
@Component({ selector: "geeks", template: ` <h1>{{ some_text }}</h1> `})export class GeeksComponent { constructor() {} some_text = "Click Here"; @HostListener("click") clicked() { this.some_text = "Event Triggered"; }}
Output:
Here there is no need to pass arguments for the handler to run. the HostListener takes ‘click’ as the event which triggered the method clicked.
Bind with click outside componentFor detection of the click outside the component, another event is to be taken look at. Here the click will not work as it detects click within the component. Here the key will be looking for click within the DOM and not just the component, and thus ‘document:click’ will be the right choice for that and also at the same time we need to filter out the event within the component which is done by the Boolean variable ‘inside’. So in the code given as follows, there will be another component added to is which will act as outside context, but click on that will cause the click event on the current component.
@Component({ selector: "another", template: ` <div style="border-style: solid;margin:5px;"> <h1>Outside Component</h1> <h2>Click here for outer component trigger</h2> </div> <geeks></geeks> `})export class AnotherComponent { constructor() {}}@Component({ selector: "geeks", template: ` <div style="border-style:solid;margin:5px;"> <h1>Inner Component</h1> <h2>{{ some_text }}</h2> </div> `})export class GeeksComponent { constructor() {} some_text = "Click Here"; inside = false; @HostListener("click") clicked() { this.inside = true; } @HostListener("document:click") clickedOut() { this.some_text = this.inside ? "Event Triggered" : "Event Triggered Outside Component"; this.inside = false; }}
Output:In this example, if there is a click on the text ‘Outside Component’ then the text shown will be ‘Event Triggered Outside Component’. This shows how the click outside the component will be captured, within the GeeksComponent.
bunnyram19
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to setup 404 page in angular routing ?
How to create module with Routing in Angular 9 ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24610,
"s": 24582,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 24836,
"s": 24610,
"text": "In angular, clicks are detected by different ways. As click is an event, thus inside a component it is detected by simple event binding. A simple click via event binding for detection within the component is given as follows:"
},
{
"code": "@Component({ selector: \"geeks\", template: `<h1 (click)=\"clicked()\">{{ some_text }}</h1> `})export class GeeksComponent { constructor() {} some_text = \"Click Here\"; clicked() { this.some_text = \"Event Triggered\"; }}",
"e": 25061,
"s": 24836,
"text": null
},
{
"code": null,
"e": 25292,
"s": 25061,
"text": "To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs."
},
{
"code": null,
"e": 25701,
"s": 25292,
"text": "Approach: Here the approach is to use @HostListener decorator. In angular, it is a decorator that helps in capturing any kind of event happening inside the DOM and gives the developer flexibility to perform any action based on that event. Here, on the simple click event, the handler will be referring the click event onto the component and for click on allover the DOM, it will capture using document:click."
},
{
"code": null,
"e": 25756,
"s": 25701,
"text": "The syntax for using HostListener is given as follows:"
},
{
"code": null,
"e": 25764,
"s": 25756,
"text": "Syntax:"
},
{
"code": null,
"e": 25833,
"s": 25764,
"text": "@HostListener(events, args)\nhandler_name(args){\n // Do something\n}\n"
},
{
"code": null,
"e": 25895,
"s": 25833,
"text": "There are three things to note in the syntax of HostListener:"
},
{
"code": null,
"e": 26258,
"s": 25895,
"text": "eventName: As the name suggests, this takes in the name of the event in the DOM, that needs to be listened.args: These are set of arguments to pass to the handler method when the event occurs. It takes input in list format.handlen_name: Here comes the method definition that will be called when event is triggered. It is called by the HostListener automatically."
},
{
"code": null,
"e": 26366,
"s": 26258,
"text": "eventName: As the name suggests, this takes in the name of the event in the DOM, that needs to be listened."
},
{
"code": null,
"e": 26483,
"s": 26366,
"text": "args: These are set of arguments to pass to the handler method when the event occurs. It takes input in list format."
},
{
"code": null,
"e": 26623,
"s": 26483,
"text": "handlen_name: Here comes the method definition that will be called when event is triggered. It is called by the HostListener automatically."
},
{
"code": null,
"e": 26835,
"s": 26623,
"text": "Example: Bind with click within component For binding the click within the component, the eventName that will go inside the hostListener will be simply ‘click’. The above code in such a case will be written as :"
},
{
"code": "@Component({ selector: \"geeks\", template: ` <h1>{{ some_text }}</h1> `})export class GeeksComponent { constructor() {} some_text = \"Click Here\"; @HostListener(\"click\") clicked() { this.some_text = \"Event Triggered\"; }}",
"e": 27068,
"s": 26835,
"text": null
},
{
"code": null,
"e": 27076,
"s": 27068,
"text": "Output:"
},
{
"code": null,
"e": 27220,
"s": 27076,
"text": "Here there is no need to pass arguments for the handler to run. the HostListener takes ‘click’ as the event which triggered the method clicked."
},
{
"code": null,
"e": 27864,
"s": 27220,
"text": "Bind with click outside componentFor detection of the click outside the component, another event is to be taken look at. Here the click will not work as it detects click within the component. Here the key will be looking for click within the DOM and not just the component, and thus ‘document:click’ will be the right choice for that and also at the same time we need to filter out the event within the component which is done by the Boolean variable ‘inside’. So in the code given as follows, there will be another component added to is which will act as outside context, but click on that will cause the click event on the current component."
},
{
"code": "@Component({ selector: \"another\", template: ` <div style=\"border-style: solid;margin:5px;\"> <h1>Outside Component</h1> <h2>Click here for outer component trigger</h2> </div> <geeks></geeks> `})export class AnotherComponent { constructor() {}}@Component({ selector: \"geeks\", template: ` <div style=\"border-style:solid;margin:5px;\"> <h1>Inner Component</h1> <h2>{{ some_text }}</h2> </div> `})export class GeeksComponent { constructor() {} some_text = \"Click Here\"; inside = false; @HostListener(\"click\") clicked() { this.inside = true; } @HostListener(\"document:click\") clickedOut() { this.some_text = this.inside ? \"Event Triggered\" : \"Event Triggered Outside Component\"; this.inside = false; }}",
"e": 28630,
"s": 27864,
"text": null
},
{
"code": null,
"e": 28863,
"s": 28630,
"text": "Output:In this example, if there is a click on the text ‘Outside Component’ then the text shown will be ‘Event Triggered Outside Component’. This shows how the click outside the component will be captured, within the GeeksComponent."
},
{
"code": null,
"e": 28874,
"s": 28863,
"text": "bunnyram19"
},
{
"code": null,
"e": 28889,
"s": 28874,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 28896,
"s": 28889,
"text": "Picked"
},
{
"code": null,
"e": 28906,
"s": 28896,
"text": "AngularJS"
},
{
"code": null,
"e": 28923,
"s": 28906,
"text": "Web Technologies"
},
{
"code": null,
"e": 29021,
"s": 28923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29030,
"s": 29021,
"text": "Comments"
},
{
"code": null,
"e": 29043,
"s": 29030,
"text": "Old Comments"
},
{
"code": null,
"e": 29078,
"s": 29043,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29131,
"s": 29078,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29155,
"s": 29131,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29198,
"s": 29155,
"text": "How to setup 404 page in angular routing ?"
},
{
"code": null,
"e": 29247,
"s": 29198,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 29303,
"s": 29247,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29336,
"s": 29303,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29398,
"s": 29336,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29441,
"s": 29398,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
ASP.NET MVC - Caching
|
In this chapter, we will be focusing on one of the most common ASP.NET techniques like Caching to improve the performance of the application. Caching means to store something in memory that is being used frequently to provide better performance. We will see how you can dramatically improve the performance of an ASP.NET MVC application by taking advantage of the output cache.
In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action.
Output caching basically allows you to store the output of a particular controller in the memory. Hence, any future request coming for the same action in that controller will be returned from the cached result. That way, the same content does not need to be generated each and every time the same controller action is invoked.
We need caching in many different scenarios to improve the performance of an application. For example, you have an ASP.NET MVC application, which displays a list employees. Now when these records are retrieved from the database by executing a database query each and every time a user invokes the controller action it returns the Index view.
Hence you can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action.
Caching enables you to avoid performing redundant work on the server.
Let’s take a look at a simple example of caching in our project.
[OutputCache(Duration = 60)]
public ActionResult Index(){
var employees = from e in db.Employees
orderby e.ID
select e;
return View(employees);
}
As you can see, we have added “OutputCache” attribute on the index action of the EmployeeController. Now to understand this concept, let us run this application in debugger mode and also insert a breakpoint in the Index action method.
Specify the following URL http://localhost:63004/employee, and press ‘Enter’. You will see that the breakpoint is hit in the Index action method.
Press ‘F5’ button to continue and you will see the list of employees on your view, which are retrieved from the database.
Refresh the browser again within 60 seconds and you will see that the breakpoint is not hit this time. This is because we have used output cache with duration of seconds. So it will cache this result for 60 seconds and when you refresh the browser, it will get the result from the cache, and it won’t load the content from the database server.
In addition to duration parameter, there are other settings options as well which you can use with output cache. These settings are not only for MVC framework but it is inherited from ASP.Net Caching.
In some cases, you might want different cached versions, such as, when you create a detail page, then when you click on the detailed link you will get details for the selected employee.
But first we need to create the detail view. For this, right-click on the Details action method from the EmployeeController and select Add View...
You will see the Details name is selected by default. Now select Details from the Template dropdown and Employee from the Model class dropdown.
Click ‘Add’ to continue and you will see the Details.cshtml.
@model MVCSimpleApp.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Details</title>
</head>
<body>
<div>
<h4>Employee</h4>
<hr />
<dl class = "dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.JoiningDate)
</dt>
<dd>
@Html.DisplayFor(model => model.JoiningDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Age)
</dt>
<dd>
@Html.DisplayFor(model => model.Age)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>
You can take advantage of the VaryByParam property of the [OutputCache] attribute. This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies. Following is the implementation of Details action.
// GET: Employee/Details/5
[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public ActionResult Details(int id){
var employee = db.Employees.SingleOrDefault(e => e.ID == id);
return View(employee);
}
When the above code is compiled and executed, you will receive the following output by specifying the URL http://localhost:63004/employee.
Click on the Details link of any link and you will see the details view of that particular employee.
The Details() action includes a VaryByParam property with the value “Id”. When different values of the Id parameter are passed to the controller action, different cached versions of the Details view are generated.
It is important to understand that using the VaryByParam property results in more caching. A different cached version of the Details view is created for each different version of the Id parameter.
You can create a cache profile in the web.config file. It is an alternative to configuring output cache properties by modifying properties of the [OutputCache] attribute. It offers a couple of important advantages which are as follows.
Controls how controller actions cache content in one central location.
Controls how controller actions cache content in one central location.
Creates one cache profile and apply the profile to several controllers or controller actions.
Creates one cache profile and apply the profile to several controllers or controller actions.
Modifies the web configuration file without recompiling your application.
Modifies the web configuration file without recompiling your application.
Disables caching for an application that has already been deployed to production.
Disables caching for an application that has already been deployed to production.
Let’s take a look at a simple example of cache profile by creating the cache profile in web.config file. The <caching> section must appear within the <system.web> section.
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name = "Cache10Min" duration = "600" varyByParam = "none"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
You can apply the Cache10Min profile to a controller action with the [OutputCache] attribute which is as follows.
[OutputCache(CacheProfile = "Cache10Min")]
public ActionResult Index(){
var employees = from e in db.Employees
orderby e.ID
select e;
return View(employees);
}
Run this application and specify the following URL http://localhost:63004/employee
If you invoke the Index() action as shown above then the same time will be returned for 10 Min.
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": 2647,
"s": 2269,
"text": "In this chapter, we will be focusing on one of the most common ASP.NET techniques like Caching to improve the performance of the application. Caching means to store something in memory that is being used frequently to provide better performance. We will see how you can dramatically improve the performance of an ASP.NET MVC application by taking advantage of the output cache."
},
{
"code": null,
"e": 2867,
"s": 2647,
"text": "In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action."
},
{
"code": null,
"e": 3194,
"s": 2867,
"text": "Output caching basically allows you to store the output of a particular controller in the memory. Hence, any future request coming for the same action in that controller will be returned from the cached result. That way, the same content does not need to be generated each and every time the same controller action is invoked."
},
{
"code": null,
"e": 3536,
"s": 3194,
"text": "We need caching in many different scenarios to improve the performance of an application. For example, you have an ASP.NET MVC application, which displays a list employees. Now when these records are retrieved from the database by executing a database query each and every time a user invokes the controller action it returns the Index view."
},
{
"code": null,
"e": 3788,
"s": 3536,
"text": "Hence you can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action."
},
{
"code": null,
"e": 3858,
"s": 3788,
"text": "Caching enables you to avoid performing redundant work on the server."
},
{
"code": null,
"e": 3923,
"s": 3858,
"text": "Let’s take a look at a simple example of caching in our project."
},
{
"code": null,
"e": 4081,
"s": 3923,
"text": "[OutputCache(Duration = 60)]\npublic ActionResult Index(){\n var employees = from e in db.Employees\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 4316,
"s": 4081,
"text": "As you can see, we have added “OutputCache” attribute on the index action of the EmployeeController. Now to understand this concept, let us run this application in debugger mode and also insert a breakpoint in the Index action method."
},
{
"code": null,
"e": 4462,
"s": 4316,
"text": "Specify the following URL http://localhost:63004/employee, and press ‘Enter’. You will see that the breakpoint is hit in the Index action method."
},
{
"code": null,
"e": 4584,
"s": 4462,
"text": "Press ‘F5’ button to continue and you will see the list of employees on your view, which are retrieved from the database."
},
{
"code": null,
"e": 4928,
"s": 4584,
"text": "Refresh the browser again within 60 seconds and you will see that the breakpoint is not hit this time. This is because we have used output cache with duration of seconds. So it will cache this result for 60 seconds and when you refresh the browser, it will get the result from the cache, and it won’t load the content from the database server."
},
{
"code": null,
"e": 5129,
"s": 4928,
"text": "In addition to duration parameter, there are other settings options as well which you can use with output cache. These settings are not only for MVC framework but it is inherited from ASP.Net Caching."
},
{
"code": null,
"e": 5315,
"s": 5129,
"text": "In some cases, you might want different cached versions, such as, when you create a detail page, then when you click on the detailed link you will get details for the selected employee."
},
{
"code": null,
"e": 5462,
"s": 5315,
"text": "But first we need to create the detail view. For this, right-click on the Details action method from the EmployeeController and select Add View..."
},
{
"code": null,
"e": 5606,
"s": 5462,
"text": "You will see the Details name is selected by default. Now select Details from the Template dropdown and Employee from the Model class dropdown."
},
{
"code": null,
"e": 5667,
"s": 5606,
"text": "Click ‘Add’ to continue and you will see the Details.cshtml."
},
{
"code": null,
"e": 6745,
"s": 5667,
"text": "@model MVCSimpleApp.Models.Employee\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Details</title>\n </head>\n\t\n <body>\n <div>\n <h4>Employee</h4>\n <hr />\n <dl class = \"dl-horizontal\">\n <dt>\n @Html.DisplayNameFor(model => model.Name)\n </dt>\n\t\t\t\t\n <dd>\n @Html.DisplayFor(model => model.Name)\n </dd>\n\t\t\t\t\n <dt>\n @Html.DisplayNameFor(model => model.JoiningDate)\n </dt>\n\t\t\t\t\n <dd>\n @Html.DisplayFor(model => model.JoiningDate)\n </dd>\n\t\t\t\t\n <dt>\n @Html.DisplayNameFor(model => model.Age)\n </dt>\n\t\t\t\t\n <dd>\n @Html.DisplayFor(model => model.Age)\n </dd>\n\t\t\t\t\n </dl>\n </div>\n\t\t\n <p>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = Model.ID }) |\n @Html.ActionLink(\"Back to List\", \"Index\")\n </p>\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 7022,
"s": 6745,
"text": "You can take advantage of the VaryByParam property of the [OutputCache] attribute. This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies. Following is the implementation of Details action."
},
{
"code": null,
"e": 7239,
"s": 7022,
"text": "// GET: Employee/Details/5\n[OutputCache(Duration = int.MaxValue, VaryByParam = \"id\")]\n\npublic ActionResult Details(int id){\n var employee = db.Employees.SingleOrDefault(e => e.ID == id);\n return View(employee);\n}"
},
{
"code": null,
"e": 7378,
"s": 7239,
"text": "When the above code is compiled and executed, you will receive the following output by specifying the URL http://localhost:63004/employee."
},
{
"code": null,
"e": 7479,
"s": 7378,
"text": "Click on the Details link of any link and you will see the details view of that particular employee."
},
{
"code": null,
"e": 7693,
"s": 7479,
"text": "The Details() action includes a VaryByParam property with the value “Id”. When different values of the Id parameter are passed to the controller action, different cached versions of the Details view are generated."
},
{
"code": null,
"e": 7890,
"s": 7693,
"text": "It is important to understand that using the VaryByParam property results in more caching. A different cached version of the Details view is created for each different version of the Id parameter."
},
{
"code": null,
"e": 8126,
"s": 7890,
"text": "You can create a cache profile in the web.config file. It is an alternative to configuring output cache properties by modifying properties of the [OutputCache] attribute. It offers a couple of important advantages which are as follows."
},
{
"code": null,
"e": 8197,
"s": 8126,
"text": "Controls how controller actions cache content in one central location."
},
{
"code": null,
"e": 8268,
"s": 8197,
"text": "Controls how controller actions cache content in one central location."
},
{
"code": null,
"e": 8362,
"s": 8268,
"text": "Creates one cache profile and apply the profile to several controllers or controller actions."
},
{
"code": null,
"e": 8456,
"s": 8362,
"text": "Creates one cache profile and apply the profile to several controllers or controller actions."
},
{
"code": null,
"e": 8530,
"s": 8456,
"text": "Modifies the web configuration file without recompiling your application."
},
{
"code": null,
"e": 8604,
"s": 8530,
"text": "Modifies the web configuration file without recompiling your application."
},
{
"code": null,
"e": 8686,
"s": 8604,
"text": "Disables caching for an application that has already been deployed to production."
},
{
"code": null,
"e": 8768,
"s": 8686,
"text": "Disables caching for an application that has already been deployed to production."
},
{
"code": null,
"e": 8940,
"s": 8768,
"text": "Let’s take a look at a simple example of cache profile by creating the cache profile in web.config file. The <caching> section must appear within the <system.web> section."
},
{
"code": null,
"e": 9143,
"s": 8940,
"text": "<caching>\n <outputCacheSettings>\n <outputCacheProfiles>\n <add name = \"Cache10Min\" duration = \"600\" varyByParam = \"none\"/>\n </outputCacheProfiles>\n </outputCacheSettings>\n</caching>"
},
{
"code": null,
"e": 9257,
"s": 9143,
"text": "You can apply the Cache10Min profile to a controller action with the [OutputCache] attribute which is as follows."
},
{
"code": null,
"e": 9430,
"s": 9257,
"text": "[OutputCache(CacheProfile = \"Cache10Min\")]\n\npublic ActionResult Index(){\n var employees = from e in db.Employees\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 9513,
"s": 9430,
"text": "Run this application and specify the following URL http://localhost:63004/employee"
},
{
"code": null,
"e": 9609,
"s": 9513,
"text": "If you invoke the Index() action as shown above then the same time will be returned for 10 Min."
},
{
"code": null,
"e": 9644,
"s": 9609,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9658,
"s": 9644,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9693,
"s": 9658,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9716,
"s": 9693,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 9750,
"s": 9716,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 9770,
"s": 9750,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 9805,
"s": 9770,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9822,
"s": 9805,
"text": " University Code"
},
{
"code": null,
"e": 9857,
"s": 9822,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9874,
"s": 9857,
"text": " University Code"
},
{
"code": null,
"e": 9908,
"s": 9874,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9923,
"s": 9908,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 9930,
"s": 9923,
"text": " Print"
},
{
"code": null,
"e": 9941,
"s": 9930,
"text": " Add Notes"
}
] |
Python | numpy.array_split() method - GeeksforGeeks
|
17 Sep, 2019
With the help of numpy.array_split() method, we can get the splitted array of having different dimensions by using numpy.array_split() method.
Syntax : numpy.array_split()
Return : Return the splitted array of one dimension.
Example #1 :In this example we can see that by using numpy.array_split() method, we are able to split the array in the number of subarrays by passing it as a parameter.
# import numpyimport numpy as np array = np.arange(9) # using numpy.array_split() methodgfg = np.array_split(array, 4) print(gfg)
Output :
[array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
Example #2 :
# import numpyimport numpy as np array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # using numpy.array_split() methodgfg = np.array_split(array, 3) print(gfg)
Output :
[array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]])]
Python numpy-arrayManipulation
Python-numpy
Python
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 24355,
"s": 24212,
"text": "With the help of numpy.array_split() method, we can get the splitted array of having different dimensions by using numpy.array_split() method."
},
{
"code": null,
"e": 24384,
"s": 24355,
"text": "Syntax : numpy.array_split()"
},
{
"code": null,
"e": 24437,
"s": 24384,
"text": "Return : Return the splitted array of one dimension."
},
{
"code": null,
"e": 24606,
"s": 24437,
"text": "Example #1 :In this example we can see that by using numpy.array_split() method, we are able to split the array in the number of subarrays by passing it as a parameter."
},
{
"code": "# import numpyimport numpy as np array = np.arange(9) # using numpy.array_split() methodgfg = np.array_split(array, 4) print(gfg)",
"e": 24739,
"s": 24606,
"text": null
},
{
"code": null,
"e": 24748,
"s": 24739,
"text": "Output :"
},
{
"code": null,
"e": 24812,
"s": 24748,
"text": "[array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]"
},
{
"code": null,
"e": 24825,
"s": 24812,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # using numpy.array_split() methodgfg = np.array_split(array, 3) print(gfg)",
"e": 24995,
"s": 24825,
"text": null
},
{
"code": null,
"e": 25004,
"s": 24995,
"text": "Output :"
},
{
"code": null,
"e": 25065,
"s": 25004,
"text": "[array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]])]"
},
{
"code": null,
"e": 25096,
"s": 25065,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 25109,
"s": 25096,
"text": "Python-numpy"
},
{
"code": null,
"e": 25116,
"s": 25109,
"text": "Python"
},
{
"code": null,
"e": 25214,
"s": 25116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25223,
"s": 25214,
"text": "Comments"
},
{
"code": null,
"e": 25236,
"s": 25223,
"text": "Old Comments"
},
{
"code": null,
"e": 25268,
"s": 25236,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25324,
"s": 25268,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25345,
"s": 25324,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 25384,
"s": 25345,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25426,
"s": 25384,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25453,
"s": 25426,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25484,
"s": 25453,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25526,
"s": 25484,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25562,
"s": 25526,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Android - Phone Calls
|
Android provides Built-in applications for phone calls, in some occasions we may need to make a phone call through our application. This could easily be done by using implicit Intent with appropriate actions. Also, we can use PhoneStateListener and TelephonyManager classes, in order to monitor the changes in some telephony states on the device.
This chapter lists down all the simple steps to create an application which can be used to make a Phone Call. You can use Android Intent to make phone call by calling built-in Phone Call functionality of the Android. Following section explains different parts of our Intent object required to make a call.
You will use ACTION_CALL action to trigger built-in phone call functionality available in Android device. Following is simple syntax to create an intent with ACTION_CALL action
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have option to modify hardcoded phone number before making a call instead of making a direct call.
To make a phone call at a given number 91-000-000-0000, you need to specify tel: as URI using setData() method as follows −
phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
The interesting point is that, to make a phone call, you do not need to specify any extra data or data type.
Following example shows you in practical how to use Android Intent to make phone call to the given mobile number.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.saira_000.myapplication;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonCall);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 0377778888" />
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.saira_000.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar.Select your mobile device as an option and then check your mobile device which will display following screen −
Now use Call button to make phone call as shown below −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3954,
"s": 3607,
"text": "Android provides Built-in applications for phone calls, in some occasions we may need to make a phone call through our application. This could easily be done by using implicit Intent with appropriate actions. Also, we can use PhoneStateListener and TelephonyManager classes, in order to monitor the changes in some telephony states on the device."
},
{
"code": null,
"e": 4260,
"s": 3954,
"text": "This chapter lists down all the simple steps to create an application which can be used to make a Phone Call. You can use Android Intent to make phone call by calling built-in Phone Call functionality of the Android. Following section explains different parts of our Intent object required to make a call."
},
{
"code": null,
"e": 4437,
"s": 4260,
"text": "You will use ACTION_CALL action to trigger built-in phone call functionality available in Android device. Following is simple syntax to create an intent with ACTION_CALL action"
},
{
"code": null,
"e": 4490,
"s": 4437,
"text": "Intent phoneIntent = new Intent(Intent.ACTION_CALL);"
},
{
"code": null,
"e": 4666,
"s": 4490,
"text": "You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have option to modify hardcoded phone number before making a call instead of making a direct call."
},
{
"code": null,
"e": 4790,
"s": 4666,
"text": "To make a phone call at a given number 91-000-000-0000, you need to specify tel: as URI using setData() method as follows −"
},
{
"code": null,
"e": 4845,
"s": 4790,
"text": "phoneIntent.setData(Uri.parse(\"tel:91-000-000-0000\"));"
},
{
"code": null,
"e": 4954,
"s": 4845,
"text": "The interesting point is that, to make a phone call, you do not need to specify any extra data or data type."
},
{
"code": null,
"e": 5068,
"s": 4954,
"text": "Following example shows you in practical how to use Android Intent to make phone call to the given mobile number."
},
{
"code": null,
"e": 5151,
"s": 5068,
"text": "Following is the content of the modified main activity file src/MainActivity.java."
},
{
"code": null,
"e": 6297,
"s": 5151,
"text": "package com.example.saira_000.myapplication;\n\nimport android.Manifest;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\n\npublic class MainActivity extends AppCompatActivity {\n private Button button;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = (Button) findViewById(R.id.buttonCall);\n\t\t\n button.setOnClickListener(new View.OnClickListener() {\n public void onClick(View arg0) {\n Intent callIntent = new Intent(Intent.ACTION_CALL);\n callIntent.setData(Uri.parse(\"tel:0377778888\"));\n\t\t\t\t\n if (ActivityCompat.checkSelfPermission(MainActivity.this,\n Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n startActivity(callIntent);\n }\n });\n\n }\n}"
},
{
"code": null,
"e": 6366,
"s": 6297,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 6780,
"s": 6366,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\" >\n\n <Button\n android:id=\"@+id/buttonCall\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"call 0377778888\" />\n\n</LinearLayout>"
},
{
"code": null,
"e": 6866,
"s": 6780,
"text": "Following will be the content of res/values/strings.xml to define two new constants −"
},
{
"code": null,
"e": 6981,
"s": 6866,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 7039,
"s": 6981,
"text": "Following is the default content of AndroidManifest.xml −"
},
{
"code": null,
"e": 7843,
"s": 7039,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.saira_000.myapplication\" >\n \n <uses-permission android:name=\"android.permission.CALL_PHONE\" />\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.saira_000.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 8201,
"s": 7843,
"text": "Let's try to run your My Application application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar.Select your mobile device as an option and then check your mobile device which will display following screen −"
},
{
"code": null,
"e": 8259,
"s": 8201,
"text": "Now use Call button to make phone call as shown below −"
},
{
"code": null,
"e": 8294,
"s": 8259,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8306,
"s": 8294,
"text": " Aditya Dua"
},
{
"code": null,
"e": 8341,
"s": 8306,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8355,
"s": 8341,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 8387,
"s": 8355,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8404,
"s": 8387,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8439,
"s": 8404,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8456,
"s": 8439,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8491,
"s": 8456,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8508,
"s": 8491,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8541,
"s": 8508,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8558,
"s": 8541,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8565,
"s": 8558,
"text": " Print"
},
{
"code": null,
"e": 8576,
"s": 8565,
"text": " Add Notes"
}
] |
A Simple Way to Optimize “Something” in Python | by George Wong | Towards Data Science
|
Why is optimizing a budget important? It allows us to control ads spending, determine how much to spend and maximize desired outcome (visits, clicks etc). As an example, given a budget of $10,000 and its constraints, we are able to determine what is the optimal budget allocation for each marketing channel such that we maximize the outcome. It would allow us to avoid crowding on a single channel where we put everything into a single basket but spreading it out to best performing channels.
A quality budget optimization strategy can significantly improve the effectiveness of search advertising campaigns, thus helping advertisers to succeed in the fierce competition of online marketing.
Linear programming (LP) is one of the most widely used optimization technique to obtain the best outcome. An excerpt from the book “Linear and Nonlinear Programming” by David G. Luenberger:
A linear programming problem is characterized, as the name implies, by linear functions of the unknowns; the objective is linear in the unknowns, and the constraints are linear equalities or linear inequalities in the unknowns.
It seems that the popularity of linear programming lies primarily with the formulation phase of analysis rather than the solution phase — and for good cause. Thus, for the problem that we are about today, it can be formulated as:
A budget constraint restricting the total amount of money to be allocated among three different channels (TV, Radio, Newspaper), the budget constraint takes the form x1 + x2 + x3 ≤ B, where B is the budget. The total spend for TV should be less than $200, Radio should be less than $500 and Newspaper should be less than $500. While total budget is capped at $1000.
Aside from that, we should also find out the objective function for a problem where we plan to maximize or minimize our preferred outcome (click, sales etc).
I’ll be using an open-source advertising dataset from Kaggle to show you how it works!
Ideally, when working with LP, the objective function should be linear by virtue.
If an objective function is not purely linear by virtue of its inherent definition, it is often far easier to define it as being linear than to decide on some other functional form and convince others that the more complex form is the best possible choice. Linearity, therefore, by virtue of its simplicity, often is selected as the easy way out or, when seeking generality, as the only functional form that will be equally applicable (or nonapplicable) in a class of similar problems — David G.Luenberger
We start off by building a multivariate linear regression model using SK-Learn’s linear regression. This kernel provided a great way to validate whether linear regression can be used as linear regression is bounded by several assumptions.
### SCIKIT-LEARN ###feature_cols = ['TV', 'Radio', 'Newspaper']X = df_advertising[feature_cols]y = df_advertising[["Sales"]]# instantiate and fitlr = LinearRegression()model = lr.fit(X, y)# print the coefficientsprint(SkLearn_result.intercept_)print(SkLearn_result.coef_)
We are able to obtain the y-intercept and coefficients from our given model.
With a RMSE of 1.509, our model is pretty accurate and based on the diagram above, we are able to see that it can predict relatively well as compared to the actual value. With the prediction model in place, we can now move towards building our objective function for linear programming.
We will be using a python packaged called PuLP. It is a optimization package for Python. PuLP is straight-forward and very easy to be used!
prob = LpProblem("Ads Sales Problem", LpMaximize)
We start off by defining the problem using LpProblem function where we wanted to maximize the output thus “LpMaximize” would be the parameter. Then we would specify our constraints such as how much we budget should be spent for a given channel.
#TV <= 200x = LpVariable("x", 0, 200)#Radio <= 500y = LpVariable("y", 0, 500)#Newspaper <= 500z = LpVariable("z", 0, 500)#Should be less than $1000prob += x + y + z <= 1000
With the constraints in place, we can now build our objective function using the coefficients given by the model:
coef = model.coef_prob += coef.item(0) * x + coef.item(1) * y + coef.item(2) * z + model.intercept_[0]
Then by calling the solve() function, it will solve it for us and we can also check the status of our optimization. By printing it, we can obtain the below result.
prob.solve()LpStatus[status]
Just using a simple for-loop to access the prob.variables, we are able to obtain the optimal value for each variable and also the maximum objective value below.
for v in prob.variables(): print(v.name, "=", v.varValue)print("Objective = %f" % (prob.objective.value()))
Now we know how much should we spend per marketing channel, we should definitely use it as a baseline model to allocate our budgets for our next marketing campaign. We can actually automate the entire process where the budget can be allocated or optimized throughout each day for a single campaign.
Linear programming for optimization is powerful when it can be applied to the right use-case as it provides key managerial insights. Advertisers usually take the budget as simple constraints and put a lot of efforts to find more effective ways for possible operations as defined by various kinds of markets. A simple strategy for budget allocation and adjustment can significantly minimize the loss in terms of effective clicks/revenue/sales in campaign management.
Linear and Non-linear programming https://www.springer.com/gp/book/9780387745022PuLP — http://coin-or.github.io/pulp/Repository for this tutorial — https://github.com/georgeblu1/Data-Projects/blob/master/Budget%20Optimization.ipynbhttps://towardsdatascience.com/linear-programming-and-discrete-optimization-with-python-using-pulp-449f3c5f6e99
Linear and Non-linear programming https://www.springer.com/gp/book/9780387745022
PuLP — http://coin-or.github.io/pulp/
Repository for this tutorial — https://github.com/georgeblu1/Data-Projects/blob/master/Budget%20Optimization.ipynb
https://towardsdatascience.com/linear-programming-and-discrete-optimization-with-python-using-pulp-449f3c5f6e99
https://www.researchgate.net/figure/Graphical-solution-of-a-linear-programming-problem_fig1_2420905https://link.springer.com/book/10.1007/978-0-387-74503-9http://coin-or.github.io/pulp/
https://www.researchgate.net/figure/Graphical-solution-of-a-linear-programming-problem_fig1_2420905
https://link.springer.com/book/10.1007/978-0-387-74503-9
http://coin-or.github.io/pulp/
Feel free to reach out to me if you have any questions or feedback for me through my LinkedIn. Quick introduction, I am a data scientist at Airasia.com, focused on building great products and driving growth because I just love doing what I do.
|
[
{
"code": null,
"e": 664,
"s": 171,
"text": "Why is optimizing a budget important? It allows us to control ads spending, determine how much to spend and maximize desired outcome (visits, clicks etc). As an example, given a budget of $10,000 and its constraints, we are able to determine what is the optimal budget allocation for each marketing channel such that we maximize the outcome. It would allow us to avoid crowding on a single channel where we put everything into a single basket but spreading it out to best performing channels."
},
{
"code": null,
"e": 863,
"s": 664,
"text": "A quality budget optimization strategy can significantly improve the effectiveness of search advertising campaigns, thus helping advertisers to succeed in the fierce competition of online marketing."
},
{
"code": null,
"e": 1053,
"s": 863,
"text": "Linear programming (LP) is one of the most widely used optimization technique to obtain the best outcome. An excerpt from the book “Linear and Nonlinear Programming” by David G. Luenberger:"
},
{
"code": null,
"e": 1281,
"s": 1053,
"text": "A linear programming problem is characterized, as the name implies, by linear functions of the unknowns; the objective is linear in the unknowns, and the constraints are linear equalities or linear inequalities in the unknowns."
},
{
"code": null,
"e": 1511,
"s": 1281,
"text": "It seems that the popularity of linear programming lies primarily with the formulation phase of analysis rather than the solution phase — and for good cause. Thus, for the problem that we are about today, it can be formulated as:"
},
{
"code": null,
"e": 1877,
"s": 1511,
"text": "A budget constraint restricting the total amount of money to be allocated among three different channels (TV, Radio, Newspaper), the budget constraint takes the form x1 + x2 + x3 ≤ B, where B is the budget. The total spend for TV should be less than $200, Radio should be less than $500 and Newspaper should be less than $500. While total budget is capped at $1000."
},
{
"code": null,
"e": 2035,
"s": 1877,
"text": "Aside from that, we should also find out the objective function for a problem where we plan to maximize or minimize our preferred outcome (click, sales etc)."
},
{
"code": null,
"e": 2122,
"s": 2035,
"text": "I’ll be using an open-source advertising dataset from Kaggle to show you how it works!"
},
{
"code": null,
"e": 2204,
"s": 2122,
"text": "Ideally, when working with LP, the objective function should be linear by virtue."
},
{
"code": null,
"e": 2710,
"s": 2204,
"text": "If an objective function is not purely linear by virtue of its inherent definition, it is often far easier to define it as being linear than to decide on some other functional form and convince others that the more complex form is the best possible choice. Linearity, therefore, by virtue of its simplicity, often is selected as the easy way out or, when seeking generality, as the only functional form that will be equally applicable (or nonapplicable) in a class of similar problems — David G.Luenberger"
},
{
"code": null,
"e": 2949,
"s": 2710,
"text": "We start off by building a multivariate linear regression model using SK-Learn’s linear regression. This kernel provided a great way to validate whether linear regression can be used as linear regression is bounded by several assumptions."
},
{
"code": null,
"e": 3221,
"s": 2949,
"text": "### SCIKIT-LEARN ###feature_cols = ['TV', 'Radio', 'Newspaper']X = df_advertising[feature_cols]y = df_advertising[[\"Sales\"]]# instantiate and fitlr = LinearRegression()model = lr.fit(X, y)# print the coefficientsprint(SkLearn_result.intercept_)print(SkLearn_result.coef_)"
},
{
"code": null,
"e": 3298,
"s": 3221,
"text": "We are able to obtain the y-intercept and coefficients from our given model."
},
{
"code": null,
"e": 3585,
"s": 3298,
"text": "With a RMSE of 1.509, our model is pretty accurate and based on the diagram above, we are able to see that it can predict relatively well as compared to the actual value. With the prediction model in place, we can now move towards building our objective function for linear programming."
},
{
"code": null,
"e": 3725,
"s": 3585,
"text": "We will be using a python packaged called PuLP. It is a optimization package for Python. PuLP is straight-forward and very easy to be used!"
},
{
"code": null,
"e": 3775,
"s": 3725,
"text": "prob = LpProblem(\"Ads Sales Problem\", LpMaximize)"
},
{
"code": null,
"e": 4020,
"s": 3775,
"text": "We start off by defining the problem using LpProblem function where we wanted to maximize the output thus “LpMaximize” would be the parameter. Then we would specify our constraints such as how much we budget should be spent for a given channel."
},
{
"code": null,
"e": 4193,
"s": 4020,
"text": "#TV <= 200x = LpVariable(\"x\", 0, 200)#Radio <= 500y = LpVariable(\"y\", 0, 500)#Newspaper <= 500z = LpVariable(\"z\", 0, 500)#Should be less than $1000prob += x + y + z <= 1000"
},
{
"code": null,
"e": 4307,
"s": 4193,
"text": "With the constraints in place, we can now build our objective function using the coefficients given by the model:"
},
{
"code": null,
"e": 4410,
"s": 4307,
"text": "coef = model.coef_prob += coef.item(0) * x + coef.item(1) * y + coef.item(2) * z + model.intercept_[0]"
},
{
"code": null,
"e": 4574,
"s": 4410,
"text": "Then by calling the solve() function, it will solve it for us and we can also check the status of our optimization. By printing it, we can obtain the below result."
},
{
"code": null,
"e": 4603,
"s": 4574,
"text": "prob.solve()LpStatus[status]"
},
{
"code": null,
"e": 4764,
"s": 4603,
"text": "Just using a simple for-loop to access the prob.variables, we are able to obtain the optimal value for each variable and also the maximum objective value below."
},
{
"code": null,
"e": 4875,
"s": 4764,
"text": "for v in prob.variables(): print(v.name, \"=\", v.varValue)print(\"Objective = %f\" % (prob.objective.value()))"
},
{
"code": null,
"e": 5174,
"s": 4875,
"text": "Now we know how much should we spend per marketing channel, we should definitely use it as a baseline model to allocate our budgets for our next marketing campaign. We can actually automate the entire process where the budget can be allocated or optimized throughout each day for a single campaign."
},
{
"code": null,
"e": 5640,
"s": 5174,
"text": "Linear programming for optimization is powerful when it can be applied to the right use-case as it provides key managerial insights. Advertisers usually take the budget as simple constraints and put a lot of efforts to find more effective ways for possible operations as defined by various kinds of markets. A simple strategy for budget allocation and adjustment can significantly minimize the loss in terms of effective clicks/revenue/sales in campaign management."
},
{
"code": null,
"e": 5983,
"s": 5640,
"text": "Linear and Non-linear programming https://www.springer.com/gp/book/9780387745022PuLP — http://coin-or.github.io/pulp/Repository for this tutorial — https://github.com/georgeblu1/Data-Projects/blob/master/Budget%20Optimization.ipynbhttps://towardsdatascience.com/linear-programming-and-discrete-optimization-with-python-using-pulp-449f3c5f6e99"
},
{
"code": null,
"e": 6064,
"s": 5983,
"text": "Linear and Non-linear programming https://www.springer.com/gp/book/9780387745022"
},
{
"code": null,
"e": 6102,
"s": 6064,
"text": "PuLP — http://coin-or.github.io/pulp/"
},
{
"code": null,
"e": 6217,
"s": 6102,
"text": "Repository for this tutorial — https://github.com/georgeblu1/Data-Projects/blob/master/Budget%20Optimization.ipynb"
},
{
"code": null,
"e": 6329,
"s": 6217,
"text": "https://towardsdatascience.com/linear-programming-and-discrete-optimization-with-python-using-pulp-449f3c5f6e99"
},
{
"code": null,
"e": 6515,
"s": 6329,
"text": "https://www.researchgate.net/figure/Graphical-solution-of-a-linear-programming-problem_fig1_2420905https://link.springer.com/book/10.1007/978-0-387-74503-9http://coin-or.github.io/pulp/"
},
{
"code": null,
"e": 6615,
"s": 6515,
"text": "https://www.researchgate.net/figure/Graphical-solution-of-a-linear-programming-problem_fig1_2420905"
},
{
"code": null,
"e": 6672,
"s": 6615,
"text": "https://link.springer.com/book/10.1007/978-0-387-74503-9"
},
{
"code": null,
"e": 6703,
"s": 6672,
"text": "http://coin-or.github.io/pulp/"
}
] |
How to convert array to arraylist in android?
|
This example demonstrates How to convert array to arraylist in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<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"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:hint = "Enter Name"
android:layout_height = "wrap_content" />
<LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content">
<Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/refresh"
android:text = "Refresh"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
<ListView
android:id = "@+id/listView"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
</ListView>
</LinearLayout>
In the above code, we have taken name and record number as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
EditText name;
ArrayAdapter arrayAdapter;
ArrayList<String> array_list;
Set set = new HashSet();
private ListView listView;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
array_list = new ArrayList<String>();
array_list.ensureCapacity(20);
name = findViewById(R.id.name);
listView = findViewById(R.id.listView);
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
set.add(name.getText().toString());
array_list.clear();
if (array_list.isEmpty()) {
String[] array = new String[]{"ANDROID", "JSP", "JAVA", "STRUTS", "HADOOP", "JSF"};
ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
array_list.addAll(list);
array_list.addAll(set);
Collections.sort(array_list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
array_list.trimToSize();
arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);
listView.setAdapter(arrayAdapter);
} else {
listView.setVisibility(View.GONE);
}
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
name.setError("Enter NAME");
}
}
});
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, we are inserting array items.
Click here to download the project code
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "This example demonstrates How to convert array to arraylist in android."
},
{
"code": null,
"e": 1263,
"s": 1134,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1328,
"s": 1263,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2478,
"s": 1328,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>"
},
{
"code": null,
"e": 2674,
"s": 2478,
"text": "In the above code, we have taken name and record number as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview."
},
{
"code": null,
"e": 2731,
"s": 2674,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5333,
"s": 2731,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.Set;\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n ArrayAdapter arrayAdapter;\n ArrayList<String> array_list;\n Set set = new HashSet();\n private ListView listView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n array_list = new ArrayList<String>();\n array_list.ensureCapacity(20);\n name = findViewById(R.id.name);\n listView = findViewById(R.id.listView);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n set.add(name.getText().toString());\n array_list.clear();\n if (array_list.isEmpty()) {\n String[] array = new String[]{\"ANDROID\", \"JSP\", \"JAVA\", \"STRUTS\", \"HADOOP\", \"JSF\"};\n ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));\n array_list.addAll(list);\n array_list.addAll(set);\n Collections.sort(array_list, new Comparator<String>() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }\n });\n array_list.trimToSize();\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n } else {\n listView.setVisibility(View.GONE);\n }\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 5680,
"s": 5333,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 5731,
"s": 5680,
"text": "In the above result, we are inserting array items."
},
{
"code": null,
"e": 5771,
"s": 5731,
"text": "Click here to download the project code"
}
] |
How to highlight a row in a table with Java Swing?
|
To highlight a row in a table, you can use the addRowSelectionInterval() method. At first create a table −
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
Add some columns −
tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Text Tutorial");
tableModel.addColumn("Video Tutorial");
tableModel.addColumn("Views");
Now, add rows to the table −
tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});
Highlight a single row by adding interval of rows. Set the same index for both the parameters since we want only a single row to be highlighted −
table.addRowSelectionInterval(4, 4);
The following is an example to highlight a row in JTable −
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
public static void main(String[] argv) throws Exception {
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Text Tutorial");
tableModel.addColumn("Video Tutorial");
tableModel.addColumn("Views");
tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});
tableModel.addRow(new Object[] { "AWS", "No", "Yes", "8900"});
tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "1300"});
tableModel.addRow(new Object[] { "Java", "Yes", "No", "9686"});
tableModel.addRow(new Object[] { "jQuery", "Yes", "Yes", "4500"});
tableModel.addRow(new Object[] { "Python", "Yes", "No", "6789"});
tableModel.addRow(new Object[] { "Scala", "Yes", "No", "3400"});
tableModel.addRow(new Object[] { "Swift", "No", "Yes", "9676"});
table.addRowSelectionInterval(4, 4);
table.setBackground(Color.white);
table.setForeground(Color.BLUE);
Font font = new Font("Verdana", Font.CENTER_BASELINE, 12);
table.setFont(font);
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1169,
"s": 1062,
"text": "To highlight a row in a table, you can use the addRowSelectionInterval() method. At first create a table −"
},
{
"code": null,
"e": 1264,
"s": 1169,
"text": "DefaultTableModel tableModel = new DefaultTableModel();\nJTable table = new JTable(tableModel);"
},
{
"code": null,
"e": 1283,
"s": 1264,
"text": "Add some columns −"
},
{
"code": null,
"e": 1439,
"s": 1283,
"text": "tableModel.addColumn(\"Language/ Technology\");\ntableModel.addColumn(\"Text Tutorial\");\ntableModel.addColumn(\"Video Tutorial\");\ntableModel.addColumn(\"Views\");"
},
{
"code": null,
"e": 1468,
"s": 1439,
"text": "Now, add rows to the table −"
},
{
"code": null,
"e": 1869,
"s": 1468,
"text": "tableModel.addRow(new Object[] { \"NodeJS\", \"No\", \"Yes\", \"2350\"});\ntableModel.addRow(new Object[] { \"MVC\", \"Yes\", \"No\", \"1500\"});\ntableModel.addRow(new Object[] { \"ASP.NET\", \"Yes\", \"Yes\", \"3400\"});\ntableModel.addRow(new Object[] { \"F#\", \"Yes\", \"No\", \"7890\"});\ntableModel.addRow(new Object[] { \"Blockchain\", \"Yes\", \"No\", \"10600\"});\ntableModel.addRow(new Object[] { \"SharePoint\", \"Yes\", \"Yes\", \"4900\"});"
},
{
"code": null,
"e": 2015,
"s": 1869,
"text": "Highlight a single row by adding interval of rows. Set the same index for both the parameters since we want only a single row to be highlighted −"
},
{
"code": null,
"e": 2052,
"s": 2015,
"text": "table.addRowSelectionInterval(4, 4);"
},
{
"code": null,
"e": 2111,
"s": 2052,
"text": "The following is an example to highlight a row in JTable −"
},
{
"code": null,
"e": 3961,
"s": 2111,
"text": "package my;\nimport java.awt.Color;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Language/ Technology\");\n tableModel.addColumn(\"Text Tutorial\");\n tableModel.addColumn(\"Video Tutorial\");\n tableModel.addColumn(\"Views\");\n tableModel.addRow(new Object[] { \"NodeJS\", \"No\", \"Yes\", \"2350\"});\n tableModel.addRow(new Object[] { \"MVC\", \"Yes\", \"No\", \"1500\"});\n tableModel.addRow(new Object[] { \"ASP.NET\", \"Yes\", \"Yes\", \"3400\"});\n tableModel.addRow(new Object[] { \"F#\", \"Yes\", \"No\", \"7890\"});\n tableModel.addRow(new Object[] { \"Blockchain\", \"Yes\", \"No\", \"10600\"});\n tableModel.addRow(new Object[] { \"SharePoint\", \"Yes\", \"Yes\", \"4900\"});\n tableModel.addRow(new Object[] { \"AWS\", \"No\", \"Yes\", \"8900\"});\n tableModel.addRow(new Object[] { \"C#\", \"Yes\", \"Yes\", \"1300\"});\n tableModel.addRow(new Object[] { \"Java\", \"Yes\", \"No\", \"9686\"});\n tableModel.addRow(new Object[] { \"jQuery\", \"Yes\", \"Yes\", \"4500\"});\n tableModel.addRow(new Object[] { \"Python\", \"Yes\", \"No\", \"6789\"});\n tableModel.addRow(new Object[] { \"Scala\", \"Yes\", \"No\", \"3400\"});\n tableModel.addRow(new Object[] { \"Swift\", \"No\", \"Yes\", \"9676\"});\n table.addRowSelectionInterval(4, 4);\n table.setBackground(Color.white);\n table.setForeground(Color.BLUE);\n Font font = new Font(\"Verdana\", Font.CENTER_BASELINE, 12);\n table.setFont(font);\n JFrame frame = new JFrame();\n frame.setSize(600, 400);\n frame.add(new JScrollPane(table));\n frame.setVisible(true);\n }\n}"
}
] |
How to remove the label on the left side in matplotlib.pyplot pie charts?
|
To remove the label on the left side in a matplotlib pie chart, we can take the following steps −
Create lists of hours, activities, and colors.
Create lists of hours, activities, and colors.
Plot a pie chart using pie() method.
Plot a pie chart using pie() method.
To hide the label on the left side in matplotlib, we can use plt.ylabel("") with ablank string.
To hide the label on the left side in matplotlib, we can use plt.ylabel("") with ablank string.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
hours = [8, 1, 11, 4]
activities = ['sleeping', 'exercise', 'studying', 'working']
colors = ["grey", "green", "orange", "blue"]
plt.pie(hours, labels=activities, colors=colors, autopct="%.2f")
plt.ylabel("")
plt.show()
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "To remove the label on the left side in a matplotlib pie chart, we can take the following steps −"
},
{
"code": null,
"e": 1207,
"s": 1160,
"text": "Create lists of hours, activities, and colors."
},
{
"code": null,
"e": 1254,
"s": 1207,
"text": "Create lists of hours, activities, and colors."
},
{
"code": null,
"e": 1291,
"s": 1254,
"text": "Plot a pie chart using pie() method."
},
{
"code": null,
"e": 1328,
"s": 1291,
"text": "Plot a pie chart using pie() method."
},
{
"code": null,
"e": 1424,
"s": 1328,
"text": "To hide the label on the left side in matplotlib, we can use plt.ylabel(\"\") with ablank string."
},
{
"code": null,
"e": 1520,
"s": 1424,
"text": "To hide the label on the left side in matplotlib, we can use plt.ylabel(\"\") with ablank string."
},
{
"code": null,
"e": 1858,
"s": 1520,
"text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nhours = [8, 1, 11, 4]\nactivities = ['sleeping', 'exercise', 'studying', 'working']\ncolors = [\"grey\", \"green\", \"orange\", \"blue\"]\nplt.pie(hours, labels=activities, colors=colors, autopct=\"%.2f\")\nplt.ylabel(\"\")\nplt.show()"
}
] |
Unix / Linux Shell - The while Loop
|
The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
while command
do
Statement(s) to be executed if command is true
done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are executed. If command is false then no statement will be executed and the program will jump to the next line after the done statement.
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
Each time this loop executes, the variable a is checked to see whether it has a value that is less than 10. If the value of a is less than 10, this test condition has an exit status of 0. In this case, the current value of a is displayed and later a is incremented by 1.
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2926,
"s": 2747,
"text": "The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly."
},
{
"code": null,
"e": 2999,
"s": 2926,
"text": "while command\ndo\n Statement(s) to be executed if command is true\ndone\n"
},
{
"code": null,
"e": 3225,
"s": 2999,
"text": "Here the Shell command is evaluated. If the resulting value is true, given statement(s) are executed. If command is false then no statement will be executed and the program will jump to the next line after the done statement."
},
{
"code": null,
"e": 3313,
"s": 3225,
"text": "Here is a simple example that uses the while loop to display the numbers zero to nine −"
},
{
"code": null,
"e": 3387,
"s": 3313,
"text": "#!/bin/sh\n\na=0\n\nwhile [ $a -lt 10 ]\ndo\n echo $a\n a=`expr $a + 1`\ndone"
},
{
"code": null,
"e": 3443,
"s": 3387,
"text": "Upon execution, you will receive the following result −"
},
{
"code": null,
"e": 3464,
"s": 3443,
"text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n"
},
{
"code": null,
"e": 3735,
"s": 3464,
"text": "Each time this loop executes, the variable a is checked to see whether it has a value that is less than 10. If the value of a is less than 10, this test condition has an exit status of 0. In this case, the current value of a is displayed and later a is incremented by 1."
},
{
"code": null,
"e": 3770,
"s": 3735,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 3798,
"s": 3770,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3832,
"s": 3798,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3849,
"s": 3832,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3882,
"s": 3849,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3893,
"s": 3882,
"text": " Pradeep D"
},
{
"code": null,
"e": 3928,
"s": 3893,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3944,
"s": 3928,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 3977,
"s": 3944,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3989,
"s": 3977,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4021,
"s": 3989,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4029,
"s": 4021,
"text": " Uplatz"
},
{
"code": null,
"e": 4036,
"s": 4029,
"text": " Print"
},
{
"code": null,
"e": 4047,
"s": 4036,
"text": " Add Notes"
}
] |
Construct Binary Tree from Parent Array | Practice | GeeksforGeeks
|
Given an array of size N that can be used to represents a tree. The array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of Binary Tree from this array representation.
Note: If two elements have the same parent, the one that appears first in the array will be the left child and the other is the right child.
Example 1:
Input:
N = 7
parent[] = {-1,0,0,1,1,3,5}
Output: 0 1 2 3 4 5 6
Explanation: the tree generated
will have a structure like
0
/ \
1 2
/ \
3 4
/
5
/
6
Example 2:
Input:
N = 3
parent[] = {2, 0, -1}
Output: 2 0 1
Explanation: the tree generated will
have a sturcture like
2
/
0
/
1
Your Task:
You don't need to read input or print anything. The task is to complete the function createTree() which takes 2 arguments parent[] and N and returns the root node of the constructed tree.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 103
0
triloki352 weeks ago
/***** C++ **********/ Node* root = NULL; Node *createTree(int parent[], int N) { unordered_map<int,Node*> mp; // all the nodes of tree are indexs of parent[] // so making all possible nodes and filling it in map for(int i=0;i<N;i++) { Node* temp = new Node(i); mp[i]=temp; } // connecting all nodes for(int i=0;i<N;i++) { // root condition if(parent[i]==-1) { auto it = mp.find(i); root = it->second; } else { // searching for parent of "i" in map auto parent_it = mp.find(parent[i]); Node* parent = parent_it->second; // finding address of node wiht value i in map auto child_it = mp.find(i); Node* child = child_it->second; if(parent->left==NULL) parent->left = child; else parent->right = child; } } return root; }
0
aryanm4682 weeks ago
class Solution{ public: //Function to construct binary tree from parent array. Node *createTree(int parent[], int N) { // Your code here Node *head=NULL; unordered_map<int,Node*> u; for(int i=0; i<N; i++) { Node* curr; if(u.find(i)==u.end()) curr= new Node(i); else { auto it =u.find(i); curr=it->second; } if(parent[i]==-1) { head=curr; } else { if(u.find(parent[i])==u.end()) { Node *dummy= new Node(parent[i]); dummy->left=curr; u[parent[i]]=dummy; } else { auto it =u.find(parent[i]); Node *dummy=it->second; if(dummy->left==NULL) dummy->left=curr; else dummy->right=curr; } } u[i]=curr; } return head; }};
0
amankumar2783 weeks ago
Java Solution:
using ArrayList<Node>
class Solution{ //Function to construct binary tree from parent array. public static Node createTree(int arr[], int n) { //Your code here if(n==0){ Node temp=null; return temp; } ArrayList<Node> list= new ArrayList<>(); for(int i=0;i<n;i++){ Node temp=new Node(i); list.add(temp); } Node root=null; for(int i=0;i<n;i++){ if(arr[i]==-1){ root=list.get(i); continue; } Node temp=list.get(arr[i]); if(temp.left==null){ temp.left=list.get(i); }else{ temp.right=list.get(i); } } return root; } }
0
abrajput15063 weeks ago
vector<int> search(int a[],int n,int data){
vector<int> v(2,-1);
int t = 0;
for(int i=0;i<n;i++)
if(a[i] == data)
v[t++] = i;
return v;
}
Node* helper(int p[],int n,int idx){
if(idx == -1)
return NULL;
Node* node = new Node(idx);
vector<int> v = search(p,n,idx);
node->left = helper(p,n,v[0]);
node->right = helper(p,n,v[1]);
return node;
}
Node *createTree(int parent[], int N)
{
// Your code here
Node* root = NULL;
int idx = -1;
for(int i=0;i<N;i++)
if(parent[i] == -1)
idx = i;
root = helper(parent,N,idx);
return root;
}
0
gujjulassr1 month ago
3.7/5.5
class Solution{ //Function to construct binary tree from parent array. public static Node createTree(int arr[], int N) { //Your code here Node[] a=new Node[N]; Node head=null; for(int i=0;i<arr.length;i++){ if(arr[i]!=-1){ a[i]=new Node(i); }else{ head=new Node(i); a[i]=head; } } for(int i=0;i<N;i++){ if(arr[i]!=-1){ if(a[arr[i]].left==null){ a[arr[i]].left=a[i]; } else if(a[arr[i]].right==null){ a[arr[i]].right=a[i]; } } } return head; } }
0
aniketkumar51 month ago
public static Node root4; public static Node createTree(int parent[], int N) { //Your code here Node[] created = new Node[N]; for(int i=0;i<N;i++){ created[i]=null; } for(int i=0;i<N;i++){ createNode(parent, i, created); } return root4; } public static void createNode(int parent[],int i, Node[] root){ if(root[i]!=null){ return ; } root[i]=new Node(i); if(parent[i]==-1){ root4=root[i]; return ; } if(root[parent[i]]==null){ createNode(parent,parent[i],root); } Node p=root[parent[i]]; if(p.left==null){ p.left = root[i]; } else{ p.right = root[i]; } }
0
salwayhrishikesh2 months ago
public static void createParent(int parent, int value, Node [] nodes){
// adding the current node in the visited list
if(nodes[value] == null)
nodes[value] = new Node(value);
// if current node is the root node then exit out of the function
if (parent == -1)
return;
// creating a node for parent
Node temp = null;
// checking if the parent node has been visited before
temp = nodes[parent] == null ? new Node(parent) : nodes[parent];
nodes[parent] = temp;
// if the parent node has no left child
if (temp.left == null){
temp.left = nodes[value];
}
// if the parent node has no right child
else{
temp.right = nodes[value];
}
}
//Function to construct binary tree from parent array.
public static Node createTree(int parent[], int N)
{
int root = 0;
Node [] nodes = new Node[N];
for (int i = 0; i < N; i ++){
createParent(parent[i], i, nodes);
if (parent[i] == -1)
root = i;
}
return nodes[root];
}
0
sankt2 months ago
Simple JAVA solution:
public static Node createTree(int parent[], int N)
{
Node root = null;
HashMap<Integer, Node> hm = new HashMap<>();
for (int i=0; i<N; i++) {
if (parent[i] == -1) {
root = new Node(i);
hm.put(i, root);
} else {
Node temp = new Node(i);
hm.put(i, temp);
}
}
for (int i=0; i<N; i++) {
if (parent[i] == -1) continue;
Node temp = hm.get(parent[i]);
if (temp.left == null) {
temp.left = hm.get(i);
} else {
temp.right = hm.get(i);
}
}
return root;
}
0
priyanshugupta1231232 months ago
Perfect JAVA Solution :
class Solution
{
//Function to construct binary tree from parent array.
public static Node createTree(int parent[], int N)
{
if(N==0)
return null;
Map<Integer,PairClass> map = new HashMap<>();
Node root = new Node(1);
int i = 0 ;
for(int n : parent){
if(n==-1){
root = new Node(i);
i++;
continue;
}
PairClass pair = map.get(n);
if(pair==null){
pair = new PairClass(i);
}else{
pair.set2(i);
}
map.put(n,pair);
i++;
}
Queue<Node> q = new ArrayDeque<>();
q.add(root);
while(!q.isEmpty()){
Node n = q.remove();
PairClass p;
if(map.get(n.data)!=null)
p = map.get(n.data);
else
continue;
if(p.isFilled){
Node left = new Node(p.val1);
Node right = new Node(p.val2);
n.left = left;
n.right = right;
q.add(left);
q.add(right);
}else{
Node left = new Node(p.val1);
n.left = left;
q.add(left);
}
}
return root;
}
public static void p(int i){
System.out.println(String.valueOf(i));
}
public static void p(String i){
System.out.println(i);
}
}
class PairClass{
int val1, val2;
boolean isFilled = false;
PairClass(int val){
this.val1 = val;
}
public void set2(int val){
isFilled = true;
this.val2 = val;
}
public void printEle(){
if(isFilled)
System.out.println(String.valueOf(val1) + " " + String.valueOf(val2));
else
System.out.println(String.valueOf(val1));
}
}
0
tharunreddy09212 months ago
java solution
class Solution{ //Function to construct binary tree from parent array. public static Node createTree(int parent[], int N) { //Your code here int rn=0; ArrayList<Node> al=new ArrayList<>(); //to find the root element; for(int i=0;i<parent.length;i++) { if(parent[i]==-1) { rn=i; break; } } for(int i=0;i<parent.length;i++) { Node x=new Node(i); al.add(x); } for(int i=0;i<parent.length;i++) { if (i==rn) continue; Node x=al.get(parent[i]); if(x.left==null) x.left=al.get(i); else x.right=al.get(i); } return al.get(rn); } }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 595,
"s": 238,
"text": "Given an array of size N that can be used to represents a tree. The array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of Binary Tree from this array representation."
},
{
"code": null,
"e": 737,
"s": 595,
"text": "Note: If two elements have the same parent, the one that appears first in the array will be the left child and the other is the right child. "
},
{
"code": null,
"e": 749,
"s": 737,
"text": "\nExample 1:"
},
{
"code": null,
"e": 950,
"s": 749,
"text": "Input:\nN = 7\nparent[] = {-1,0,0,1,1,3,5}\nOutput: 0 1 2 3 4 5 6\nExplanation: the tree generated\nwill have a structure like \n 0\n / \\\n 1 2\n / \\\n 3 4\n /\n 5\n /\n6"
},
{
"code": null,
"e": 961,
"s": 950,
"text": "Example 2:"
},
{
"code": null,
"e": 1155,
"s": 961,
"text": "Input:\nN = 3\nparent[] = {2, 0, -1}\nOutput: 2 0 1\nExplanation: the tree generated will\nhave a sturcture like\n 2\n / \n 0 \n / \n 1 "
},
{
"code": null,
"e": 1355,
"s": 1155,
"text": "\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function createTree() which takes 2 arguments parent[] and N and returns the root node of the constructed tree."
},
{
"code": null,
"e": 1418,
"s": 1355,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1444,
"s": 1418,
"text": "\nConstraints:\n1 ≤ N ≤ 103"
},
{
"code": null,
"e": 1446,
"s": 1444,
"text": "0"
},
{
"code": null,
"e": 1467,
"s": 1446,
"text": "triloki352 weeks ago"
},
{
"code": null,
"e": 2589,
"s": 1467,
"text": " /***** C++ **********/ Node* root = NULL; Node *createTree(int parent[], int N) { unordered_map<int,Node*> mp; // all the nodes of tree are indexs of parent[] // so making all possible nodes and filling it in map for(int i=0;i<N;i++) { Node* temp = new Node(i); mp[i]=temp; } // connecting all nodes for(int i=0;i<N;i++) { // root condition if(parent[i]==-1) { auto it = mp.find(i); root = it->second; } else { // searching for parent of \"i\" in map auto parent_it = mp.find(parent[i]); Node* parent = parent_it->second; // finding address of node wiht value i in map auto child_it = mp.find(i); Node* child = child_it->second; if(parent->left==NULL) parent->left = child; else parent->right = child; } } return root; }"
},
{
"code": null,
"e": 2591,
"s": 2589,
"text": "0"
},
{
"code": null,
"e": 2612,
"s": 2591,
"text": "aryanm4682 weeks ago"
},
{
"code": null,
"e": 3720,
"s": 2612,
"text": "class Solution{ public: //Function to construct binary tree from parent array. Node *createTree(int parent[], int N) { // Your code here Node *head=NULL; unordered_map<int,Node*> u; for(int i=0; i<N; i++) { Node* curr; if(u.find(i)==u.end()) curr= new Node(i); else { auto it =u.find(i); curr=it->second; } if(parent[i]==-1) { head=curr; } else { if(u.find(parent[i])==u.end()) { Node *dummy= new Node(parent[i]); dummy->left=curr; u[parent[i]]=dummy; } else { auto it =u.find(parent[i]); Node *dummy=it->second; if(dummy->left==NULL) dummy->left=curr; else dummy->right=curr; } } u[i]=curr; } return head; }};"
},
{
"code": null,
"e": 3722,
"s": 3720,
"text": "0"
},
{
"code": null,
"e": 3746,
"s": 3722,
"text": "amankumar2783 weeks ago"
},
{
"code": null,
"e": 3761,
"s": 3746,
"text": "Java Solution:"
},
{
"code": null,
"e": 3783,
"s": 3761,
"text": "using ArrayList<Node>"
},
{
"code": null,
"e": 4495,
"s": 3785,
"text": "class Solution{ //Function to construct binary tree from parent array. public static Node createTree(int arr[], int n) { //Your code here if(n==0){ Node temp=null; return temp; } ArrayList<Node> list= new ArrayList<>(); for(int i=0;i<n;i++){ Node temp=new Node(i); list.add(temp); } Node root=null; for(int i=0;i<n;i++){ if(arr[i]==-1){ root=list.get(i); continue; } Node temp=list.get(arr[i]); if(temp.left==null){ temp.left=list.get(i); }else{ temp.right=list.get(i); } } return root; } }"
},
{
"code": null,
"e": 4499,
"s": 4497,
"text": "0"
},
{
"code": null,
"e": 4523,
"s": 4499,
"text": "abrajput15063 weeks ago"
},
{
"code": null,
"e": 5296,
"s": 4523,
"text": "vector<int> search(int a[],int n,int data){\n vector<int> v(2,-1);\n int t = 0;\n for(int i=0;i<n;i++)\n if(a[i] == data)\n v[t++] = i;\n return v;\n }\n Node* helper(int p[],int n,int idx){\n if(idx == -1)\n return NULL;\n \n Node* node = new Node(idx);\n vector<int> v = search(p,n,idx);\n \n node->left = helper(p,n,v[0]);\n node->right = helper(p,n,v[1]);\n \n return node;\n }\n Node *createTree(int parent[], int N)\n {\n // Your code here\n Node* root = NULL;\n int idx = -1;\n for(int i=0;i<N;i++)\n if(parent[i] == -1)\n idx = i;\n root = helper(parent,N,idx);\n return root;\n }"
},
{
"code": null,
"e": 5298,
"s": 5296,
"text": "0"
},
{
"code": null,
"e": 5320,
"s": 5298,
"text": "gujjulassr1 month ago"
},
{
"code": null,
"e": 5328,
"s": 5320,
"text": "3.7/5.5"
},
{
"code": null,
"e": 6017,
"s": 5330,
"text": "class Solution{ //Function to construct binary tree from parent array. public static Node createTree(int arr[], int N) { //Your code here Node[] a=new Node[N]; Node head=null; for(int i=0;i<arr.length;i++){ if(arr[i]!=-1){ a[i]=new Node(i); }else{ head=new Node(i); a[i]=head; } } for(int i=0;i<N;i++){ if(arr[i]!=-1){ if(a[arr[i]].left==null){ a[arr[i]].left=a[i]; } else if(a[arr[i]].right==null){ a[arr[i]].right=a[i]; } } } return head; } }"
},
{
"code": null,
"e": 6019,
"s": 6017,
"text": "0"
},
{
"code": null,
"e": 6043,
"s": 6019,
"text": "aniketkumar51 month ago"
},
{
"code": null,
"e": 6845,
"s": 6043,
"text": " public static Node root4; public static Node createTree(int parent[], int N) { //Your code here Node[] created = new Node[N]; for(int i=0;i<N;i++){ created[i]=null; } for(int i=0;i<N;i++){ createNode(parent, i, created); } return root4; } public static void createNode(int parent[],int i, Node[] root){ if(root[i]!=null){ return ; } root[i]=new Node(i); if(parent[i]==-1){ root4=root[i]; return ; } if(root[parent[i]]==null){ createNode(parent,parent[i],root); } Node p=root[parent[i]]; if(p.left==null){ p.left = root[i]; } else{ p.right = root[i]; } }"
},
{
"code": null,
"e": 6847,
"s": 6845,
"text": "0"
},
{
"code": null,
"e": 6876,
"s": 6847,
"text": "salwayhrishikesh2 months ago"
},
{
"code": null,
"e": 8124,
"s": 6876,
"text": "public static void createParent(int parent, int value, Node [] nodes){\n // adding the current node in the visited list\n if(nodes[value] == null)\n nodes[value] = new Node(value);\n \n // if current node is the root node then exit out of the function\n if (parent == -1)\n return;\n \n // creating a node for parent\n Node temp = null;\n \n // checking if the parent node has been visited before\n temp = nodes[parent] == null ? new Node(parent) : nodes[parent];\n nodes[parent] = temp;\n \n // if the parent node has no left child\n if (temp.left == null){\n temp.left = nodes[value];\n }\n \n // if the parent node has no right child\n else{\n temp.right = nodes[value];\n }\n \n }\n \n //Function to construct binary tree from parent array.\n \n public static Node createTree(int parent[], int N)\n {\n int root = 0;\n Node [] nodes = new Node[N];\n \n for (int i = 0; i < N; i ++){\n createParent(parent[i], i, nodes);\n if (parent[i] == -1)\n root = i;\n }\n \n return nodes[root];\n }"
},
{
"code": null,
"e": 8126,
"s": 8124,
"text": "0"
},
{
"code": null,
"e": 8144,
"s": 8126,
"text": "sankt2 months ago"
},
{
"code": null,
"e": 8933,
"s": 8144,
"text": "Simple JAVA solution: \n \n public static Node createTree(int parent[], int N)\n {\n Node root = null;\n \n HashMap<Integer, Node> hm = new HashMap<>();\n \n for (int i=0; i<N; i++) {\n if (parent[i] == -1) {\n root = new Node(i);\n hm.put(i, root);\n } else {\n Node temp = new Node(i);\n hm.put(i, temp); \n }\n }\n \n for (int i=0; i<N; i++) {\n if (parent[i] == -1) continue;\n Node temp = hm.get(parent[i]);\n \n if (temp.left == null) {\n temp.left = hm.get(i);\n } else {\n temp.right = hm.get(i); \n }\n }\n \n return root;\n }"
},
{
"code": null,
"e": 8935,
"s": 8933,
"text": "0"
},
{
"code": null,
"e": 8968,
"s": 8935,
"text": "priyanshugupta1231232 months ago"
},
{
"code": null,
"e": 8992,
"s": 8968,
"text": "Perfect JAVA Solution :"
},
{
"code": null,
"e": 10976,
"s": 8992,
"text": "class Solution\n{\n //Function to construct binary tree from parent array.\n public static Node createTree(int parent[], int N)\n {\n if(N==0)\n return null;\n \n Map<Integer,PairClass> map = new HashMap<>();\n Node root = new Node(1);\n int i = 0 ;\n for(int n : parent){\n if(n==-1){\n root = new Node(i);\n i++;\n continue;\n }\n PairClass pair = map.get(n);\n if(pair==null){\n pair = new PairClass(i);\n }else{\n pair.set2(i);\n }\n map.put(n,pair);\n i++;\n }\n \n Queue<Node> q = new ArrayDeque<>();\n q.add(root);\n \n while(!q.isEmpty()){\n Node n = q.remove();\n PairClass p;\n if(map.get(n.data)!=null)\n p = map.get(n.data);\n else\n continue;\n if(p.isFilled){\n Node left = new Node(p.val1);\n Node right = new Node(p.val2);\n n.left = left;\n n.right = right;\n q.add(left);\n q.add(right);\n }else{\n Node left = new Node(p.val1);\n n.left = left;\n q.add(left);\n } \n }\n return root;\n \n }\n public static void p(int i){\n System.out.println(String.valueOf(i));\n }\n \n public static void p(String i){\n System.out.println(i);\n }\n}\n\nclass PairClass{\n int val1, val2;\n boolean isFilled = false;\n PairClass(int val){\n this.val1 = val;\n }\n public void set2(int val){\n isFilled = true;\n this.val2 = val;\n }\n public void printEle(){\n if(isFilled)\n System.out.println(String.valueOf(val1) + \" \" + String.valueOf(val2));\n else\n System.out.println(String.valueOf(val1));\n } \n}\n"
},
{
"code": null,
"e": 10978,
"s": 10976,
"text": "0"
},
{
"code": null,
"e": 11006,
"s": 10978,
"text": "tharunreddy09212 months ago"
},
{
"code": null,
"e": 11020,
"s": 11006,
"text": "java solution"
},
{
"code": null,
"e": 11806,
"s": 11020,
"text": "class Solution{ //Function to construct binary tree from parent array. public static Node createTree(int parent[], int N) { //Your code here int rn=0; ArrayList<Node> al=new ArrayList<>(); //to find the root element; for(int i=0;i<parent.length;i++) { if(parent[i]==-1) { rn=i; break; } } for(int i=0;i<parent.length;i++) { Node x=new Node(i); al.add(x); } for(int i=0;i<parent.length;i++) { if (i==rn) continue; Node x=al.get(parent[i]); if(x.left==null) x.left=al.get(i); else x.right=al.get(i); } return al.get(rn); } }"
},
{
"code": null,
"e": 11954,
"s": 11808,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 11990,
"s": 11954,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 12000,
"s": 11990,
"text": "\nProblem\n"
},
{
"code": null,
"e": 12010,
"s": 12000,
"text": "\nContest\n"
},
{
"code": null,
"e": 12073,
"s": 12010,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12221,
"s": 12073,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 12429,
"s": 12221,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 12535,
"s": 12429,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Tryit Editor v3.6 - Show Python
|
#the required first parameter of the 'get' method is the 'url':
x = requests.get('https://w3schools.com/python/demopage.htm')
#print the response text (the content of the requested file):
|
[
{
"code": null,
"e": 82,
"s": 18,
"text": "#the required first parameter of the 'get' method is the 'url':"
},
{
"code": null,
"e": 144,
"s": 82,
"text": "x = requests.get('https://w3schools.com/python/demopage.htm')"
},
{
"code": null,
"e": 146,
"s": 144,
"text": ""
}
] |
Python - Extract Symmetric Tuples - GeeksforGeeks
|
10 Jul, 2020
Sometimes while working with Python tuples, we can have a problem in which we need to extract all the pairs which are symmetric, i.e for any (x, y), we have (y, x) pair present. This kind of problem can have application in domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(6, 7), (2, 3), (7, 6)]Output : {(6, 7)}
Input : test_list = [(6, 7), (2, 3)]Output : {}
Method #1 : Using dictionary comprehension + set()The combination of above functionalities can be used to solve this problem. In this, we initially construct reverse pairs, and then compare with original list pairs, and extract one of equals. The set() is used to remove duplicates, to avoid unnecessary computions of elements.
# Python3 code to demonstrate working of # Extract Symmetric Tuples# Using dictionary comprehension + set() # initializing listtest_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)] # printing original listprint("The original list is : " + str(test_list)) # Extract Symmetric Tuples# Using dictionary comprehension + set()temp = set(test_list) & {(b, a) for a, b in test_list}res = {(a, b) for a, b in temp if a < b} # printing result print("The Symmetric tuples : " + str(res))
The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
The Symmetric tuples : {(8, 9), (6, 7)}
Method #2 : Using Counter() + list comprehensionThis is yet another way in which this task can be performed. In this, we follow similar approach of constructing reverse pairs, but here, we count the equal elements, the element with count 2 is duplicate and matches the reversed tuples.
# Python3 code to demonstrate working of # Extract Symmetric Tuples# Using Counter() + list comprehensionfrom collections import Counter # initializing listtest_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)] # printing original listprint("The original list is : " + str(test_list)) # Extract Symmetric Tuples# Using Counter() + list comprehension<temp = [(sub[1], sub[0]) if sub[0] < sub[1] else sub for sub in test_list]cnts = Counter(temp)res = [key for key, val in cnts.items() if val == 2] # printing result print("The Symmetric tuples : " + str(res))
The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
The Symmetric tuples : [(7, 6), (9, 8)]
Python List-of-Tuples
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25881,
"s": 25537,
"text": "Sometimes while working with Python tuples, we can have a problem in which we need to extract all the pairs which are symmetric, i.e for any (x, y), we have (y, x) pair present. This kind of problem can have application in domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 25943,
"s": 25881,
"text": "Input : test_list = [(6, 7), (2, 3), (7, 6)]Output : {(6, 7)}"
},
{
"code": null,
"e": 25991,
"s": 25943,
"text": "Input : test_list = [(6, 7), (2, 3)]Output : {}"
},
{
"code": null,
"e": 26319,
"s": 25991,
"text": "Method #1 : Using dictionary comprehension + set()The combination of above functionalities can be used to solve this problem. In this, we initially construct reverse pairs, and then compare with original list pairs, and extract one of equals. The set() is used to remove duplicates, to avoid unnecessary computions of elements."
},
{
"code": "# Python3 code to demonstrate working of # Extract Symmetric Tuples# Using dictionary comprehension + set() # initializing listtest_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Extract Symmetric Tuples# Using dictionary comprehension + set()temp = set(test_list) & {(b, a) for a, b in test_list}res = {(a, b) for a, b in temp if a < b} # printing result print(\"The Symmetric tuples : \" + str(res)) ",
"e": 26810,
"s": 26319,
"text": null
},
{
"code": null,
"e": 26924,
"s": 26810,
"text": "The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]\nThe Symmetric tuples : {(8, 9), (6, 7)}\n"
},
{
"code": null,
"e": 27212,
"s": 26926,
"text": "Method #2 : Using Counter() + list comprehensionThis is yet another way in which this task can be performed. In this, we follow similar approach of constructing reverse pairs, but here, we count the equal elements, the element with count 2 is duplicate and matches the reversed tuples."
},
{
"code": "# Python3 code to demonstrate working of # Extract Symmetric Tuples# Using Counter() + list comprehensionfrom collections import Counter # initializing listtest_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Extract Symmetric Tuples# Using Counter() + list comprehension<temp = [(sub[1], sub[0]) if sub[0] < sub[1] else sub for sub in test_list]cnts = Counter(temp)res = [key for key, val in cnts.items() if val == 2] # printing result print(\"The Symmetric tuples : \" + str(res)) ",
"e": 27783,
"s": 27212,
"text": null
},
{
"code": null,
"e": 27897,
"s": 27783,
"text": "The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]\nThe Symmetric tuples : [(7, 6), (9, 8)]\n"
},
{
"code": null,
"e": 27919,
"s": 27897,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 27940,
"s": 27919,
"text": "Python list-programs"
},
{
"code": null,
"e": 27962,
"s": 27940,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27969,
"s": 27962,
"text": "Python"
},
{
"code": null,
"e": 27985,
"s": 27969,
"text": "Python Programs"
},
{
"code": null,
"e": 28083,
"s": 27985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28115,
"s": 28083,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28157,
"s": 28115,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28199,
"s": 28157,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28255,
"s": 28199,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28282,
"s": 28255,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28304,
"s": 28282,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28343,
"s": 28304,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28389,
"s": 28343,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28427,
"s": 28389,
"text": "Python | Convert a list to dictionary"
}
] |
How to Remove the First Entry or Last Entry from the Java TreeMap? - GeeksforGeeks
|
15 Nov, 2021
TreeMap is the implementation class of the Map interface. It allows the objects to be sorted according to the keys and sorting can be natural sorting or you can use a comparator. Insertion order is also not preserved in Tree Map.
Syntax:
TreeMap<String,Integer> map = new TreeMap<>();
In the below example we will create one Tree Map and insert records in it using the put() method. As the Tree Map sorts the records on the basis of keys, you can see the output is in the sorted order of keys from a to z. For iterating over the Tree Map we iterate over all the keys of Tree Map using the key Set() method which gives all the keys of Tree Map in a set.
Implementation:
Java
// Java Program to remove the first entry// or last entry from TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and // values of type integer TreeMap<String, Integer> gfg = new TreeMap<>(); // adding values to treemap gfg.put("interviews", 97); gfg.put("fang", 86); gfg.put("competitive programming", 95); gfg.put("dsa", 99); gfg.put("java", 99); gfg.put("c++", 99); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } }}
c++,99
competitive programming,95
dsa,99
fang,86
interviews,97
java,99
Removing the first and last entry from TreeMap:
1. Using pollFirstEntry() and pollLastEntry() methods:
TreeMap has two method which can remove the first and last entry .pollFirstEntry() for removing the first entry and for last entry we use pollLastEntry().
Syntax:
mapObject.pollFirstEntry();
mapObject.pollLastEntry();
Return Type: The return type of both the method is entry object removed from the map.
First, we will create a TreeMap and add records in it using the put() method and then print all the records using for each loop. For printing, we will use all the keys which we can get using the keySet() method. Now we will use pollFirstEntry() and pollLastEntry() on TreeMap to remove first and last entry. After removing the first and last entry we again will iterate over the TreeMap using the for each loop.
Implementation:
Java
// Java Program remove the first entry// or last entry from the TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and values of type // integer TreeMap<String, Integer> gfg = new TreeMap<>(); // adding values to tree map gfg.put("Interviews", 97); gfg.put("fang", 86); gfg.put("competitive programming", 95); gfg.put("dsa", 99); gfg.put("java", 99); gfg.put("c++", 99); System.out.println( "-------before removing first and last entry-------"); // iterating over the treemap in java for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } // removing and printing first entry System.out.println( "----printing the first removed entry----"); System.out.println(gfg.pollFirstEntry()); // removing and printing last entry System.out.println( "----printing the last removed entry"); System.out.println(gfg.pollLastEntry()); System.out.println( "-------after removing first and last entry-------"); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } }}
-------before removing first and last entry-------
Interviews,97
c++,99
competitive programming,95
dsa,99
fang,86
java,99
----printing the first removed entry----
Interviews=97
----printing the last removed entry
java=99
-------after removing first and last entry-------
c++,99
competitive programming,95
dsa,99
fang,86
2. Using lastKey() and firstKey():
Syntax:
map.remove(map.lastKey());
map.remove(map.firstKey());
Approach:
First, we will create the TreeMap and inserts a record in it using a put() method. Now we will print all the records using for each loop and the output will be in the sorting order of keys from a to z. For removing the first entry and last entry we will use the remove(key) method. In the remove method, we need to pass the key as an argument. Now if we somehow get the first and last key we will be able to remove the first and last entry. TreeMap gives us two such methods which can give us first and the last key which is firstKey() and lastkey(), after getting the keys we will pass these keys in the remove() method and then again print the values present in treemap using for each loop.
Implementation:
Java
// Java Program to remove the first entry// or last entry from the TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and values of type // integer TreeMap<String, Integer> gfg = new TreeMap<>(); gfg.put("Interviews", 97); gfg.put("fang", 86); gfg.put("competitive programming", 95); gfg.put("dsa", 99); gfg.put("java", 99); gfg.put("c++", 99); // iterating over the treemap in java System.out.println( "-------before removing first and last entry-------"); for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } // removing first entry through firstKey() gfg.remove(gfg.firstKey()); // removing last entry through lastKey() gfg.remove(gfg.lastKey()); System.out.println( "-------after removing first and last entry-------"); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } }}
-------before removing first and last entry-------
Interviews,97
c++,99
competitive programming,95
dsa,99
fang,86
java,99
-------after removing first and last entry-------
c++,99
competitive programming,95
dsa,99
fang,86
3. Using Streams():
Here we will get the first and last key using streams then call the remove method on it.
Syntax:
firsrkey = map.entrySet().stream().findFirst().get()
treemap.remove(firstkey);
lastkey = map.entrySet().stream().skip(map.size()-1).findFirst().get()
treemap.remove(key);
Approach:
Here we will create a TreeMap and add records in it using the put() method and then print every record using for each loop. Now we will use streams for getting the first and last key. For the first key, we will get a set of all the keys using the keySet() method and then we will use the stream() on it, now for getting the first item(a record) from the stream we will use findFirst() and get() on it to get the first key then pass this in remove method to remove first entry(a record).
For the last Key, we will again use keySet() for all the keys and after it stream(), Now we will skip the n-1 elements because if we skip the first n-1 records then ultimately we will arrive at the last record. For getting the n( number of total records or size of the TreeMap) we use the size() method.
Implementation:
Java
// Java Program remove the first entry// or last entry from the TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and values of type // integer TreeMap<String, Integer> gfg = new TreeMap<>(); gfg.put("Interviews", 97); gfg.put("fang", 86); gfg.put("competitive programming", 95); gfg.put("dsa", 99); gfg.put("java", 99); gfg.put("c++", 99); // iterating over the treemap in java System.out.println( "-------before removing first and last entry-------"); for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } // removing first entry through firstKey() String firstKey = gfg.keySet().stream().findFirst().get(); gfg.remove(firstKey); // removing last entry through lastKey() String lastKey = gfg.keySet() .stream() .skip(gfg.size() - 1) .findFirst() .get(); gfg.remove(lastKey); System.out.println( "-------after removing first and last entry-------"); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + "," + gfg.get(key)); } }}
-------before removing first and last entry-------
Interviews,97
c++,99
competitive programming,95
dsa,99
fang,86
java,99
-------after removing first and last entry-------
c++,99
competitive programming,95
dsa,99
fang,86
simmytarika5
anikaseth98
java-TreeMap
Picked
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 25455,
"s": 25225,
"text": "TreeMap is the implementation class of the Map interface. It allows the objects to be sorted according to the keys and sorting can be natural sorting or you can use a comparator. Insertion order is also not preserved in Tree Map."
},
{
"code": null,
"e": 25463,
"s": 25455,
"text": "Syntax:"
},
{
"code": null,
"e": 25510,
"s": 25463,
"text": "TreeMap<String,Integer> map = new TreeMap<>();"
},
{
"code": null,
"e": 25878,
"s": 25510,
"text": "In the below example we will create one Tree Map and insert records in it using the put() method. As the Tree Map sorts the records on the basis of keys, you can see the output is in the sorted order of keys from a to z. For iterating over the Tree Map we iterate over all the keys of Tree Map using the key Set() method which gives all the keys of Tree Map in a set."
},
{
"code": null,
"e": 25894,
"s": 25878,
"text": "Implementation:"
},
{
"code": null,
"e": 25899,
"s": 25894,
"text": "Java"
},
{
"code": "// Java Program to remove the first entry// or last entry from TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and // values of type integer TreeMap<String, Integer> gfg = new TreeMap<>(); // adding values to treemap gfg.put(\"interviews\", 97); gfg.put(\"fang\", 86); gfg.put(\"competitive programming\", 95); gfg.put(\"dsa\", 99); gfg.put(\"java\", 99); gfg.put(\"c++\", 99); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } }}",
"e": 26602,
"s": 25899,
"text": null
},
{
"code": null,
"e": 26673,
"s": 26602,
"text": "c++,99\ncompetitive programming,95\ndsa,99\nfang,86\ninterviews,97\njava,99"
},
{
"code": null,
"e": 26724,
"s": 26676,
"text": "Removing the first and last entry from TreeMap:"
},
{
"code": null,
"e": 26779,
"s": 26724,
"text": "1. Using pollFirstEntry() and pollLastEntry() methods:"
},
{
"code": null,
"e": 26935,
"s": 26779,
"text": "TreeMap has two method which can remove the first and last entry .pollFirstEntry() for removing the first entry and for last entry we use pollLastEntry()."
},
{
"code": null,
"e": 26943,
"s": 26935,
"text": "Syntax:"
},
{
"code": null,
"e": 26998,
"s": 26943,
"text": "mapObject.pollFirstEntry();\nmapObject.pollLastEntry();"
},
{
"code": null,
"e": 27084,
"s": 26998,
"text": "Return Type: The return type of both the method is entry object removed from the map."
},
{
"code": null,
"e": 27496,
"s": 27084,
"text": "First, we will create a TreeMap and add records in it using the put() method and then print all the records using for each loop. For printing, we will use all the keys which we can get using the keySet() method. Now we will use pollFirstEntry() and pollLastEntry() on TreeMap to remove first and last entry. After removing the first and last entry we again will iterate over the TreeMap using the for each loop."
},
{
"code": null,
"e": 27512,
"s": 27496,
"text": "Implementation:"
},
{
"code": null,
"e": 27517,
"s": 27512,
"text": "Java"
},
{
"code": "// Java Program remove the first entry// or last entry from the TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and values of type // integer TreeMap<String, Integer> gfg = new TreeMap<>(); // adding values to tree map gfg.put(\"Interviews\", 97); gfg.put(\"fang\", 86); gfg.put(\"competitive programming\", 95); gfg.put(\"dsa\", 99); gfg.put(\"java\", 99); gfg.put(\"c++\", 99); System.out.println( \"-------before removing first and last entry-------\"); // iterating over the treemap in java for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } // removing and printing first entry System.out.println( \"----printing the first removed entry----\"); System.out.println(gfg.pollFirstEntry()); // removing and printing last entry System.out.println( \"----printing the last removed entry\"); System.out.println(gfg.pollLastEntry()); System.out.println( \"-------after removing first and last entry-------\"); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } }}",
"e": 28910,
"s": 27517,
"text": null
},
{
"code": null,
"e": 29230,
"s": 28910,
"text": "-------before removing first and last entry-------\nInterviews,97\nc++,99\ncompetitive programming,95\ndsa,99\nfang,86\njava,99\n----printing the first removed entry----\nInterviews=97\n----printing the last removed entry\njava=99\n-------after removing first and last entry-------\nc++,99\ncompetitive programming,95\ndsa,99\nfang,86"
},
{
"code": null,
"e": 29265,
"s": 29230,
"text": "2. Using lastKey() and firstKey():"
},
{
"code": null,
"e": 29273,
"s": 29265,
"text": "Syntax:"
},
{
"code": null,
"e": 29328,
"s": 29273,
"text": "map.remove(map.lastKey());\nmap.remove(map.firstKey());"
},
{
"code": null,
"e": 29338,
"s": 29328,
"text": "Approach:"
},
{
"code": null,
"e": 30032,
"s": 29338,
"text": "First, we will create the TreeMap and inserts a record in it using a put() method. Now we will print all the records using for each loop and the output will be in the sorting order of keys from a to z. For removing the first entry and last entry we will use the remove(key) method. In the remove method, we need to pass the key as an argument. Now if we somehow get the first and last key we will be able to remove the first and last entry. TreeMap gives us two such methods which can give us first and the last key which is firstKey() and lastkey(), after getting the keys we will pass these keys in the remove() method and then again print the values present in treemap using for each loop."
},
{
"code": null,
"e": 30048,
"s": 30032,
"text": "Implementation:"
},
{
"code": null,
"e": 30053,
"s": 30048,
"text": "Java"
},
{
"code": "// Java Program to remove the first entry// or last entry from the TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and values of type // integer TreeMap<String, Integer> gfg = new TreeMap<>(); gfg.put(\"Interviews\", 97); gfg.put(\"fang\", 86); gfg.put(\"competitive programming\", 95); gfg.put(\"dsa\", 99); gfg.put(\"java\", 99); gfg.put(\"c++\", 99); // iterating over the treemap in java System.out.println( \"-------before removing first and last entry-------\"); for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } // removing first entry through firstKey() gfg.remove(gfg.firstKey()); // removing last entry through lastKey() gfg.remove(gfg.lastKey()); System.out.println( \"-------after removing first and last entry-------\"); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } }}",
"e": 31233,
"s": 30053,
"text": null
},
{
"code": null,
"e": 31454,
"s": 31233,
"text": "-------before removing first and last entry-------\nInterviews,97\nc++,99\ncompetitive programming,95\ndsa,99\nfang,86\njava,99\n-------after removing first and last entry-------\nc++,99\ncompetitive programming,95\ndsa,99\nfang,86"
},
{
"code": null,
"e": 31474,
"s": 31454,
"text": "3. Using Streams():"
},
{
"code": null,
"e": 31563,
"s": 31474,
"text": "Here we will get the first and last key using streams then call the remove method on it."
},
{
"code": null,
"e": 31571,
"s": 31563,
"text": "Syntax:"
},
{
"code": null,
"e": 31743,
"s": 31571,
"text": "firsrkey = map.entrySet().stream().findFirst().get()\ntreemap.remove(firstkey);\n\nlastkey = map.entrySet().stream().skip(map.size()-1).findFirst().get()\ntreemap.remove(key);"
},
{
"code": null,
"e": 31753,
"s": 31743,
"text": "Approach:"
},
{
"code": null,
"e": 32240,
"s": 31753,
"text": "Here we will create a TreeMap and add records in it using the put() method and then print every record using for each loop. Now we will use streams for getting the first and last key. For the first key, we will get a set of all the keys using the keySet() method and then we will use the stream() on it, now for getting the first item(a record) from the stream we will use findFirst() and get() on it to get the first key then pass this in remove method to remove first entry(a record)."
},
{
"code": null,
"e": 32544,
"s": 32240,
"text": "For the last Key, we will again use keySet() for all the keys and after it stream(), Now we will skip the n-1 elements because if we skip the first n-1 records then ultimately we will arrive at the last record. For getting the n( number of total records or size of the TreeMap) we use the size() method."
},
{
"code": null,
"e": 32560,
"s": 32544,
"text": "Implementation:"
},
{
"code": null,
"e": 32565,
"s": 32560,
"text": "Java"
},
{
"code": "// Java Program remove the first entry// or last entry from the TreeMapimport java.io.*;import java.util.TreeMap;import java.util.Set; class GFG { public static void main(String[] args) { // treemap with keys as string and values of type // integer TreeMap<String, Integer> gfg = new TreeMap<>(); gfg.put(\"Interviews\", 97); gfg.put(\"fang\", 86); gfg.put(\"competitive programming\", 95); gfg.put(\"dsa\", 99); gfg.put(\"java\", 99); gfg.put(\"c++\", 99); // iterating over the treemap in java System.out.println( \"-------before removing first and last entry-------\"); for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } // removing first entry through firstKey() String firstKey = gfg.keySet().stream().findFirst().get(); gfg.remove(firstKey); // removing last entry through lastKey() String lastKey = gfg.keySet() .stream() .skip(gfg.size() - 1) .findFirst() .get(); gfg.remove(lastKey); System.out.println( \"-------after removing first and last entry-------\"); // iterating over the treemap for (String key : gfg.keySet()) { System.out.println(key + \",\" + gfg.get(key)); } }}",
"e": 34009,
"s": 32565,
"text": null
},
{
"code": null,
"e": 34230,
"s": 34009,
"text": "-------before removing first and last entry-------\nInterviews,97\nc++,99\ncompetitive programming,95\ndsa,99\nfang,86\njava,99\n-------after removing first and last entry-------\nc++,99\ncompetitive programming,95\ndsa,99\nfang,86"
},
{
"code": null,
"e": 34243,
"s": 34230,
"text": "simmytarika5"
},
{
"code": null,
"e": 34255,
"s": 34243,
"text": "anikaseth98"
},
{
"code": null,
"e": 34268,
"s": 34255,
"text": "java-TreeMap"
},
{
"code": null,
"e": 34275,
"s": 34268,
"text": "Picked"
},
{
"code": null,
"e": 34280,
"s": 34275,
"text": "Java"
},
{
"code": null,
"e": 34294,
"s": 34280,
"text": "Java Programs"
},
{
"code": null,
"e": 34299,
"s": 34294,
"text": "Java"
},
{
"code": null,
"e": 34397,
"s": 34299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34412,
"s": 34397,
"text": "Stream In Java"
},
{
"code": null,
"e": 34433,
"s": 34412,
"text": "Constructors in Java"
},
{
"code": null,
"e": 34452,
"s": 34433,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 34482,
"s": 34452,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 34528,
"s": 34482,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 34554,
"s": 34528,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 34588,
"s": 34554,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 34635,
"s": 34588,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 34667,
"s": 34635,
"text": "How to Iterate HashMap in Java?"
}
] |
Process Control Commands in Unix/Linux - GeeksforGeeks
|
18 Mar, 2021
Process control commands in Unix are:
bg - put suspended process into background
fg - bring process into foreground
jobs - list processes
bg Command : bg is a process control command that resumes suspended process while keeping them running in the background. User can run a job in the background by adding a “&” symbol at the end of the command.Syntax :bg [job]
OptionsThe character % introduces a job specification. The Job can be a process ID (PID) number, or we can use one of the following symbol combinations:%Number : Use the job number such as %1 or %2.
%String : Use the string whose name begins
with suspended command such as %commandNameHere or
%ping.
%+ OR %% : Refers to the current job.
%- : Refers to the previous job.
bg examplesCommandbg %1Output:The stopped job will resume operation, but remain in the background.
It will not receive any input from the terminal while it's in the background,
but it will keep running.
fg Command : fg command moves a background job in the current shell environment into the foreground. Use the job ID parameter to indicate a specific job to be run in the foreground. If this parameter is not supplied, the fg command uses the job most recently suspended, placed in the background, or run as a background job .Syntax :fg [ %job]Options%job: Specifies the job that you want to run in the foreground.
fg examplesCommand$ fgOutput:It will resume the most recently suspended or background job.
Command$ fg 1Output:It brings the job with the id 1 into the foreground, resuming it if it was suspended.
Jobs Command : Jobs command is used to list the jobs that you are running in the background and in the foreground. If the prompt is returned with no information no jobs are present. All shells are not capable of running this command. This command is only available in the csh, bash, tcsh, and ksh shells.Syntax :jobs [JOB]OptionsJOB Job name or number.
-l Lists process IDs in addition to the normal information.
-n List only processes that have changed status since the last notification.
-p Lists process IDs only.
-r Restrict output to running jobs.
-s Restrict output to stopped jobs.
jobs command examplesTo display the status of jobs in the current shell:Command$ jobsOutput:[1] 7893 Running gpass &
[2] 7904 Running gnome-calculator &
[3]- 7955 Running gedit fetch-stock-prices.py &
[4]+ 7958 Stopped ping cyberciti.biz
To display the process ID or jobs for the job whose name begins with “p,”:Command$ jobs -p %pOR$ jobs %pOutput:[4]- Stopped ping cyberciti.bizThe character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping.Pass the -p option to jobs command to display PIDs only:Command$ jobs -pOutput:7895
7906
7910
7946
Pass the -r option to jobs command to display only running jobs only:Command$ jobs -rOutput:[1] Running gpass &
[2] Running gnome-calculator &
[3]- Running gedit fetch-stock-prices.py &
bg Command : bg is a process control command that resumes suspended process while keeping them running in the background. User can run a job in the background by adding a “&” symbol at the end of the command.Syntax :bg [job]
OptionsThe character % introduces a job specification. The Job can be a process ID (PID) number, or we can use one of the following symbol combinations:%Number : Use the job number such as %1 or %2.
%String : Use the string whose name begins
with suspended command such as %commandNameHere or
%ping.
%+ OR %% : Refers to the current job.
%- : Refers to the previous job.
bg examplesCommandbg %1Output:The stopped job will resume operation, but remain in the background.
It will not receive any input from the terminal while it's in the background,
but it will keep running.
bg [job]
Options
The character % introduces a job specification. The Job can be a process ID (PID) number, or we can use one of the following symbol combinations:
%Number : Use the job number such as %1 or %2.
%String : Use the string whose name begins
with suspended command such as %commandNameHere or
%ping.
%+ OR %% : Refers to the current job.
%- : Refers to the previous job.
bg examples
Command
bg %1
Output:
The stopped job will resume operation, but remain in the background.
It will not receive any input from the terminal while it's in the background,
but it will keep running.
fg Command : fg command moves a background job in the current shell environment into the foreground. Use the job ID parameter to indicate a specific job to be run in the foreground. If this parameter is not supplied, the fg command uses the job most recently suspended, placed in the background, or run as a background job .Syntax :fg [ %job]Options%job: Specifies the job that you want to run in the foreground.
fg examplesCommand$ fgOutput:It will resume the most recently suspended or background job.
Command$ fg 1Output:It brings the job with the id 1 into the foreground, resuming it if it was suspended.
fg [ %job]
Options
%job: Specifies the job that you want to run in the foreground.
fg examples
Command
$ fg
Output:
It will resume the most recently suspended or background job.
Command
$ fg 1
Output:
It brings the job with the id 1 into the foreground, resuming it if it was suspended.
Jobs Command : Jobs command is used to list the jobs that you are running in the background and in the foreground. If the prompt is returned with no information no jobs are present. All shells are not capable of running this command. This command is only available in the csh, bash, tcsh, and ksh shells.Syntax :jobs [JOB]OptionsJOB Job name or number.
-l Lists process IDs in addition to the normal information.
-n List only processes that have changed status since the last notification.
-p Lists process IDs only.
-r Restrict output to running jobs.
-s Restrict output to stopped jobs.
jobs command examplesTo display the status of jobs in the current shell:Command$ jobsOutput:[1] 7893 Running gpass &
[2] 7904 Running gnome-calculator &
[3]- 7955 Running gedit fetch-stock-prices.py &
[4]+ 7958 Stopped ping cyberciti.biz
To display the process ID or jobs for the job whose name begins with “p,”:Command$ jobs -p %pOR$ jobs %pOutput:[4]- Stopped ping cyberciti.bizThe character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping.Pass the -p option to jobs command to display PIDs only:Command$ jobs -pOutput:7895
7906
7910
7946
Pass the -r option to jobs command to display only running jobs only:Command$ jobs -rOutput:[1] Running gpass &
[2] Running gnome-calculator &
[3]- Running gedit fetch-stock-prices.py &
jobs [JOB]
Options
JOB Job name or number.
-l Lists process IDs in addition to the normal information.
-n List only processes that have changed status since the last notification.
-p Lists process IDs only.
-r Restrict output to running jobs.
-s Restrict output to stopped jobs.
jobs command examples
To display the status of jobs in the current shell:Command
$ jobs
Output:
[1] 7893 Running gpass &
[2] 7904 Running gnome-calculator &
[3]- 7955 Running gedit fetch-stock-prices.py &
[4]+ 7958 Stopped ping cyberciti.biz
To display the process ID or jobs for the job whose name begins with “p,”:Command
$ jobs -p %p
OR
$ jobs %p
Output:
[4]- Stopped ping cyberciti.biz
The character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping.
Pass the -p option to jobs command to display PIDs only:Command
$ jobs -p
Output:
7895
7906
7910
7946
Pass the -r option to jobs command to display only running jobs only:Command
$ jobs -r
Output:
[1] Running gpass &
[2] Running gnome-calculator &
[3]- Running gedit fetch-stock-prices.py &
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 25689,
"s": 25651,
"text": "Process control commands in Unix are:"
},
{
"code": null,
"e": 25790,
"s": 25689,
"text": "bg - put suspended process into background\nfg - bring process into foreground\njobs - list processes\n"
},
{
"code": null,
"e": 28803,
"s": 25790,
"text": "bg Command : bg is a process control command that resumes suspended process while keeping them running in the background. User can run a job in the background by adding a “&” symbol at the end of the command.Syntax :bg [job]\nOptionsThe character % introduces a job specification. The Job can be a process ID (PID) number, or we can use one of the following symbol combinations:%Number : Use the job number such as %1 or %2.\n%String : Use the string whose name begins \n with suspended command such as %commandNameHere or \n %ping.\n%+ OR %% : Refers to the current job.\n%- : Refers to the previous job.\nbg examplesCommandbg %1Output:The stopped job will resume operation, but remain in the background. \nIt will not receive any input from the terminal while it's in the background, \nbut it will keep running.\nfg Command : fg command moves a background job in the current shell environment into the foreground. Use the job ID parameter to indicate a specific job to be run in the foreground. If this parameter is not supplied, the fg command uses the job most recently suspended, placed in the background, or run as a background job .Syntax :fg [ %job]Options%job: Specifies the job that you want to run in the foreground.\nfg examplesCommand$ fgOutput:It will resume the most recently suspended or background job.\nCommand$ fg 1Output:It brings the job with the id 1 into the foreground, resuming it if it was suspended.\nJobs Command : Jobs command is used to list the jobs that you are running in the background and in the foreground. If the prompt is returned with no information no jobs are present. All shells are not capable of running this command. This command is only available in the csh, bash, tcsh, and ksh shells.Syntax :jobs [JOB]OptionsJOB Job name or number.\n-l Lists process IDs in addition to the normal information.\n-n List only processes that have changed status since the last notification.\n-p Lists process IDs only.\n-r Restrict output to running jobs.\n-s Restrict output to stopped jobs.\njobs command examplesTo display the status of jobs in the current shell:Command$ jobsOutput:[1] 7893 Running gpass &\n[2] 7904 Running gnome-calculator &\n[3]- 7955 Running gedit fetch-stock-prices.py &\n[4]+ 7958 Stopped ping cyberciti.biz\nTo display the process ID or jobs for the job whose name begins with “p,”:Command$ jobs -p %pOR$ jobs %pOutput:[4]- Stopped ping cyberciti.bizThe character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping.Pass the -p option to jobs command to display PIDs only:Command$ jobs -pOutput:7895\n7906\n7910\n7946\nPass the -r option to jobs command to display only running jobs only:Command$ jobs -rOutput:[1] Running gpass &\n[2] Running gnome-calculator &\n[3]- Running gedit fetch-stock-prices.py &\n"
},
{
"code": null,
"e": 29651,
"s": 28803,
"text": "bg Command : bg is a process control command that resumes suspended process while keeping them running in the background. User can run a job in the background by adding a “&” symbol at the end of the command.Syntax :bg [job]\nOptionsThe character % introduces a job specification. The Job can be a process ID (PID) number, or we can use one of the following symbol combinations:%Number : Use the job number such as %1 or %2.\n%String : Use the string whose name begins \n with suspended command such as %commandNameHere or \n %ping.\n%+ OR %% : Refers to the current job.\n%- : Refers to the previous job.\nbg examplesCommandbg %1Output:The stopped job will resume operation, but remain in the background. \nIt will not receive any input from the terminal while it's in the background, \nbut it will keep running.\n"
},
{
"code": null,
"e": 29661,
"s": 29651,
"text": "bg [job]\n"
},
{
"code": null,
"e": 29669,
"s": 29661,
"text": "Options"
},
{
"code": null,
"e": 29815,
"s": 29669,
"text": "The character % introduces a job specification. The Job can be a process ID (PID) number, or we can use one of the following symbol combinations:"
},
{
"code": null,
"e": 30081,
"s": 29815,
"text": "%Number : Use the job number such as %1 or %2.\n%String : Use the string whose name begins \n with suspended command such as %commandNameHere or \n %ping.\n%+ OR %% : Refers to the current job.\n%- : Refers to the previous job.\n"
},
{
"code": null,
"e": 30093,
"s": 30081,
"text": "bg examples"
},
{
"code": null,
"e": 30101,
"s": 30093,
"text": "Command"
},
{
"code": null,
"e": 30107,
"s": 30101,
"text": "bg %1"
},
{
"code": null,
"e": 30115,
"s": 30107,
"text": "Output:"
},
{
"code": null,
"e": 30291,
"s": 30115,
"text": "The stopped job will resume operation, but remain in the background. \nIt will not receive any input from the terminal while it's in the background, \nbut it will keep running.\n"
},
{
"code": null,
"e": 30902,
"s": 30291,
"text": "fg Command : fg command moves a background job in the current shell environment into the foreground. Use the job ID parameter to indicate a specific job to be run in the foreground. If this parameter is not supplied, the fg command uses the job most recently suspended, placed in the background, or run as a background job .Syntax :fg [ %job]Options%job: Specifies the job that you want to run in the foreground.\nfg examplesCommand$ fgOutput:It will resume the most recently suspended or background job.\nCommand$ fg 1Output:It brings the job with the id 1 into the foreground, resuming it if it was suspended.\n"
},
{
"code": null,
"e": 30913,
"s": 30902,
"text": "fg [ %job]"
},
{
"code": null,
"e": 30921,
"s": 30913,
"text": "Options"
},
{
"code": null,
"e": 30986,
"s": 30921,
"text": "%job: Specifies the job that you want to run in the foreground.\n"
},
{
"code": null,
"e": 30998,
"s": 30986,
"text": "fg examples"
},
{
"code": null,
"e": 31006,
"s": 30998,
"text": "Command"
},
{
"code": null,
"e": 31011,
"s": 31006,
"text": "$ fg"
},
{
"code": null,
"e": 31019,
"s": 31011,
"text": "Output:"
},
{
"code": null,
"e": 31082,
"s": 31019,
"text": "It will resume the most recently suspended or background job.\n"
},
{
"code": null,
"e": 31090,
"s": 31082,
"text": "Command"
},
{
"code": null,
"e": 31097,
"s": 31090,
"text": "$ fg 1"
},
{
"code": null,
"e": 31105,
"s": 31097,
"text": "Output:"
},
{
"code": null,
"e": 31192,
"s": 31105,
"text": "It brings the job with the id 1 into the foreground, resuming it if it was suspended.\n"
},
{
"code": null,
"e": 32748,
"s": 31192,
"text": "Jobs Command : Jobs command is used to list the jobs that you are running in the background and in the foreground. If the prompt is returned with no information no jobs are present. All shells are not capable of running this command. This command is only available in the csh, bash, tcsh, and ksh shells.Syntax :jobs [JOB]OptionsJOB Job name or number.\n-l Lists process IDs in addition to the normal information.\n-n List only processes that have changed status since the last notification.\n-p Lists process IDs only.\n-r Restrict output to running jobs.\n-s Restrict output to stopped jobs.\njobs command examplesTo display the status of jobs in the current shell:Command$ jobsOutput:[1] 7893 Running gpass &\n[2] 7904 Running gnome-calculator &\n[3]- 7955 Running gedit fetch-stock-prices.py &\n[4]+ 7958 Stopped ping cyberciti.biz\nTo display the process ID or jobs for the job whose name begins with “p,”:Command$ jobs -p %pOR$ jobs %pOutput:[4]- Stopped ping cyberciti.bizThe character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping.Pass the -p option to jobs command to display PIDs only:Command$ jobs -pOutput:7895\n7906\n7910\n7946\nPass the -r option to jobs command to display only running jobs only:Command$ jobs -rOutput:[1] Running gpass &\n[2] Running gnome-calculator &\n[3]- Running gedit fetch-stock-prices.py &\n"
},
{
"code": null,
"e": 32760,
"s": 32748,
"text": "jobs [JOB]"
},
{
"code": null,
"e": 32768,
"s": 32760,
"text": "Options"
},
{
"code": null,
"e": 33044,
"s": 32768,
"text": "JOB Job name or number.\n-l Lists process IDs in addition to the normal information.\n-n List only processes that have changed status since the last notification.\n-p Lists process IDs only.\n-r Restrict output to running jobs.\n-s Restrict output to stopped jobs.\n"
},
{
"code": null,
"e": 33066,
"s": 33044,
"text": "jobs command examples"
},
{
"code": null,
"e": 33125,
"s": 33066,
"text": "To display the status of jobs in the current shell:Command"
},
{
"code": null,
"e": 33132,
"s": 33125,
"text": "$ jobs"
},
{
"code": null,
"e": 33140,
"s": 33132,
"text": "Output:"
},
{
"code": null,
"e": 33357,
"s": 33140,
"text": "[1] 7893 Running gpass &\n[2] 7904 Running gnome-calculator &\n[3]- 7955 Running gedit fetch-stock-prices.py &\n[4]+ 7958 Stopped ping cyberciti.biz\n"
},
{
"code": null,
"e": 33439,
"s": 33357,
"text": "To display the process ID or jobs for the job whose name begins with “p,”:Command"
},
{
"code": null,
"e": 33452,
"s": 33439,
"text": "$ jobs -p %p"
},
{
"code": null,
"e": 33455,
"s": 33452,
"text": "OR"
},
{
"code": null,
"e": 33465,
"s": 33455,
"text": "$ jobs %p"
},
{
"code": null,
"e": 33473,
"s": 33465,
"text": "Output:"
},
{
"code": null,
"e": 33522,
"s": 33473,
"text": "[4]- Stopped ping cyberciti.biz"
},
{
"code": null,
"e": 33668,
"s": 33522,
"text": "The character % introduces a job specification. In this example, you are using the string whose name begins with suspended command such as %ping."
},
{
"code": null,
"e": 33732,
"s": 33668,
"text": "Pass the -p option to jobs command to display PIDs only:Command"
},
{
"code": null,
"e": 33742,
"s": 33732,
"text": "$ jobs -p"
},
{
"code": null,
"e": 33750,
"s": 33742,
"text": "Output:"
},
{
"code": null,
"e": 33771,
"s": 33750,
"text": "7895\n7906\n7910\n7946\n"
},
{
"code": null,
"e": 33848,
"s": 33771,
"text": "Pass the -r option to jobs command to display only running jobs only:Command"
},
{
"code": null,
"e": 33858,
"s": 33848,
"text": "$ jobs -r"
},
{
"code": null,
"e": 33866,
"s": 33858,
"text": "Output:"
},
{
"code": null,
"e": 34014,
"s": 33866,
"text": "[1] Running gpass &\n[2] Running gnome-calculator &\n[3]- Running gedit fetch-stock-prices.py &\n"
},
{
"code": null,
"e": 34025,
"s": 34014,
"text": "Linux-Unix"
},
{
"code": null,
"e": 34123,
"s": 34025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34158,
"s": 34123,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 34192,
"s": 34158,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 34218,
"s": 34192,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 34247,
"s": 34218,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 34284,
"s": 34247,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 34321,
"s": 34284,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 34363,
"s": 34321,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 34389,
"s": 34363,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 34425,
"s": 34389,
"text": "uniq Command in LINUX with examples"
}
] |
How to scale Pandas DataFrame columns ? - GeeksforGeeks
|
02 Jul, 2021
When a dataset has values of different columns at drastically different scales, it gets tough to analyze the trends and patterns and comparison of the features or columns. So, in cases where all the columns have a significant difference in their scales, are needed to be modified in such a way that all those values fall into the same scale. This process is called Scaling.
There are two most common techniques of how to scale columns of Pandas dataframe – Min-Max Normalization and Standardization. Both of them have been discussed in the content below.
Dataset in Use: Iris
Here, all the values are scaled in between the range of [0,1] where 0 is the minimum value and 1 is the maximum value. The formula for Min-Max Normalization is –
Method 1: Using Pandas and Numpy
The first way of doing this is by separately calculate the values required as given in the formula and then apply it to the dataset.
Example:
Python3
import seaborn as snsimport pandas as pdimport numpy as np data = sns.load_dataset('iris')print('Original Dataset')data.head() # Min-Max Normalizationdf = data.drop('species', axis=1)df_norm = (df-df.min())/(df.max()-df.min())df_norm = pd.concat((df_norm, data.species), 1) print("Scaled Dataset Using Pandas")df_norm.head()
Output:
Method 2: Using MinMaxScaler from sklearn
This is a straightforward method of doing the same. It just requires sklearn module to be imported.
Example:
Python3
import seaborn as snsfrom sklearn.preprocessing import MinMaxScalerimport pandas as pd data = sns.load_dataset('iris')print('Original Dataset')data.head() scaler = MinMaxScaler() df_scaled = scaler.fit_transform(df.to_numpy())df_scaled = pd.DataFrame(df_scaled, columns=[ 'sepal_length', 'sepal_width', 'petal_length', 'petal_width']) print("Scaled Dataset Using MinMaxScaler")df_scaled.head()
Output:
Standardization doesn’t have any fixed minimum or maximum value. Here, the values of all the columns are scaled in such a way that they all have a mean equal to 0 and standard deviation equal to 1. This scaling technique works well with outliers. Thus, this technique is preferred if outliers are present in the dataset.
Example:
Python3
import pandas as pdfrom sklearn.preprocessing import StandardScalerimport seaborn as sns data = sns.load_dataset('iris')print('Original Dataset')data.head() std_scaler = StandardScaler() df_scaled = std_scaler.fit_transform(df.to_numpy())df_scaled = pd.DataFrame(df_scaled, columns=[ 'sepal_length','sepal_width','petal_length','petal_width']) print("Scaled Dataset Using StandardScaler")df_scaled.head()
Output :
simranarora5sos
sweetyty
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 25911,
"s": 25537,
"text": "When a dataset has values of different columns at drastically different scales, it gets tough to analyze the trends and patterns and comparison of the features or columns. So, in cases where all the columns have a significant difference in their scales, are needed to be modified in such a way that all those values fall into the same scale. This process is called Scaling."
},
{
"code": null,
"e": 26092,
"s": 25911,
"text": "There are two most common techniques of how to scale columns of Pandas dataframe – Min-Max Normalization and Standardization. Both of them have been discussed in the content below."
},
{
"code": null,
"e": 26113,
"s": 26092,
"text": "Dataset in Use: Iris"
},
{
"code": null,
"e": 26275,
"s": 26113,
"text": "Here, all the values are scaled in between the range of [0,1] where 0 is the minimum value and 1 is the maximum value. The formula for Min-Max Normalization is –"
},
{
"code": null,
"e": 26309,
"s": 26275,
"text": "Method 1: Using Pandas and Numpy "
},
{
"code": null,
"e": 26442,
"s": 26309,
"text": "The first way of doing this is by separately calculate the values required as given in the formula and then apply it to the dataset."
},
{
"code": null,
"e": 26451,
"s": 26442,
"text": "Example:"
},
{
"code": null,
"e": 26459,
"s": 26451,
"text": "Python3"
},
{
"code": "import seaborn as snsimport pandas as pdimport numpy as np data = sns.load_dataset('iris')print('Original Dataset')data.head() # Min-Max Normalizationdf = data.drop('species', axis=1)df_norm = (df-df.min())/(df.max()-df.min())df_norm = pd.concat((df_norm, data.species), 1) print(\"Scaled Dataset Using Pandas\")df_norm.head()",
"e": 26784,
"s": 26459,
"text": null
},
{
"code": null,
"e": 26792,
"s": 26784,
"text": "Output:"
},
{
"code": null,
"e": 26835,
"s": 26792,
"text": "Method 2: Using MinMaxScaler from sklearn "
},
{
"code": null,
"e": 26935,
"s": 26835,
"text": "This is a straightforward method of doing the same. It just requires sklearn module to be imported."
},
{
"code": null,
"e": 26944,
"s": 26935,
"text": "Example:"
},
{
"code": null,
"e": 26952,
"s": 26944,
"text": "Python3"
},
{
"code": "import seaborn as snsfrom sklearn.preprocessing import MinMaxScalerimport pandas as pd data = sns.load_dataset('iris')print('Original Dataset')data.head() scaler = MinMaxScaler() df_scaled = scaler.fit_transform(df.to_numpy())df_scaled = pd.DataFrame(df_scaled, columns=[ 'sepal_length', 'sepal_width', 'petal_length', 'petal_width']) print(\"Scaled Dataset Using MinMaxScaler\")df_scaled.head()",
"e": 27347,
"s": 26952,
"text": null
},
{
"code": null,
"e": 27355,
"s": 27347,
"text": "Output:"
},
{
"code": null,
"e": 27677,
"s": 27355,
"text": "Standardization doesn’t have any fixed minimum or maximum value. Here, the values of all the columns are scaled in such a way that they all have a mean equal to 0 and standard deviation equal to 1. This scaling technique works well with outliers. Thus, this technique is preferred if outliers are present in the dataset. "
},
{
"code": null,
"e": 27686,
"s": 27677,
"text": "Example:"
},
{
"code": null,
"e": 27694,
"s": 27686,
"text": "Python3"
},
{
"code": "import pandas as pdfrom sklearn.preprocessing import StandardScalerimport seaborn as sns data = sns.load_dataset('iris')print('Original Dataset')data.head() std_scaler = StandardScaler() df_scaled = std_scaler.fit_transform(df.to_numpy())df_scaled = pd.DataFrame(df_scaled, columns=[ 'sepal_length','sepal_width','petal_length','petal_width']) print(\"Scaled Dataset Using StandardScaler\")df_scaled.head()",
"e": 28100,
"s": 27694,
"text": null
},
{
"code": null,
"e": 28112,
"s": 28103,
"text": "Output :"
},
{
"code": null,
"e": 28132,
"s": 28116,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28141,
"s": 28132,
"text": "sweetyty"
},
{
"code": null,
"e": 28148,
"s": 28141,
"text": "Picked"
},
{
"code": null,
"e": 28172,
"s": 28148,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28186,
"s": 28172,
"text": "Python-pandas"
},
{
"code": null,
"e": 28193,
"s": 28186,
"text": "Python"
},
{
"code": null,
"e": 28291,
"s": 28193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28323,
"s": 28291,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28365,
"s": 28323,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28407,
"s": 28365,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28463,
"s": 28407,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28490,
"s": 28463,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28529,
"s": 28490,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28560,
"s": 28529,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28589,
"s": 28560,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28611,
"s": 28589,
"text": "Defaultdict in Python"
}
] |
How to create an image slider works with radio button ? - GeeksforGeeks
|
18 Jan, 2021
A slider is a series of images that appear in sequence. Now, we will see an image slider working with radio buttons using HTML & CSS in which the image slides up, on clicking the radio button.
Approach:
The property of the radio buttons is only one radio button in a group that can be selected at the same time.We will use radio buttons to select the image that we want to see from the image slider by giving an unique id to each radio button.Next, we will embed all the images one by one and create labels for radio button id’s and will apply necessary CSS properties to achieve the desired output.
The property of the radio buttons is only one radio button in a group that can be selected at the same time.
We will use radio buttons to select the image that we want to see from the image slider by giving an unique id to each radio button.
Next, we will embed all the images one by one and create labels for radio button id’s and will apply necessary CSS properties to achieve the desired output.
Example:
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>Image Slider</title> <style> /* CSS code */ body { margin: 0; padding: 0; height: 100vh; display: flex; justify-content: center; align-items: center; } .slider { width: 800px; height: 500px; border-radius: 10px; overflow: hidden; } .imgs_slides { width: 500%; height: 500px; display: flex; } /* We have to set display: none; If not, all of our images would be visible at the same time */ .imgs_slides input { display: none; } .slide { width: 20%; transition: 2s; } .slide img { width: 800px; height: 500px; } /* css for slide navigation */ .navigation { position: absolute; width: 800px; margin-top: -40px; display: flex; justify-content: center; } .navigation-btn { border: 2px solid #de6a23; padding: 5px; border-radius: 10px; cursor: pointer; transition: 1s; } .navigation-btn:not(:last-child) { margin-right: 40px; } .navigation-btn:hover { background: #de6a23; } /* The checked attribute is used with reference to <input type="radio">, when radio button is clicked the class will shift w.r.t left margin as mentioned which results in image slider */ #radio1:checked~.first { margin-left: 0; } #radio2:checked~.first { margin-left: -20%; } #radio3:checked~.first { margin-left: -40%; } #radio4:checked~.first { margin-left: -60%; } #radio5:checked~.first { margin-left: -80%; } </style> <link rel="stylesheet" type="text/css" href="styles.css" /></head> <body> <center> <!-- Image slider start --> <div class="slider"> <div class="imgs_slides"> <!-- Radio buttons start --> <input type="radio" name="radio-btn" id="radio1" /> <input type="radio" name="radio-btn" id="radio2" /> <input type="radio" name="radio-btn" id="radio3" /> <input type="radio" name="radio-btn" id="radio4" /> <input type="radio" name="radio-btn" id="radio5" /> <!-- Radio buttons end --> <!-- Embedding images start --> <div class="first slide"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210105130612/img1.PNG" /> </div> <div class="slide"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210105130614/img2.PNG" /> </div> <div class="slide"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210105130615/img3.PNG" /> </div> <div class="slide"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210105130616/img4.PNG" /> </div> <div class="slide"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210105130617/img5.PNG" /> </div> <!-- Embedding images end --> </div> <!-- Navigation start --> <div class="navigation"> <label for="radio1" class="navigation-btn"> </label> <label for="radio2" class="navigation-btn"> </label> <label for="radio3" class="navigation-btn"> </label> <label for="radio4" class="navigation-btn"> </label> <label for="radio5" class="navigation-btn"> </label> </div> <!-- Navigation end --> </div> <!-- Image slider end --> </center></body> </html>
Output:
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
Picked
CSS
HTML
Web Technologies
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": "\n18 Jan, 2021"
},
{
"code": null,
"e": 26814,
"s": 26621,
"text": "A slider is a series of images that appear in sequence. Now, we will see an image slider working with radio buttons using HTML & CSS in which the image slides up, on clicking the radio button."
},
{
"code": null,
"e": 26824,
"s": 26814,
"text": "Approach:"
},
{
"code": null,
"e": 27221,
"s": 26824,
"text": "The property of the radio buttons is only one radio button in a group that can be selected at the same time.We will use radio buttons to select the image that we want to see from the image slider by giving an unique id to each radio button.Next, we will embed all the images one by one and create labels for radio button id’s and will apply necessary CSS properties to achieve the desired output."
},
{
"code": null,
"e": 27330,
"s": 27221,
"text": "The property of the radio buttons is only one radio button in a group that can be selected at the same time."
},
{
"code": null,
"e": 27463,
"s": 27330,
"text": "We will use radio buttons to select the image that we want to see from the image slider by giving an unique id to each radio button."
},
{
"code": null,
"e": 27620,
"s": 27463,
"text": "Next, we will embed all the images one by one and create labels for radio button id’s and will apply necessary CSS properties to achieve the desired output."
},
{
"code": null,
"e": 27629,
"s": 27620,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <title>Image Slider</title> <style> /* CSS code */ body { margin: 0; padding: 0; height: 100vh; display: flex; justify-content: center; align-items: center; } .slider { width: 800px; height: 500px; border-radius: 10px; overflow: hidden; } .imgs_slides { width: 500%; height: 500px; display: flex; } /* We have to set display: none; If not, all of our images would be visible at the same time */ .imgs_slides input { display: none; } .slide { width: 20%; transition: 2s; } .slide img { width: 800px; height: 500px; } /* css for slide navigation */ .navigation { position: absolute; width: 800px; margin-top: -40px; display: flex; justify-content: center; } .navigation-btn { border: 2px solid #de6a23; padding: 5px; border-radius: 10px; cursor: pointer; transition: 1s; } .navigation-btn:not(:last-child) { margin-right: 40px; } .navigation-btn:hover { background: #de6a23; } /* The checked attribute is used with reference to <input type=\"radio\">, when radio button is clicked the class will shift w.r.t left margin as mentioned which results in image slider */ #radio1:checked~.first { margin-left: 0; } #radio2:checked~.first { margin-left: -20%; } #radio3:checked~.first { margin-left: -40%; } #radio4:checked~.first { margin-left: -60%; } #radio5:checked~.first { margin-left: -80%; } </style> <link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head> <body> <center> <!-- Image slider start --> <div class=\"slider\"> <div class=\"imgs_slides\"> <!-- Radio buttons start --> <input type=\"radio\" name=\"radio-btn\" id=\"radio1\" /> <input type=\"radio\" name=\"radio-btn\" id=\"radio2\" /> <input type=\"radio\" name=\"radio-btn\" id=\"radio3\" /> <input type=\"radio\" name=\"radio-btn\" id=\"radio4\" /> <input type=\"radio\" name=\"radio-btn\" id=\"radio5\" /> <!-- Radio buttons end --> <!-- Embedding images start --> <div class=\"first slide\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210105130612/img1.PNG\" /> </div> <div class=\"slide\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210105130614/img2.PNG\" /> </div> <div class=\"slide\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210105130615/img3.PNG\" /> </div> <div class=\"slide\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210105130616/img4.PNG\" /> </div> <div class=\"slide\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210105130617/img5.PNG\" /> </div> <!-- Embedding images end --> </div> <!-- Navigation start --> <div class=\"navigation\"> <label for=\"radio1\" class=\"navigation-btn\"> </label> <label for=\"radio2\" class=\"navigation-btn\"> </label> <label for=\"radio3\" class=\"navigation-btn\"> </label> <label for=\"radio4\" class=\"navigation-btn\"> </label> <label for=\"radio5\" class=\"navigation-btn\"> </label> </div> <!-- Navigation end --> </div> <!-- Image slider end --> </center></body> </html>",
"e": 31906,
"s": 27629,
"text": null
},
{
"code": null,
"e": 31914,
"s": 31906,
"text": "Output:"
},
{
"code": null,
"e": 32051,
"s": 31914,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 32060,
"s": 32051,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32070,
"s": 32060,
"text": "HTML-Misc"
},
{
"code": null,
"e": 32077,
"s": 32070,
"text": "Picked"
},
{
"code": null,
"e": 32081,
"s": 32077,
"text": "CSS"
},
{
"code": null,
"e": 32086,
"s": 32081,
"text": "HTML"
},
{
"code": null,
"e": 32103,
"s": 32086,
"text": "Web Technologies"
},
{
"code": null,
"e": 32108,
"s": 32103,
"text": "HTML"
},
{
"code": null,
"e": 32206,
"s": 32108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32245,
"s": 32206,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32282,
"s": 32245,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32311,
"s": 32282,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32353,
"s": 32311,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32388,
"s": 32353,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32448,
"s": 32388,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32501,
"s": 32448,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 32562,
"s": 32501,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 32586,
"s": 32562,
"text": "REST API (Introduction)"
}
] |
Print Lines Starting with String in Linux - GeeksforGeeks
|
17 Jun, 2021
Printing lines that contain a particular string at the beginning is quite annoying to manually deal with, so we can make use of bash to design a shell script. The most versatile and powerful tool for searching patterns or lines is by using grep, awk, or sed to find the most efficient solution to the problem.
The first thing to get started with is the file in which the string is to be searched and also the string. Both of the parameters will be inputted from the user. After that, we can use any one of the three tools grep, sed or awk. The concept is the same, we need to find the string only at the beginning of a line using regex and print the lines depending on the tool to be used.
We will input the file name and string from the user. We will use the read command and pass in the -p argument to prompt the user a text to display what he/she should input. We will store the input in the appropriate variable names.
#!/bin/bash
read -p “Enter the file name : ” file
read -p “Enter the string to search for in the file : ” str
The following are the three tools used to perform the operation of finding and printing lines that have a string input from the user. Anyone can be used as per user choice and requirements.
Method 1: Using GREP Command
The grep command is quite useful for finding patterns in the file or strings in the line. We will be using the simple grep command that searches for the word at the beginning of the file using the ^ operator and prints the line from the file. This is quite straightforward to understand if you are familiar with the grep command in Linux. The grep command will simply search for the input string/word from the file and print the line in which the string occurs only at the beginning. The last argument, which is “grep -v grep || true” only returns 0 if the grep didn’t find any match. This will not show the annoying error of shell return 1, it will not print anything and the user will understand that no line started with that string in the file.
#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the string to search for in the file : " str
grep "^$str" $file | { grep -v grep || true; }
using the grep command to search for strings at the start of lines.
The grep command is also a bit flexible as it allows us to print the line numbers as well. We can print the line numbers by adding some arguments to the above command. The -n argument after grep will print the line number in which the string is found in the file.
#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the string to search for in the file : " str
grep -n "^$str" $file | { grep -v grep || true; }
using the grep command to search for strings at the start of lines and print line numbers.
Both the cases in grep will be case-sensitive. To make the search case insensitive, you can add in the argument -i just after the grep like,
grep -i "^$str" $file | { grep -v grep || true; }
using grep command to search case insensitive strings at the start of lines.
Method 2: Using SED Command
The sed command is different than the grep command as it is a stream editor and not a command to just pass in arguments. We need to use -n so that the command doesn’t print everything from the file provided in the last argument of the command below. The following regex will search for the string variable and print all the matched lines. And the result will be compact output. The regex used is simple and similar to grep as it matches the string only at the beginning of the line using the ^ operator and backslashes mean the expression is a regex. The p argument will print the lines which match the regex. Both the cases in grep will be case-sensitive.
#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the string to search for in the file : " str
sed -n "/^$str/p" $file
using sed command to search for strings at the start of lines.
The gnu sed doesn’t support case-insensitive searches or matches. Still, you can use Perl to add case-insensitive matches.
Method 3: Using AWK Command
The regex for the AWK command is also the same and does the same thing in its own command style. The regex is almost similar to the sed command, which searches for the string variable, in the beginning, using the ^ operator and then simply prints the matched lines from the command. Both the cases in grep will be case-sensitive.
#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the string to search for in the file : " str
awk "/^$str/{print}" $file
using the awk command to search for strings at the start of lines.
To make the search in awk case insensitive, you can make some changes to the same command.
awk "BEGIN {IGNORECASE = 1} /^$str/{print}" $file
using the awk command to search for case insensitive strings at the start of lines.
The awk command has some inbuilt functions which set the arguments as default to case sensitive, we can change the properties of the awk commands.
Linux-text-processing-commands
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25677,
"s": 25649,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25987,
"s": 25677,
"text": "Printing lines that contain a particular string at the beginning is quite annoying to manually deal with, so we can make use of bash to design a shell script. The most versatile and powerful tool for searching patterns or lines is by using grep, awk, or sed to find the most efficient solution to the problem."
},
{
"code": null,
"e": 26368,
"s": 25987,
"text": "The first thing to get started with is the file in which the string is to be searched and also the string. Both of the parameters will be inputted from the user. After that, we can use any one of the three tools grep, sed or awk. The concept is the same, we need to find the string only at the beginning of a line using regex and print the lines depending on the tool to be used. "
},
{
"code": null,
"e": 26601,
"s": 26368,
"text": "We will input the file name and string from the user. We will use the read command and pass in the -p argument to prompt the user a text to display what he/she should input. We will store the input in the appropriate variable names."
},
{
"code": null,
"e": 26613,
"s": 26601,
"text": "#!/bin/bash"
},
{
"code": null,
"e": 26653,
"s": 26615,
"text": "read -p “Enter the file name : ” file"
},
{
"code": null,
"e": 26713,
"s": 26653,
"text": "read -p “Enter the string to search for in the file : ” str"
},
{
"code": null,
"e": 26903,
"s": 26713,
"text": "The following are the three tools used to perform the operation of finding and printing lines that have a string input from the user. Anyone can be used as per user choice and requirements."
},
{
"code": null,
"e": 26932,
"s": 26903,
"text": "Method 1: Using GREP Command"
},
{
"code": null,
"e": 27682,
"s": 26932,
"text": "The grep command is quite useful for finding patterns in the file or strings in the line. We will be using the simple grep command that searches for the word at the beginning of the file using the ^ operator and prints the line from the file. This is quite straightforward to understand if you are familiar with the grep command in Linux. The grep command will simply search for the input string/word from the file and print the line in which the string occurs only at the beginning. The last argument, which is “grep -v grep || true” only returns 0 if the grep didn’t find any match. This will not show the annoying error of shell return 1, it will not print anything and the user will understand that no line started with that string in the file."
},
{
"code": null,
"e": 27841,
"s": 27682,
"text": "#!/bin/bash\n\nread -p \"Enter the file name : \" file\nread -p \"Enter the string to search for in the file : \" str\n\ngrep \"^$str\" $file | { grep -v grep || true; }"
},
{
"code": null,
"e": 27909,
"s": 27841,
"text": "using the grep command to search for strings at the start of lines."
},
{
"code": null,
"e": 28174,
"s": 27909,
"text": "The grep command is also a bit flexible as it allows us to print the line numbers as well. We can print the line numbers by adding some arguments to the above command. The -n argument after grep will print the line number in which the string is found in the file. "
},
{
"code": null,
"e": 28336,
"s": 28174,
"text": "#!/bin/bash\n\nread -p \"Enter the file name : \" file\nread -p \"Enter the string to search for in the file : \" str\n\ngrep -n \"^$str\" $file | { grep -v grep || true; }"
},
{
"code": null,
"e": 28427,
"s": 28336,
"text": "using the grep command to search for strings at the start of lines and print line numbers."
},
{
"code": null,
"e": 28568,
"s": 28427,
"text": "Both the cases in grep will be case-sensitive. To make the search case insensitive, you can add in the argument -i just after the grep like,"
},
{
"code": null,
"e": 28618,
"s": 28568,
"text": "grep -i \"^$str\" $file | { grep -v grep || true; }"
},
{
"code": null,
"e": 28695,
"s": 28618,
"text": "using grep command to search case insensitive strings at the start of lines."
},
{
"code": null,
"e": 28723,
"s": 28695,
"text": "Method 2: Using SED Command"
},
{
"code": null,
"e": 29381,
"s": 28723,
"text": "The sed command is different than the grep command as it is a stream editor and not a command to just pass in arguments. We need to use -n so that the command doesn’t print everything from the file provided in the last argument of the command below. The following regex will search for the string variable and print all the matched lines. And the result will be compact output. The regex used is simple and similar to grep as it matches the string only at the beginning of the line using the ^ operator and backslashes mean the expression is a regex. The p argument will print the lines which match the regex. Both the cases in grep will be case-sensitive. "
},
{
"code": null,
"e": 29517,
"s": 29381,
"text": "#!/bin/bash\n\nread -p \"Enter the file name : \" file\nread -p \"Enter the string to search for in the file : \" str\n\nsed -n \"/^$str/p\" $file"
},
{
"code": null,
"e": 29580,
"s": 29517,
"text": "using sed command to search for strings at the start of lines."
},
{
"code": null,
"e": 29703,
"s": 29580,
"text": "The gnu sed doesn’t support case-insensitive searches or matches. Still, you can use Perl to add case-insensitive matches."
},
{
"code": null,
"e": 29731,
"s": 29703,
"text": "Method 3: Using AWK Command"
},
{
"code": null,
"e": 30061,
"s": 29731,
"text": "The regex for the AWK command is also the same and does the same thing in its own command style. The regex is almost similar to the sed command, which searches for the string variable, in the beginning, using the ^ operator and then simply prints the matched lines from the command. Both the cases in grep will be case-sensitive."
},
{
"code": null,
"e": 30200,
"s": 30061,
"text": "#!/bin/bash\n\nread -p \"Enter the file name : \" file\nread -p \"Enter the string to search for in the file : \" str\n\nawk \"/^$str/{print}\" $file"
},
{
"code": null,
"e": 30267,
"s": 30200,
"text": "using the awk command to search for strings at the start of lines."
},
{
"code": null,
"e": 30358,
"s": 30267,
"text": "To make the search in awk case insensitive, you can make some changes to the same command."
},
{
"code": null,
"e": 30408,
"s": 30358,
"text": "awk \"BEGIN {IGNORECASE = 1} /^$str/{print}\" $file"
},
{
"code": null,
"e": 30492,
"s": 30408,
"text": "using the awk command to search for case insensitive strings at the start of lines."
},
{
"code": null,
"e": 30639,
"s": 30492,
"text": "The awk command has some inbuilt functions which set the arguments as default to case sensitive, we can change the properties of the awk commands."
},
{
"code": null,
"e": 30670,
"s": 30639,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 30677,
"s": 30670,
"text": "Picked"
},
{
"code": null,
"e": 30690,
"s": 30677,
"text": "Shell Script"
},
{
"code": null,
"e": 30701,
"s": 30690,
"text": "Linux-Unix"
},
{
"code": null,
"e": 30799,
"s": 30701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30834,
"s": 30799,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 30860,
"s": 30834,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30894,
"s": 30860,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 30923,
"s": 30894,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 30960,
"s": 30923,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 30997,
"s": 30960,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 31039,
"s": 30997,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 31065,
"s": 31039,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 31101,
"s": 31065,
"text": "uniq Command in LINUX with examples"
}
] |
Introduction to PySpark | Distributed Computing with Apache Spark - GeeksforGeeks
|
29 Apr, 2022
Datasets are becoming huge. Infact, data is growing faster than processing speeds. Therefore, algorithms involving large data and high amount of computation are often run on a distributed computing system. A distributed computing system involves nodes (networked computers) that run processes in parallel and communicate (if, necessary).
MapReduce – The programming model that is used for Distributed computing is known as MapReduce. The MapReduce model involves two stages, Map and Reduce.
Map – The mapper processes each line of the input data (it is in the form of a file), and produces key – value pairs.Input data → Mapper → list([key, value])Reduce – The reducer processes the list of key – value pairs (after the Mapper’s function). It outputs a new set of key – value pairs.list([key, value]) → Reducer → list([key, list(values)])
Map – The mapper processes each line of the input data (it is in the form of a file), and produces key – value pairs.Input data → Mapper → list([key, value])
Input data → Mapper → list([key, value])
Reduce – The reducer processes the list of key – value pairs (after the Mapper’s function). It outputs a new set of key – value pairs.list([key, value]) → Reducer → list([key, list(values)])
list([key, value]) → Reducer → list([key, list(values)])
Spark – Spark (open source Big-Data processing engine by Apache) is a cluster computing system. It is faster as compared to other cluster computing systems (such as, Hadoop). It provides high level APIs in Python, Scala, and Java. Parallel jobs are easy to write in Spark. We will cover PySpark (Python + Apache Spark), because this will make the learning curve flatter. To install Spark on a linux system, follow this. To run Spark in a multi – cluster system, follow this. We will see how to create RDDs (fundamental data structure of Spark).
RDDs (Resilient Distributed Datasets) – RDDs are immutable collection of objects. Since we are using PySpark, these objects can be of multiple types. These will become more clear further.
SparkContext – For creating a standalone application in Spark, we first define a SparkContext –
from pyspark import SparkConf, SparkContextconf = SparkConf().setMaster("local").setAppName("Test")# setMaster(local) - we are doing tasks on a single machinesc = SparkContext(conf = conf)
RDD transformations – Now, a SparkContext object is created. Now, we will create RDDs and see some transformations on them.
# create an RDD called lines from ‘file_name.txt’lines = sc.textFile("file_name.txt", 2) # print lines.collect() prints the whole RDDprint lines.collect()
One major advantage of using Spark is that it does not load the dataset into memory, lines is a pointer to the ‘file_name.txt’ ?file.
A simple PySpark app to count the degree of each vertex for a given graph –
from pyspark import SparkConf, SparkContextconf = SparkConf().setMaster("local").setAppName("Test")# setMaster(local) - we are doing tasks on a single machinesc = SparkContext(conf = conf)def conv(line): line = line.split() return (int(line[0]), [int(line[1])])def numNeighbours(x, y): return len(x) + len(y)lines = sc.textFile('graph.txt')edges = lines.map(lambda line: conv(line))Adj_list = edges.reduceByKey(lambda x, y: numNeighbours(x, y))print Adj_list.collect()
Understanding the above code –
Our text file is in the following format – (each line represents an edge of a directed graph)1 21 32 33 4. .. .. .PySparkLarge Datasets may contain millions of nodes, and edges.First few lines set up the SparkContext. We create an RDD lines from it.Then, we transform the lines RDD to edges RDD.The function conv acts on each line and key value pairs of the form (1, 2), (1, 3), (2, 3), (3, 4), ... are stored in the edges RDD.After this the reduceByKey aggregates all the key – pairs corresponding to a particular key and numNeighbours function is used for generating each vertex’s degree in a separate RDD Adj_list, which has the form (1, 2), (2, 1), (3, 1), ...
Our text file is in the following format – (each line represents an edge of a directed graph)1 21 32 33 4. .. .. .PySpark
Large Datasets may contain millions of nodes, and edges.
First few lines set up the SparkContext. We create an RDD lines from it.
Then, we transform the lines RDD to edges RDD.The function conv acts on each line and key value pairs of the form (1, 2), (1, 3), (2, 3), (3, 4), ... are stored in the edges RDD.
After this the reduceByKey aggregates all the key – pairs corresponding to a particular key and numNeighbours function is used for generating each vertex’s degree in a separate RDD Adj_list, which has the form (1, 2), (2, 1), (3, 1), ...
Running the code –
The above code can be run by the following commands –$ cd /home/arik/Downloads/spark-1.6.0/
$ ./bin/spark-submit degree.py
You can use your Spark installation path in the first line.
The above code can be run by the following commands –$ cd /home/arik/Downloads/spark-1.6.0/
$ ./bin/spark-submit degree.py
$ cd /home/arik/Downloads/spark-1.6.0/
$ ./bin/spark-submit degree.py
You can use your Spark installation path in the first line.
We will see more on, how to run MapReduce tasks in a cluster of machines using Spark, and also go through other MapReduce tasks.
References –
http://lintool.github.io/SparkTutorial/https://spark.apache.org/
http://lintool.github.io/SparkTutorial/
https://spark.apache.org/
This article is contributed by Arik Pamnani. 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.
simmytarika5
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
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ?
|
[
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 26507,
"s": 26169,
"text": "Datasets are becoming huge. Infact, data is growing faster than processing speeds. Therefore, algorithms involving large data and high amount of computation are often run on a distributed computing system. A distributed computing system involves nodes (networked computers) that run processes in parallel and communicate (if, necessary)."
},
{
"code": null,
"e": 26660,
"s": 26507,
"text": "MapReduce – The programming model that is used for Distributed computing is known as MapReduce. The MapReduce model involves two stages, Map and Reduce."
},
{
"code": null,
"e": 27008,
"s": 26660,
"text": "Map – The mapper processes each line of the input data (it is in the form of a file), and produces key – value pairs.Input data → Mapper → list([key, value])Reduce – The reducer processes the list of key – value pairs (after the Mapper’s function). It outputs a new set of key – value pairs.list([key, value]) → Reducer → list([key, list(values)])"
},
{
"code": null,
"e": 27166,
"s": 27008,
"text": "Map – The mapper processes each line of the input data (it is in the form of a file), and produces key – value pairs.Input data → Mapper → list([key, value])"
},
{
"code": null,
"e": 27207,
"s": 27166,
"text": "Input data → Mapper → list([key, value])"
},
{
"code": null,
"e": 27398,
"s": 27207,
"text": "Reduce – The reducer processes the list of key – value pairs (after the Mapper’s function). It outputs a new set of key – value pairs.list([key, value]) → Reducer → list([key, list(values)])"
},
{
"code": null,
"e": 27455,
"s": 27398,
"text": "list([key, value]) → Reducer → list([key, list(values)])"
},
{
"code": null,
"e": 28000,
"s": 27455,
"text": "Spark – Spark (open source Big-Data processing engine by Apache) is a cluster computing system. It is faster as compared to other cluster computing systems (such as, Hadoop). It provides high level APIs in Python, Scala, and Java. Parallel jobs are easy to write in Spark. We will cover PySpark (Python + Apache Spark), because this will make the learning curve flatter. To install Spark on a linux system, follow this. To run Spark in a multi – cluster system, follow this. We will see how to create RDDs (fundamental data structure of Spark)."
},
{
"code": null,
"e": 28188,
"s": 28000,
"text": "RDDs (Resilient Distributed Datasets) – RDDs are immutable collection of objects. Since we are using PySpark, these objects can be of multiple types. These will become more clear further."
},
{
"code": null,
"e": 28284,
"s": 28188,
"text": "SparkContext – For creating a standalone application in Spark, we first define a SparkContext –"
},
{
"code": "from pyspark import SparkConf, SparkContextconf = SparkConf().setMaster(\"local\").setAppName(\"Test\")# setMaster(local) - we are doing tasks on a single machinesc = SparkContext(conf = conf)",
"e": 28473,
"s": 28284,
"text": null
},
{
"code": null,
"e": 28597,
"s": 28473,
"text": "RDD transformations – Now, a SparkContext object is created. Now, we will create RDDs and see some transformations on them."
},
{
"code": "# create an RDD called lines from ‘file_name.txt’lines = sc.textFile(\"file_name.txt\", 2) # print lines.collect() prints the whole RDDprint lines.collect()",
"e": 28753,
"s": 28597,
"text": null
},
{
"code": null,
"e": 28887,
"s": 28753,
"text": "One major advantage of using Spark is that it does not load the dataset into memory, lines is a pointer to the ‘file_name.txt’ ?file."
},
{
"code": null,
"e": 28963,
"s": 28887,
"text": "A simple PySpark app to count the degree of each vertex for a given graph –"
},
{
"code": "from pyspark import SparkConf, SparkContextconf = SparkConf().setMaster(\"local\").setAppName(\"Test\")# setMaster(local) - we are doing tasks on a single machinesc = SparkContext(conf = conf)def conv(line): line = line.split() return (int(line[0]), [int(line[1])])def numNeighbours(x, y): return len(x) + len(y)lines = sc.textFile('graph.txt')edges = lines.map(lambda line: conv(line))Adj_list = edges.reduceByKey(lambda x, y: numNeighbours(x, y))print Adj_list.collect()",
"e": 29441,
"s": 28963,
"text": null
},
{
"code": null,
"e": 29472,
"s": 29441,
"text": "Understanding the above code –"
},
{
"code": null,
"e": 30158,
"s": 29472,
"text": "Our text file is in the following format – (each line represents an edge of a directed graph)1 21 32 33 4. .. .. .PySparkLarge Datasets may contain millions of nodes, and edges.First few lines set up the SparkContext. We create an RDD lines from it.Then, we transform the lines RDD to edges RDD.The function conv acts on each line and key value pairs of the form (1, 2), (1, 3), (2, 3), (3, 4), ... are stored in the edges RDD.After this the reduceByKey aggregates all the key – pairs corresponding to a particular key and numNeighbours function is used for generating each vertex’s degree in a separate RDD Adj_list, which has the form (1, 2), (2, 1), (3, 1), ..."
},
{
"code": null,
"e": 30301,
"s": 30158,
"text": "Our text file is in the following format – (each line represents an edge of a directed graph)1 21 32 33 4. .. .. .PySpark"
},
{
"code": null,
"e": 30358,
"s": 30301,
"text": "Large Datasets may contain millions of nodes, and edges."
},
{
"code": null,
"e": 30431,
"s": 30358,
"text": "First few lines set up the SparkContext. We create an RDD lines from it."
},
{
"code": null,
"e": 30610,
"s": 30431,
"text": "Then, we transform the lines RDD to edges RDD.The function conv acts on each line and key value pairs of the form (1, 2), (1, 3), (2, 3), (3, 4), ... are stored in the edges RDD."
},
{
"code": null,
"e": 30848,
"s": 30610,
"text": "After this the reduceByKey aggregates all the key – pairs corresponding to a particular key and numNeighbours function is used for generating each vertex’s degree in a separate RDD Adj_list, which has the form (1, 2), (2, 1), (3, 1), ..."
},
{
"code": null,
"e": 30867,
"s": 30848,
"text": "Running the code –"
},
{
"code": null,
"e": 31050,
"s": 30867,
"text": "The above code can be run by the following commands –$ cd /home/arik/Downloads/spark-1.6.0/\n$ ./bin/spark-submit degree.py\nYou can use your Spark installation path in the first line."
},
{
"code": null,
"e": 31174,
"s": 31050,
"text": "The above code can be run by the following commands –$ cd /home/arik/Downloads/spark-1.6.0/\n$ ./bin/spark-submit degree.py\n"
},
{
"code": null,
"e": 31245,
"s": 31174,
"text": "$ cd /home/arik/Downloads/spark-1.6.0/\n$ ./bin/spark-submit degree.py\n"
},
{
"code": null,
"e": 31305,
"s": 31245,
"text": "You can use your Spark installation path in the first line."
},
{
"code": null,
"e": 31434,
"s": 31305,
"text": "We will see more on, how to run MapReduce tasks in a cluster of machines using Spark, and also go through other MapReduce tasks."
},
{
"code": null,
"e": 31447,
"s": 31434,
"text": "References –"
},
{
"code": null,
"e": 31512,
"s": 31447,
"text": "http://lintool.github.io/SparkTutorial/https://spark.apache.org/"
},
{
"code": null,
"e": 31552,
"s": 31512,
"text": "http://lintool.github.io/SparkTutorial/"
},
{
"code": null,
"e": 31578,
"s": 31552,
"text": "https://spark.apache.org/"
},
{
"code": null,
"e": 31874,
"s": 31578,
"text": "This article is contributed by Arik Pamnani. 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."
},
{
"code": null,
"e": 31999,
"s": 31874,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32012,
"s": 31999,
"text": "simmytarika5"
},
{
"code": null,
"e": 32029,
"s": 32012,
"text": "Web Technologies"
},
{
"code": null,
"e": 32127,
"s": 32029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32167,
"s": 32127,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32212,
"s": 32167,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32255,
"s": 32212,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32316,
"s": 32255,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32388,
"s": 32316,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 32443,
"s": 32388,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 32488,
"s": 32443,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 32529,
"s": 32488,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 32553,
"s": 32529,
"text": "REST API (Introduction)"
}
] |
Background local notifications in Flutter - GeeksforGeeks
|
15 Aug, 2021
Sometimes user wants some very important features like the latest news updates, latest articles updates, weather condition alert, complete his/her profile update, future events update and much more in his/ her Android or iOS device without opening App and if you would like to develop this kind of Android and iOS application then this article will help you to do so. In this process, we set up background jobs that periodically check update about the latest events or alert.
It is an open-source UI software development toolkit created by Google. It comes in handy while developing applications for Android, Mac, Windows, Google Fuchsia, iOS, Linux, and the web through a single codebase.
It is a client-optimized programming language for apps on multiple platforms. It is used to developed mobile, desktop, server, and web applications. Dart is an object-oriented language that also has garbage-collection property and has a syntax similar to the C programming language. It can compile in both native code or JavaScript.
It is used as a wrapper around the Android’s WorkManager and also the iOS performFetchWithCompletionHandler, which effectively enables the headless execution of Dart code in the background. WorkManager provides an easy-to-use API where we can define a background job that should run once, or periodically, apply multiple constraints like for example if a task needs an internet connection, or if the battery should be fully charged, and much more.
It is a cross-platform plugin for displaying local notifications in a flutter application. It offers a bunch of features like for example scheduling when notifications should appear, periodically show a notification (interval-based), handle when a user has tapped on a notification when the app is in the foreground, background, or terminated, specify a custom notification sound and much more.
It is the official integrated development environment(IDE) for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development, and this hole representation of Android Studio will be used as IDE.
Here, We are creating background jobs with headless execution. To get started we need to install certain flutter plugins and Android Studio must be installed in the local system.
Before getting started Flutter development toolkit in the local system and Flutter plugin in Android Studio IDE must be installed.
Open Android Studio and create a new flutter application project with a name called ‘geeksforgeeks’.
Once the project is created and sync successfully, connect your Android device to Android Studio and make sure Developer options and USB debugging are On.
Run the project by clicking on the first green icon at the center top to cross-check the project is built and running successfully(first time Android Studio takes a little more time as usual).
Now, It’s time to install the necessary plugins, open the ‘pubspec.yaml’ file from geeksforgeeks -> pubspec.yaml project structure and copy-paste two dependencies that are Workmanager and flutter_local_notifications as follows.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
# Use with the Workmanger class for background jobs headless execution.
workmanager: ^0.2.3
# Use with FlutterLocalNotificationsPlugin class for local push notifications.
flutter_local_notifications: ^1.4.4+2
Once, you have done the above steps then click on ‘Packages get’ flutter command appearing at the center top to get install all necessary packages and plugins.
Now, It’s time to add some required permissions, open the ‘AndroidManifest.xml’ file from geeksforgeeks -> android -> app -> src -> main -> AndroidManifest.xml project directory structure and copy-paste following permissions.
<!-- Add below permission inside 'manifest' tag -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- Add below permission inside 'application' tag -->
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
Now, It is time to code, open ‘main.dart’ file from geeksforgeeks -> lib -> main.dart project directory structure and copy-paste following the entire code.
Dart
import 'package:flutter/material.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:workmanager/workmanager.dart'; void main() { // needed if you intend to initialize in the `main` function WidgetsFlutterBinding.ensureInitialized(); Workmanager().initialize( // The top level function, aka callbackDispatcher callbackDispatcher, // If enabled it will post a notification whenever // the task is running. Handy for debugging tasks isInDebugMode: true ); // Periodic task registration Workmanager().registerPeriodicTask( "2", //This is the value that will be // returned in the callbackDispatcher "simplePeriodicTask", // When no frequency is provided // the default 15 minutes is set. // Minimum frequency is 15 min. // Android will automatically change // your frequency to 15 min // if you have configured a lower frequency. frequency: Duration(minutes: 15), ); runApp(MyApp());} void callbackDispatcher() { Workmanager().executeTask((task, inputData) { // initialise the plugin of flutterlocalnotifications. FlutterLocalNotificationsPlugin flip = new FlutterLocalNotificationsPlugin(); // app_icon needs to be a added as a drawable // resource to the Android head project. var android = new AndroidInitializationSettings('@mipmap/ic_launcher'); var IOS = new IOSInitializationSettings(); // initialise settings for both Android and iOS device. var settings = new InitializationSettings(android, IOS); flip.initialize(settings); _showNotificationWithDefaultSound(flip); return Future.value(true); });} Future _showNotificationWithDefaultSound(flip) async { // Show a notification after every 15 minute with the first // appearance happening a minute after invoking the method var androidPlatformChannelSpecifics = new AndroidNotificationDetails( 'your channel id', 'your channel name', 'your channel description', importance: Importance.Max, priority: Priority.High ); var iOSPlatformChannelSpecifics = new IOSNotificationDetails(); // initialise channel platform for both Android and iOS device. var platformChannelSpecifics = new NotificationDetails( androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics ); await flip.show(0, 'GeeksforGeeks', 'Your are one step away to connect with GeeksforGeeks', platformChannelSpecifics, payload: 'Default_Sound' );} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Geeks Demo', theme: ThemeData( // This is the theme // of your application. primarySwatch: Colors.green, ), home: HomePage(title: "GeeksforGeeks"), ); }} class HomePage extends StatefulWidget { HomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. // It is stateful, meaning // that it has a State object (defined below) // that contains fields that affect // how it looks. // This class is the configuration for the state. // It holds the values (in this // case the title) provided by the parent // (in this case the App widget) and // used by the build method of the State. // Fields in a Widget subclass are // always marked "final". final String title; @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { // This method is rerun every time setState is called. // The Flutter framework has been optimized // to make rerunning build methods // fast, so that you can just rebuild // anything that needs updating rather // than having to individually change //instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from // the MyHomePage object that was created by // the App.build method, and use it // to set our appbar title. title: Text(widget.title), ), body: new Container(), ); }}
Finally, Run the project by clicking on the first green icon at the center top to see the output, and your job gets done.
Output:
References:
https://pub.dev/packages/flutter_local_notifications/example
https://pub.dev/packages/workmanager/example
latchmepersad
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
|
[
{
"code": null,
"e": 27183,
"s": 27155,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 27659,
"s": 27183,
"text": "Sometimes user wants some very important features like the latest news updates, latest articles updates, weather condition alert, complete his/her profile update, future events update and much more in his/ her Android or iOS device without opening App and if you would like to develop this kind of Android and iOS application then this article will help you to do so. In this process, we set up background jobs that periodically check update about the latest events or alert."
},
{
"code": null,
"e": 27873,
"s": 27659,
"text": "It is an open-source UI software development toolkit created by Google. It comes in handy while developing applications for Android, Mac, Windows, Google Fuchsia, iOS, Linux, and the web through a single codebase."
},
{
"code": null,
"e": 28206,
"s": 27873,
"text": "It is a client-optimized programming language for apps on multiple platforms. It is used to developed mobile, desktop, server, and web applications. Dart is an object-oriented language that also has garbage-collection property and has a syntax similar to the C programming language. It can compile in both native code or JavaScript."
},
{
"code": null,
"e": 28654,
"s": 28206,
"text": "It is used as a wrapper around the Android’s WorkManager and also the iOS performFetchWithCompletionHandler, which effectively enables the headless execution of Dart code in the background. WorkManager provides an easy-to-use API where we can define a background job that should run once, or periodically, apply multiple constraints like for example if a task needs an internet connection, or if the battery should be fully charged, and much more."
},
{
"code": null,
"e": 29049,
"s": 28654,
"text": "It is a cross-platform plugin for displaying local notifications in a flutter application. It offers a bunch of features like for example scheduling when notifications should appear, periodically show a notification (interval-based), handle when a user has tapped on a notification when the app is in the foreground, background, or terminated, specify a custom notification sound and much more."
},
{
"code": null,
"e": 29309,
"s": 29049,
"text": "It is the official integrated development environment(IDE) for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development, and this hole representation of Android Studio will be used as IDE."
},
{
"code": null,
"e": 29488,
"s": 29309,
"text": "Here, We are creating background jobs with headless execution. To get started we need to install certain flutter plugins and Android Studio must be installed in the local system."
},
{
"code": null,
"e": 29620,
"s": 29488,
"text": "Before getting started Flutter development toolkit in the local system and Flutter plugin in Android Studio IDE must be installed."
},
{
"code": null,
"e": 29721,
"s": 29620,
"text": "Open Android Studio and create a new flutter application project with a name called ‘geeksforgeeks’."
},
{
"code": null,
"e": 29876,
"s": 29721,
"text": "Once the project is created and sync successfully, connect your Android device to Android Studio and make sure Developer options and USB debugging are On."
},
{
"code": null,
"e": 30069,
"s": 29876,
"text": "Run the project by clicking on the first green icon at the center top to cross-check the project is built and running successfully(first time Android Studio takes a little more time as usual)."
},
{
"code": null,
"e": 30297,
"s": 30069,
"text": "Now, It’s time to install the necessary plugins, open the ‘pubspec.yaml’ file from geeksforgeeks -> pubspec.yaml project structure and copy-paste two dependencies that are Workmanager and flutter_local_notifications as follows."
},
{
"code": null,
"e": 30711,
"s": 30297,
"text": "dependencies:\n flutter:\n sdk: flutter\n\n # The following adds the Cupertino Icons font to your application.\n # Use with the CupertinoIcons class for iOS style icons.\n cupertino_icons: ^0.1.2\n # Use with the Workmanger class for background jobs headless execution.\n workmanager: ^0.2.3\n # Use with FlutterLocalNotificationsPlugin class for local push notifications.\n flutter_local_notifications: ^1.4.4+2"
},
{
"code": null,
"e": 30871,
"s": 30711,
"text": "Once, you have done the above steps then click on ‘Packages get’ flutter command appearing at the center top to get install all necessary packages and plugins."
},
{
"code": null,
"e": 31097,
"s": 30871,
"text": "Now, It’s time to add some required permissions, open the ‘AndroidManifest.xml’ file from geeksforgeeks -> android -> app -> src -> main -> AndroidManifest.xml project directory structure and copy-paste following permissions."
},
{
"code": null,
"e": 31578,
"s": 31097,
"text": "<!-- Add below permission inside 'manifest' tag -->\n<uses-permission android:name=\"android.permission.RECEIVE_BOOT_COMPLETED\"/>\n<!-- Add below permission inside 'application' tag -->\n<receiver android:name=\"com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver\">\n <intent-filter>\n <action android:name=\"android.intent.action.BOOT_COMPLETED\"/>\n <action android:name=\"android.intent.action.MY_PACKAGE_REPLACED\"/>\n </intent-filter>\n</receiver>"
},
{
"code": null,
"e": 31734,
"s": 31578,
"text": "Now, It is time to code, open ‘main.dart’ file from geeksforgeeks -> lib -> main.dart project directory structure and copy-paste following the entire code."
},
{
"code": null,
"e": 31739,
"s": 31734,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:workmanager/workmanager.dart'; void main() { // needed if you intend to initialize in the `main` function WidgetsFlutterBinding.ensureInitialized(); Workmanager().initialize( // The top level function, aka callbackDispatcher callbackDispatcher, // If enabled it will post a notification whenever // the task is running. Handy for debugging tasks isInDebugMode: true ); // Periodic task registration Workmanager().registerPeriodicTask( \"2\", //This is the value that will be // returned in the callbackDispatcher \"simplePeriodicTask\", // When no frequency is provided // the default 15 minutes is set. // Minimum frequency is 15 min. // Android will automatically change // your frequency to 15 min // if you have configured a lower frequency. frequency: Duration(minutes: 15), ); runApp(MyApp());} void callbackDispatcher() { Workmanager().executeTask((task, inputData) { // initialise the plugin of flutterlocalnotifications. FlutterLocalNotificationsPlugin flip = new FlutterLocalNotificationsPlugin(); // app_icon needs to be a added as a drawable // resource to the Android head project. var android = new AndroidInitializationSettings('@mipmap/ic_launcher'); var IOS = new IOSInitializationSettings(); // initialise settings for both Android and iOS device. var settings = new InitializationSettings(android, IOS); flip.initialize(settings); _showNotificationWithDefaultSound(flip); return Future.value(true); });} Future _showNotificationWithDefaultSound(flip) async { // Show a notification after every 15 minute with the first // appearance happening a minute after invoking the method var androidPlatformChannelSpecifics = new AndroidNotificationDetails( 'your channel id', 'your channel name', 'your channel description', importance: Importance.Max, priority: Priority.High ); var iOSPlatformChannelSpecifics = new IOSNotificationDetails(); // initialise channel platform for both Android and iOS device. var platformChannelSpecifics = new NotificationDetails( androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics ); await flip.show(0, 'GeeksforGeeks', 'Your are one step away to connect with GeeksforGeeks', platformChannelSpecifics, payload: 'Default_Sound' );} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Geeks Demo', theme: ThemeData( // This is the theme // of your application. primarySwatch: Colors.green, ), home: HomePage(title: \"GeeksforGeeks\"), ); }} class HomePage extends StatefulWidget { HomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. // It is stateful, meaning // that it has a State object (defined below) // that contains fields that affect // how it looks. // This class is the configuration for the state. // It holds the values (in this // case the title) provided by the parent // (in this case the App widget) and // used by the build method of the State. // Fields in a Widget subclass are // always marked \"final\". final String title; @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { // This method is rerun every time setState is called. // The Flutter framework has been optimized // to make rerunning build methods // fast, so that you can just rebuild // anything that needs updating rather // than having to individually change //instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from // the MyHomePage object that was created by // the App.build method, and use it // to set our appbar title. title: Text(widget.title), ), body: new Container(), ); }}",
"e": 35951,
"s": 31739,
"text": null
},
{
"code": null,
"e": 36073,
"s": 35951,
"text": "Finally, Run the project by clicking on the first green icon at the center top to see the output, and your job gets done."
},
{
"code": null,
"e": 36082,
"s": 36073,
"text": "Output: "
},
{
"code": null,
"e": 36094,
"s": 36082,
"text": "References:"
},
{
"code": null,
"e": 36155,
"s": 36094,
"text": "https://pub.dev/packages/flutter_local_notifications/example"
},
{
"code": null,
"e": 36200,
"s": 36155,
"text": "https://pub.dev/packages/workmanager/example"
},
{
"code": null,
"e": 36214,
"s": 36200,
"text": "latchmepersad"
},
{
"code": null,
"e": 36219,
"s": 36214,
"text": "Dart"
},
{
"code": null,
"e": 36227,
"s": 36219,
"text": "Flutter"
},
{
"code": null,
"e": 36325,
"s": 36227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36357,
"s": 36325,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 36385,
"s": 36357,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 36407,
"s": 36385,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 36432,
"s": 36407,
"text": "Splash Screen in Flutter"
},
{
"code": null,
"e": 36471,
"s": 36432,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36503,
"s": 36471,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 36542,
"s": 36503,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36568,
"s": 36542,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 36594,
"s": 36568,
"text": "Flutter - Flexible Widget"
}
] |
Lodash _.minBy() Method - GeeksforGeeks
|
02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.minBy() method is used to compute the minimum value from the original array by iterating over each element in the array using the Iteratee function. It is almost the same as _.min() function.
Syntax:
_.minBy( array, [iteratee = _.identity] )
Parameters: This method accepts two parameters as mentioned above and described below:
array: It is the array that the method iterates over to get the minimum element.
iteratee: It is the function that is invoked for every element in the array.
Return Value: This method returns the minimum element.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }]; // Use of _.minBy() method let min_val = _.minBy(arr, function(o) { return o.n; }); // Printing the output console.log(min_val);
Output:
{ 'n': 2 }
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Original array var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }]; // Use of _.minBy() method let min_val = _.minBy(arr, 'n'); // Printing the output console.log(min_val);
Output:
{ 'n': 3 }
JavaScript-Lodash
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 calculate the number of days between two dates in 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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 38681,
"s": 38653,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 38821,
"s": 38681,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 39019,
"s": 38821,
"text": "The _.minBy() method is used to compute the minimum value from the original array by iterating over each element in the array using the Iteratee function. It is almost the same as _.min() function."
},
{
"code": null,
"e": 39027,
"s": 39019,
"text": "Syntax:"
},
{
"code": null,
"e": 39070,
"s": 39027,
"text": "_.minBy( array, [iteratee = _.identity] )\n"
},
{
"code": null,
"e": 39157,
"s": 39070,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 39238,
"s": 39157,
"text": "array: It is the array that the method iterates over to get the minimum element."
},
{
"code": null,
"e": 39315,
"s": 39238,
"text": "iteratee: It is the function that is invoked for every element in the array."
},
{
"code": null,
"e": 39370,
"s": 39315,
"text": "Return Value: This method returns the minimum element."
},
{
"code": null,
"e": 39381,
"s": 39370,
"text": "Example 1:"
},
{
"code": null,
"e": 39392,
"s": 39381,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }]; // Use of _.minBy() method let min_val = _.minBy(arr, function(o) { return o.n; }); // Printing the output console.log(min_val);",
"e": 39666,
"s": 39392,
"text": null
},
{
"code": null,
"e": 39674,
"s": 39666,
"text": "Output:"
},
{
"code": null,
"e": 39686,
"s": 39674,
"text": "{ 'n': 2 }\n"
},
{
"code": null,
"e": 39699,
"s": 39686,
"text": "Example 2: "
},
{
"code": null,
"e": 39710,
"s": 39699,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }]; // Use of _.minBy() method let min_val = _.minBy(arr, 'n'); // Printing the output console.log(min_val);",
"e": 39983,
"s": 39710,
"text": null
},
{
"code": null,
"e": 39991,
"s": 39983,
"text": "Output:"
},
{
"code": null,
"e": 40003,
"s": 39991,
"text": "{ 'n': 3 }\n"
},
{
"code": null,
"e": 40021,
"s": 40003,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 40032,
"s": 40021,
"text": "JavaScript"
},
{
"code": null,
"e": 40049,
"s": 40032,
"text": "Web Technologies"
},
{
"code": null,
"e": 40147,
"s": 40049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40187,
"s": 40147,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40232,
"s": 40187,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40293,
"s": 40232,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 40365,
"s": 40293,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 40434,
"s": 40365,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 40474,
"s": 40434,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40507,
"s": 40474,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40552,
"s": 40507,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40595,
"s": 40552,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Rearrange array to maximize sum of GCD of array elements with their respective indices - GeeksforGeeks
|
25 Jun, 2021
Given an array arr[] consisting of a permutation of first N natural numbers, the task is to find the maximum possible value of ΣGCD(arr[i], i) (1-based indexing) by rearranging the given array elements.
Examples:
Input: arr[] = { 2, 1} Output: 6 Explanation: Rearranging the given array to { 2, 1}. ΣGCD(arr[i], i) = GCD(arr[1], 1) + GCD(arr[2], 2) = GCD(2, 1) + GCD(1, 2)= 2 Rearranging the given array to { 1, 2 }. ΣGCD(arr[i], i) = GCD(arr[1], 1) + GCD(arr[2], 2) = GCD(1, 1) + GCD(2, 2) = 3 Therefore, the required output is 3
Input: arr[] = { 4, 5, 3, 2, 1 } Output: 15
Naive Approach: The simplest approach to solve the problem is to traverse the array and generate all possible permutations of the given array and for each permutation, find the value of ΣGCD(arr[i], i). Finally, print the maximum value of ΣGCD(arr[i], i) from each permutation.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arrayint findMaxValByRearrArr(int arr[], int N){ // Sort the array in // ascending order sort(arr, arr + N); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) int sum = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = max(res, sum); } while (next_permutation(arr, arr + N)); return res;} // Driver Codeint main(){ int arr[] = { 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); cout << findMaxValByRearrArr(arr, N); return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array static int findMaxValByRearrArr(int arr[], int N) { // Sort the array in // ascending order Arrays.sort(arr); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) int sum = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = Math.max(res, sum); } while (next_permutation(arr)); return res; } static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } // Driver Code public static void main(String[] args) { int arr[] = { 3, 2, 1 }; int N = arr.length; System.out.print(findMaxValByRearrArr(arr, N)); }} // This code is contributed by 29AjayKumar
# Python3 program to implement# the above approach # Function to find the maximum sum of# GCD(arr[i], i) by rearranging the arraydef findMaxValByRearrArr(arr, N): # Sort the array in # ascending order arr.sort() # Stores maximum sum of GCD(arr[i], i) # by rearranging the array elements res = 0 # Generate all possible # permutations of the array while (True): # Stores sum of GCD(arr[i], i) Sum = 0 # Traverse the array for i in range(N): # Update sum Sum += __gcd(i + 1, arr[i]) # Update res res = max(res, Sum) if (not next_permutation(arr)): break return res def __gcd(a, b): if b == 0: return a else: return __gcd(b, a % b) def next_permutation(p): for a in range(len(p) - 2, -1, -1): if (p[a] < p[a + 1]): b = len(p) - 1 while True: if (p[b] > p[a]): t = p[a] p[a] = p[b] p[b] = t a += 1 b = len(p) - 1 while a < b: t = p[a] p[a] = p[b] p[b] = t a += 1 b -= 1 return True b -= 1 return False # Driver code arr = [ 3, 2, 1 ]N = len(arr) print(findMaxValByRearrArr(arr, N)) # This code is contributed by divyesh072019
// C# program to implement// the above approachusing System;class GFG{ // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array static int findMaxValByRearrArr(int []arr, int N) { // Sort the array in // ascending order Array.Sort(arr); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) int sum = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = Math.Max(res, sum); } while (next_permutation(arr)); return res; } static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } static bool next_permutation(int[] p) { for (int a = p.Length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.Length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.Length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } // Driver Code public static void Main(String[] args) { int []arr = { 3, 2, 1 }; int N = arr.Length; Console.Write(findMaxValByRearrArr(arr, N)); }} // This code is contributed by 29AjayKumar
<script>// Javascript program to implement// the above approach // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array function findMaxValByRearrArr(arr, N) { // Sort the array in // ascending order arr.sort(); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements let res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) let sum = 0; // Traverse the array for (let i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = Math.max(res, sum); } while (next_permutation(arr)); return res; } function __gcd(a, b) { return b == 0? a:__gcd(b, a % b); } function next_permutation(p) { for (let a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (let b = p.length - 1;; --b) if (p[b] > p[a]) { let t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } // Driver Code let arr = [ 3, 2, 1 ]; let N = arr.length; document.write(findMaxValByRearrArr(arr, N)); // This code is contributed by souravghosh0416.</script>
6
Time Complexity: O(N!) Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
Maximum possible value of GCD(X, Y) = min(X, Y) Therefore, the maximum possible value of GCD(i, arr[i]) = min(i, arr[i]) If array is sorted then i = arr[i] and the value of GCD(i, arr[i]) = i ΣGCD(arr[i], i) = Σi = N * (N + 1) / 2
Follow the steps below to solve the problem:
Initialize a variable, say res, to store the maximum possible sum of ΣGCD(arr[i], i).
Update res = (N * (N + 1) / 2).
Finally, print the value of res.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arrayint findMaxValByRearrArr(int arr[], int N){ // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Update res res = (N * (N + 1)) / 2; return res;} // Driver Codeint main(){ int arr[] = { 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); cout << findMaxValByRearrArr(arr, N); return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arraystatic int findMaxValByRearrArr(int arr[], int N){ // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Update res res = (N * (N + 1)) / 2; return res;} // Driver Codepublic static void main(String[] args){ int arr[] = { 3, 2, 1 }; int N = arr.length; System.out.print(findMaxValByRearrArr(arr, N));}} // This code is contributed by shikhasingrajput
# Python program to implement# the above approach # Function to find the maximum sum of# GCD(arr[i], i) by rearranging the arraydef findMaxValByRearrArr(arr, N): # Stores maximum sum of GCD(arr[i], i) # by rearranging the array elements res = 0; # Update res res = (N * (N + 1)) // 2; return res; # Driver Codeif __name__ == '__main__': arr = [ 3, 2, 1 ]; N = len(arr); print(findMaxValByRearrArr(arr, N)); # This code contributed by shikhasingrajput
// C# program to implement// the above approachusing System; class GFG{ // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arraystatic int findMaxValByRearrArr(int []arr, int N){ // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Update res res = (N * (N + 1)) / 2; return res;} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 2, 1 }; int N = arr.Length; Console.Write(findMaxValByRearrArr(arr, N));}} // This code is contributed by shikhasingrajput
<script> // Javascript program to implement // the above approach // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array function findMaxValByRearrArr(arr, N) { // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements let res = 0; // Update res res = parseInt((N * (N + 1)) / 2, 10); return res; } let arr = [ 3, 2, 1 ]; let N = arr.length; document.write(findMaxValByRearrArr(arr, N)); </script>
6
Time Complexity: O(1) Auxiliary Space: O(1)
shikhasingrajput
29AjayKumar
divyesh072019
decode2207
souravghosh0416
surinderdawra388
array-rearrange
HCF
permutation
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
permutation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Linked List vs Array
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 26619,
"s": 26591,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 26822,
"s": 26619,
"text": "Given an array arr[] consisting of a permutation of first N natural numbers, the task is to find the maximum possible value of ΣGCD(arr[i], i) (1-based indexing) by rearranging the given array elements."
},
{
"code": null,
"e": 26832,
"s": 26822,
"text": "Examples:"
},
{
"code": null,
"e": 27150,
"s": 26832,
"text": "Input: arr[] = { 2, 1} Output: 6 Explanation: Rearranging the given array to { 2, 1}. ΣGCD(arr[i], i) = GCD(arr[1], 1) + GCD(arr[2], 2) = GCD(2, 1) + GCD(1, 2)= 2 Rearranging the given array to { 1, 2 }. ΣGCD(arr[i], i) = GCD(arr[1], 1) + GCD(arr[2], 2) = GCD(1, 1) + GCD(2, 2) = 3 Therefore, the required output is 3"
},
{
"code": null,
"e": 27194,
"s": 27150,
"text": "Input: arr[] = { 4, 5, 3, 2, 1 } Output: 15"
},
{
"code": null,
"e": 27472,
"s": 27194,
"text": "Naive Approach: The simplest approach to solve the problem is to traverse the array and generate all possible permutations of the given array and for each permutation, find the value of ΣGCD(arr[i], i). Finally, print the maximum value of ΣGCD(arr[i], i) from each permutation."
},
{
"code": null,
"e": 27523,
"s": 27472,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27527,
"s": 27523,
"text": "C++"
},
{
"code": null,
"e": 27532,
"s": 27527,
"text": "Java"
},
{
"code": null,
"e": 27540,
"s": 27532,
"text": "Python3"
},
{
"code": null,
"e": 27543,
"s": 27540,
"text": "C#"
},
{
"code": null,
"e": 27554,
"s": 27543,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arrayint findMaxValByRearrArr(int arr[], int N){ // Sort the array in // ascending order sort(arr, arr + N); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) int sum = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = max(res, sum); } while (next_permutation(arr, arr + N)); return res;} // Driver Codeint main(){ int arr[] = { 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); cout << findMaxValByRearrArr(arr, N); return 0;}",
"e": 28479,
"s": 27554,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array static int findMaxValByRearrArr(int arr[], int N) { // Sort the array in // ascending order Arrays.sort(arr); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) int sum = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = Math.max(res, sum); } while (next_permutation(arr)); return res; } static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } // Driver Code public static void main(String[] args) { int arr[] = { 3, 2, 1 }; int N = arr.length; System.out.print(findMaxValByRearrArr(arr, N)); }} // This code is contributed by 29AjayKumar",
"e": 29986,
"s": 28479,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to find the maximum sum of# GCD(arr[i], i) by rearranging the arraydef findMaxValByRearrArr(arr, N): # Sort the array in # ascending order arr.sort() # Stores maximum sum of GCD(arr[i], i) # by rearranging the array elements res = 0 # Generate all possible # permutations of the array while (True): # Stores sum of GCD(arr[i], i) Sum = 0 # Traverse the array for i in range(N): # Update sum Sum += __gcd(i + 1, arr[i]) # Update res res = max(res, Sum) if (not next_permutation(arr)): break return res def __gcd(a, b): if b == 0: return a else: return __gcd(b, a % b) def next_permutation(p): for a in range(len(p) - 2, -1, -1): if (p[a] < p[a + 1]): b = len(p) - 1 while True: if (p[b] > p[a]): t = p[a] p[a] = p[b] p[b] = t a += 1 b = len(p) - 1 while a < b: t = p[a] p[a] = p[b] p[b] = t a += 1 b -= 1 return True b -= 1 return False # Driver code arr = [ 3, 2, 1 ]N = len(arr) print(findMaxValByRearrArr(arr, N)) # This code is contributed by divyesh072019",
"e": 31640,
"s": 29986,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array static int findMaxValByRearrArr(int []arr, int N) { // Sort the array in // ascending order Array.Sort(arr); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) int sum = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = Math.Max(res, sum); } while (next_permutation(arr)); return res; } static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } static bool next_permutation(int[] p) { for (int a = p.Length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.Length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.Length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } // Driver Code public static void Main(String[] args) { int []arr = { 3, 2, 1 }; int N = arr.Length; Console.Write(findMaxValByRearrArr(arr, N)); }} // This code is contributed by 29AjayKumar",
"e": 33139,
"s": 31640,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array function findMaxValByRearrArr(arr, N) { // Sort the array in // ascending order arr.sort(); // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements let res = 0; // Generate all possible // permutations of the array do { // Stores sum of GCD(arr[i], i) let sum = 0; // Traverse the array for (let i = 0; i < N; i++) { // Update sum sum += __gcd(i + 1, arr[i]); } // Update res res = Math.max(res, sum); } while (next_permutation(arr)); return res; } function __gcd(a, b) { return b == 0? a:__gcd(b, a % b); } function next_permutation(p) { for (let a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (let b = p.length - 1;; --b) if (p[b] > p[a]) { let t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } // Driver Code let arr = [ 3, 2, 1 ]; let N = arr.length; document.write(findMaxValByRearrArr(arr, N)); // This code is contributed by souravghosh0416.</script>",
"e": 34563,
"s": 33139,
"text": null
},
{
"code": null,
"e": 34565,
"s": 34563,
"text": "6"
},
{
"code": null,
"e": 34612,
"s": 34567,
"text": "Time Complexity: O(N!) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34705,
"s": 34612,
"text": "Efficient Approach: The above approach can be optimized based on the following observations:"
},
{
"code": null,
"e": 34938,
"s": 34705,
"text": "Maximum possible value of GCD(X, Y) = min(X, Y) Therefore, the maximum possible value of GCD(i, arr[i]) = min(i, arr[i]) If array is sorted then i = arr[i] and the value of GCD(i, arr[i]) = i ΣGCD(arr[i], i) = Σi = N * (N + 1) / 2 "
},
{
"code": null,
"e": 34983,
"s": 34938,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 35069,
"s": 34983,
"text": "Initialize a variable, say res, to store the maximum possible sum of ΣGCD(arr[i], i)."
},
{
"code": null,
"e": 35101,
"s": 35069,
"text": "Update res = (N * (N + 1) / 2)."
},
{
"code": null,
"e": 35134,
"s": 35101,
"text": "Finally, print the value of res."
},
{
"code": null,
"e": 35185,
"s": 35134,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 35189,
"s": 35185,
"text": "C++"
},
{
"code": null,
"e": 35194,
"s": 35189,
"text": "Java"
},
{
"code": null,
"e": 35202,
"s": 35194,
"text": "Python3"
},
{
"code": null,
"e": 35205,
"s": 35202,
"text": "C#"
},
{
"code": null,
"e": 35216,
"s": 35205,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arrayint findMaxValByRearrArr(int arr[], int N){ // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Update res res = (N * (N + 1)) / 2; return res;} // Driver Codeint main(){ int arr[] = { 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); cout << findMaxValByRearrArr(arr, N); return 0;}",
"e": 35750,
"s": 35216,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arraystatic int findMaxValByRearrArr(int arr[], int N){ // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Update res res = (N * (N + 1)) / 2; return res;} // Driver Codepublic static void main(String[] args){ int arr[] = { 3, 2, 1 }; int N = arr.length; System.out.print(findMaxValByRearrArr(arr, N));}} // This code is contributed by shikhasingrajput",
"e": 36328,
"s": 35750,
"text": null
},
{
"code": "# Python program to implement# the above approach # Function to find the maximum sum of# GCD(arr[i], i) by rearranging the arraydef findMaxValByRearrArr(arr, N): # Stores maximum sum of GCD(arr[i], i) # by rearranging the array elements res = 0; # Update res res = (N * (N + 1)) // 2; return res; # Driver Codeif __name__ == '__main__': arr = [ 3, 2, 1 ]; N = len(arr); print(findMaxValByRearrArr(arr, N)); # This code contributed by shikhasingrajput",
"e": 36808,
"s": 36328,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the maximum sum of// GCD(arr[i], i) by rearranging the arraystatic int findMaxValByRearrArr(int []arr, int N){ // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements int res = 0; // Update res res = (N * (N + 1)) / 2; return res;} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 2, 1 }; int N = arr.Length; Console.Write(findMaxValByRearrArr(arr, N));}} // This code is contributed by shikhasingrajput",
"e": 37393,
"s": 36808,
"text": null
},
{
"code": "<script> // Javascript program to implement // the above approach // Function to find the maximum sum of // GCD(arr[i], i) by rearranging the array function findMaxValByRearrArr(arr, N) { // Stores maximum sum of GCD(arr[i], i) // by rearranging the array elements let res = 0; // Update res res = parseInt((N * (N + 1)) / 2, 10); return res; } let arr = [ 3, 2, 1 ]; let N = arr.length; document.write(findMaxValByRearrArr(arr, N)); </script>",
"e": 37928,
"s": 37393,
"text": null
},
{
"code": null,
"e": 37930,
"s": 37928,
"text": "6"
},
{
"code": null,
"e": 37976,
"s": 37932,
"text": "Time Complexity: O(1) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 37993,
"s": 37976,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 38005,
"s": 37993,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38019,
"s": 38005,
"text": "divyesh072019"
},
{
"code": null,
"e": 38030,
"s": 38019,
"text": "decode2207"
},
{
"code": null,
"e": 38046,
"s": 38030,
"text": "souravghosh0416"
},
{
"code": null,
"e": 38063,
"s": 38046,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38079,
"s": 38063,
"text": "array-rearrange"
},
{
"code": null,
"e": 38083,
"s": 38079,
"text": "HCF"
},
{
"code": null,
"e": 38095,
"s": 38083,
"text": "permutation"
},
{
"code": null,
"e": 38102,
"s": 38095,
"text": "Arrays"
},
{
"code": null,
"e": 38109,
"s": 38102,
"text": "Greedy"
},
{
"code": null,
"e": 38122,
"s": 38109,
"text": "Mathematical"
},
{
"code": null,
"e": 38129,
"s": 38122,
"text": "Arrays"
},
{
"code": null,
"e": 38136,
"s": 38129,
"text": "Greedy"
},
{
"code": null,
"e": 38149,
"s": 38136,
"text": "Mathematical"
},
{
"code": null,
"e": 38161,
"s": 38149,
"text": "permutation"
},
{
"code": null,
"e": 38259,
"s": 38161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38307,
"s": 38259,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 38339,
"s": 38307,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38353,
"s": 38339,
"text": "Linear Search"
},
{
"code": null,
"e": 38421,
"s": 38353,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 38442,
"s": 38421,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 38493,
"s": 38442,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 38544,
"s": 38493,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 38602,
"s": 38544,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 38662,
"s": 38602,
"text": "Write a program to print all permutations of a given string"
}
] |
How to find maximum string length by column in R DataFrame ? - GeeksforGeeks
|
30 May, 2021
In this article, we are going to see how to find maximum string length by column in R Programming Language.
To find the maximum string length by column in the given dataframe, first, nchar() function is called to get the length of all the string present in the particular column of the dataframe, and then the max() function must be called to get the maximum value of the length of the string generated by the nchar() function. The nchar() and the max() function are base functions of the R programming language, so there is no need to import any package.
nchar() function takes a character vector as an argument and returns a vector whose elements contain the sizes of the corresponding elements of x
Syntax:
nchar(x, type = “chars”, allowNA = FALSE, keepNA = NA)
Parameter:
x: character vector or a vector to be coerced to a character vector. Giving a factor is an error.
type:character string: partial matching to one of c(“bytes”, “chars”, “width”). See ‘Details’.
allowNA: logical, should NA be returned for invalid multibyte strings or “bytes”-encoded strings (rather than throwing an error)?
keepNA:logical: should NA be returned where ever x is NA?
max() function finds the maximum value among the data provided.
Syntax:
MAX(vector, rank = 1, value = FALSE, rank.adjust = TRUE, forceChoice = FALSE)
Parameter:
vector: Vector in which maximum/minimum element needs to be identified
rank:value(s) or rank(s) of maximum values.
value: Should value or rank be returned?
rank.adjust: If the maximum value of a range of ranks exceeds vector length, should this be adjusted?
forceChoice: In the case of ties, should all results be returned or only one?
Example1:
R
gfg_data <- data.frame(x = c("geeks", "for", "geeks"), y = c("I", "Love", "Coding"), z=c("R", "programming ", "language")) max(nchar(gfg_data$y))
Output:
[1] 6
Example 2:
R
gfg_data <- data.frame(x = c("geeks", "for", "geeks"), y = c("I", "Love", "Coding"), z=c("R", "programming ", "language")) max(nchar(gfg_data$z))
Output:
[1] 12
Picked
R DataFrame-Programs
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to import an Excel File into R ?
Plot mean and standard deviation using ggplot2 in R
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 26596,
"s": 26487,
"text": "In this article, we are going to see how to find maximum string length by column in R Programming Language. "
},
{
"code": null,
"e": 27044,
"s": 26596,
"text": "To find the maximum string length by column in the given dataframe, first, nchar() function is called to get the length of all the string present in the particular column of the dataframe, and then the max() function must be called to get the maximum value of the length of the string generated by the nchar() function. The nchar() and the max() function are base functions of the R programming language, so there is no need to import any package."
},
{
"code": null,
"e": 27190,
"s": 27044,
"text": "nchar() function takes a character vector as an argument and returns a vector whose elements contain the sizes of the corresponding elements of x"
},
{
"code": null,
"e": 27198,
"s": 27190,
"text": "Syntax:"
},
{
"code": null,
"e": 27253,
"s": 27198,
"text": "nchar(x, type = “chars”, allowNA = FALSE, keepNA = NA)"
},
{
"code": null,
"e": 27264,
"s": 27253,
"text": "Parameter:"
},
{
"code": null,
"e": 27362,
"s": 27264,
"text": "x: character vector or a vector to be coerced to a character vector. Giving a factor is an error."
},
{
"code": null,
"e": 27457,
"s": 27362,
"text": "type:character string: partial matching to one of c(“bytes”, “chars”, “width”). See ‘Details’."
},
{
"code": null,
"e": 27587,
"s": 27457,
"text": "allowNA: logical, should NA be returned for invalid multibyte strings or “bytes”-encoded strings (rather than throwing an error)?"
},
{
"code": null,
"e": 27645,
"s": 27587,
"text": "keepNA:logical: should NA be returned where ever x is NA?"
},
{
"code": null,
"e": 27709,
"s": 27645,
"text": "max() function finds the maximum value among the data provided."
},
{
"code": null,
"e": 27717,
"s": 27709,
"text": "Syntax:"
},
{
"code": null,
"e": 27795,
"s": 27717,
"text": "MAX(vector, rank = 1, value = FALSE, rank.adjust = TRUE, forceChoice = FALSE)"
},
{
"code": null,
"e": 27806,
"s": 27795,
"text": "Parameter:"
},
{
"code": null,
"e": 27877,
"s": 27806,
"text": "vector: Vector in which maximum/minimum element needs to be identified"
},
{
"code": null,
"e": 27921,
"s": 27877,
"text": "rank:value(s) or rank(s) of maximum values."
},
{
"code": null,
"e": 27963,
"s": 27921,
"text": "value: Should value or rank be returned?"
},
{
"code": null,
"e": 28065,
"s": 27963,
"text": "rank.adjust: If the maximum value of a range of ranks exceeds vector length, should this be adjusted?"
},
{
"code": null,
"e": 28143,
"s": 28065,
"text": "forceChoice: In the case of ties, should all results be returned or only one?"
},
{
"code": null,
"e": 28153,
"s": 28143,
"text": "Example1:"
},
{
"code": null,
"e": 28155,
"s": 28153,
"text": "R"
},
{
"code": "gfg_data <- data.frame(x = c(\"geeks\", \"for\", \"geeks\"), y = c(\"I\", \"Love\", \"Coding\"), z=c(\"R\", \"programming \", \"language\")) max(nchar(gfg_data$y)) ",
"e": 28350,
"s": 28155,
"text": null
},
{
"code": null,
"e": 28358,
"s": 28350,
"text": "Output:"
},
{
"code": null,
"e": 28364,
"s": 28358,
"text": "[1] 6"
},
{
"code": null,
"e": 28375,
"s": 28364,
"text": "Example 2:"
},
{
"code": null,
"e": 28377,
"s": 28375,
"text": "R"
},
{
"code": "gfg_data <- data.frame(x = c(\"geeks\", \"for\", \"geeks\"), y = c(\"I\", \"Love\", \"Coding\"), z=c(\"R\", \"programming \", \"language\")) max(nchar(gfg_data$z)) ",
"e": 28572,
"s": 28377,
"text": null
},
{
"code": null,
"e": 28580,
"s": 28572,
"text": "Output:"
},
{
"code": null,
"e": 28587,
"s": 28580,
"text": "[1] 12"
},
{
"code": null,
"e": 28594,
"s": 28587,
"text": "Picked"
},
{
"code": null,
"e": 28615,
"s": 28594,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 28627,
"s": 28615,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28638,
"s": 28627,
"text": "R Language"
},
{
"code": null,
"e": 28736,
"s": 28638,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28788,
"s": 28736,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28823,
"s": 28788,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28861,
"s": 28823,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28919,
"s": 28861,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28962,
"s": 28919,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29011,
"s": 28962,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29028,
"s": 29011,
"text": "R - if statement"
},
{
"code": null,
"e": 29065,
"s": 29028,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29117,
"s": 29065,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Matplotlib - Button Widget - GeeksforGeeks
|
30 Aug, 2021
In Matplotlib a button is one of the important widgets by which we can perform various operations. They are mostly used for making a good functional graph having different properties. There are three types of buttons
Button
Radio Buttons
Check Buttons
In this article, we will learn how to use different buttons in the matplotlib plot. For this, we will use some data, plot a graph, then form a button and use it. Let’s understand buttons one by one with the help of some examples.
This is a simple button that is responsible for performing only one function.
Syntax: simple_button=Button()
Parameters:
ax– defines the axes where the button should be located
label– the name that we want on the button
color– color of the button
hover color– color of the button when it gets clicked
In this example, we will create a simple button, and we will use this button to add one more line to the existing graph.
Python3
# importing librariesimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Button # creating datax1=np.array([0,1,2,3])y1=np.array([5,2,8,6]) # creating plotfig = plt.figure()ax = fig.subplots()plt.subplots_adjust(left = 0.3, bottom = 0.25)p,=ax.plot(x1,y1,color="blue", marker="o") # defining function to add line plotdef add(val): x2=np.array([0,1,2,3]) y2=np.array([10,2,0,12]) ax.plot(x2,y2,color="green", marker="o") # defining button and add its functionalityaxes = plt.axes([0.81, 0.000001, 0.1, 0.075])bnext = Button(axes, 'Add',color="yellow")bnext.on_clicked(add)plt.show()
Output:
This type of button consists of a series of circular buttons that can be used to enable/disable one of the functions of our graph.
Syntax: radio_button=RadioButtons()
Parameters:
ax– defines the axes where the button should be located
label– list of names that we want on every button
active– list of booleans describing the state of each button
active color– color of the active button
Here we created a simple sin graph where the radio buttons show the color of the line in the plot.
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import RadioButtons # creating an array starting from# 0 to 1 with step size 0.01t = np.arange(0.0, 1.0, 0.01) # the values of sin values of ts0 = np.sin(2*np.pi*t) # depict visualizationfig, ax = plt.subplots()l, = ax.plot(t, s0, lw=2, color='red')plt.subplots_adjust(left=0.3) # adjust radio buttonsaxcolor = 'lightgoldenrodyellow'rax = plt.axes([0.05, 0.4, 0.15, 0.30], facecolor=axcolor) radio = RadioButtons(rax, ['red', 'blue', 'green'], [True,False,False,False], activecolor='r') def color(labels): l.set_color(labels) fig.canvas.draw()radio.on_clicked(color) plt.show()
Output:
Unlike Radio Button where we can select only one option, Check Button allows us to select multiple options. This feature is useful when we want to perform 2 or more functions on the plot.
Syntax: check_button=CheckButtons()
Parameters:
ax– defines the axes where the button should be located
label– list of names that we want on every button
actives– list of booleans describing the state of each button
We created the same plot as a simple button but added 2 more graphs for the check button. We plotted it simultaneously.
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Button, RadioButtons, CheckButtons fig = plt.figure()ax = fig.subplots()plt.subplots_adjust(left=0.3, bottom=0.25) x1 = np.array([0, 1, 2, 3])y1 = np.array([5, 2, 8, 6])p, = ax.plot(x1, y1, color="blue", marker="o") x2 = np.array([0, 1, 2, 3])y2 = np.array([10, 2, 0, 12])p1, = ax.plot(x2, y2, color="green", marker="o") x3 = np.array([0, 1, 2, 3])y3 = np.array([0, 3, 2, 19])p2, = ax.plot(x3, y3, color="yellow", marker="o")lines = [p, p1, p2]labels = ["plot1", "plot2", "plot3"] def func(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) fig.canvas.draw() label = [True, True, True] # xposition, yposition, width and heightax_check = plt.axes([0.9, 0.001, 0.2, 0.3])plot_button = CheckButtons(ax_check, labels, label)plot_button.on_clicked(func) plt.show()
Output:
adnanirshad158
Picked
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 25778,
"s": 25561,
"text": "In Matplotlib a button is one of the important widgets by which we can perform various operations. They are mostly used for making a good functional graph having different properties. There are three types of buttons"
},
{
"code": null,
"e": 25785,
"s": 25778,
"text": "Button"
},
{
"code": null,
"e": 25799,
"s": 25785,
"text": "Radio Buttons"
},
{
"code": null,
"e": 25813,
"s": 25799,
"text": "Check Buttons"
},
{
"code": null,
"e": 26043,
"s": 25813,
"text": "In this article, we will learn how to use different buttons in the matplotlib plot. For this, we will use some data, plot a graph, then form a button and use it. Let’s understand buttons one by one with the help of some examples."
},
{
"code": null,
"e": 26122,
"s": 26043,
"text": "This is a simple button that is responsible for performing only one function. "
},
{
"code": null,
"e": 26153,
"s": 26122,
"text": "Syntax: simple_button=Button()"
},
{
"code": null,
"e": 26165,
"s": 26153,
"text": "Parameters:"
},
{
"code": null,
"e": 26221,
"s": 26165,
"text": "ax– defines the axes where the button should be located"
},
{
"code": null,
"e": 26264,
"s": 26221,
"text": "label– the name that we want on the button"
},
{
"code": null,
"e": 26291,
"s": 26264,
"text": "color– color of the button"
},
{
"code": null,
"e": 26345,
"s": 26291,
"text": "hover color– color of the button when it gets clicked"
},
{
"code": null,
"e": 26466,
"s": 26345,
"text": "In this example, we will create a simple button, and we will use this button to add one more line to the existing graph."
},
{
"code": null,
"e": 26474,
"s": 26466,
"text": "Python3"
},
{
"code": "# importing librariesimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Button # creating datax1=np.array([0,1,2,3])y1=np.array([5,2,8,6]) # creating plotfig = plt.figure()ax = fig.subplots()plt.subplots_adjust(left = 0.3, bottom = 0.25)p,=ax.plot(x1,y1,color=\"blue\", marker=\"o\") # defining function to add line plotdef add(val): x2=np.array([0,1,2,3]) y2=np.array([10,2,0,12]) ax.plot(x2,y2,color=\"green\", marker=\"o\") # defining button and add its functionalityaxes = plt.axes([0.81, 0.000001, 0.1, 0.075])bnext = Button(axes, 'Add',color=\"yellow\")bnext.on_clicked(add)plt.show()",
"e": 27090,
"s": 26474,
"text": null
},
{
"code": null,
"e": 27102,
"s": 27094,
"text": "Output:"
},
{
"code": null,
"e": 27238,
"s": 27106,
"text": "This type of button consists of a series of circular buttons that can be used to enable/disable one of the functions of our graph. "
},
{
"code": null,
"e": 27276,
"s": 27240,
"text": "Syntax: radio_button=RadioButtons()"
},
{
"code": null,
"e": 27288,
"s": 27276,
"text": "Parameters:"
},
{
"code": null,
"e": 27344,
"s": 27288,
"text": "ax– defines the axes where the button should be located"
},
{
"code": null,
"e": 27394,
"s": 27344,
"text": "label– list of names that we want on every button"
},
{
"code": null,
"e": 27455,
"s": 27394,
"text": "active– list of booleans describing the state of each button"
},
{
"code": null,
"e": 27496,
"s": 27455,
"text": "active color– color of the active button"
},
{
"code": null,
"e": 27597,
"s": 27498,
"text": "Here we created a simple sin graph where the radio buttons show the color of the line in the plot."
},
{
"code": null,
"e": 27607,
"s": 27599,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import RadioButtons # creating an array starting from# 0 to 1 with step size 0.01t = np.arange(0.0, 1.0, 0.01) # the values of sin values of ts0 = np.sin(2*np.pi*t) # depict visualizationfig, ax = plt.subplots()l, = ax.plot(t, s0, lw=2, color='red')plt.subplots_adjust(left=0.3) # adjust radio buttonsaxcolor = 'lightgoldenrodyellow'rax = plt.axes([0.05, 0.4, 0.15, 0.30], facecolor=axcolor) radio = RadioButtons(rax, ['red', 'blue', 'green'], [True,False,False,False], activecolor='r') def color(labels): l.set_color(labels) fig.canvas.draw()radio.on_clicked(color) plt.show()",
"e": 28333,
"s": 27607,
"text": null
},
{
"code": null,
"e": 28345,
"s": 28337,
"text": "Output:"
},
{
"code": null,
"e": 28538,
"s": 28349,
"text": "Unlike Radio Button where we can select only one option, Check Button allows us to select multiple options. This feature is useful when we want to perform 2 or more functions on the plot. "
},
{
"code": null,
"e": 28576,
"s": 28540,
"text": "Syntax: check_button=CheckButtons()"
},
{
"code": null,
"e": 28588,
"s": 28576,
"text": "Parameters:"
},
{
"code": null,
"e": 28644,
"s": 28588,
"text": "ax– defines the axes where the button should be located"
},
{
"code": null,
"e": 28694,
"s": 28644,
"text": "label– list of names that we want on every button"
},
{
"code": null,
"e": 28756,
"s": 28694,
"text": "actives– list of booleans describing the state of each button"
},
{
"code": null,
"e": 28878,
"s": 28758,
"text": "We created the same plot as a simple button but added 2 more graphs for the check button. We plotted it simultaneously."
},
{
"code": null,
"e": 28888,
"s": 28880,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Button, RadioButtons, CheckButtons fig = plt.figure()ax = fig.subplots()plt.subplots_adjust(left=0.3, bottom=0.25) x1 = np.array([0, 1, 2, 3])y1 = np.array([5, 2, 8, 6])p, = ax.plot(x1, y1, color=\"blue\", marker=\"o\") x2 = np.array([0, 1, 2, 3])y2 = np.array([10, 2, 0, 12])p1, = ax.plot(x2, y2, color=\"green\", marker=\"o\") x3 = np.array([0, 1, 2, 3])y3 = np.array([0, 3, 2, 19])p2, = ax.plot(x3, y3, color=\"yellow\", marker=\"o\")lines = [p, p1, p2]labels = [\"plot1\", \"plot2\", \"plot3\"] def func(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) fig.canvas.draw() label = [True, True, True] # xposition, yposition, width and heightax_check = plt.axes([0.9, 0.001, 0.2, 0.3])plot_button = CheckButtons(ax_check, labels, label)plot_button.on_clicked(func) plt.show()",
"e": 29782,
"s": 28888,
"text": null
},
{
"code": null,
"e": 29790,
"s": 29782,
"text": "Output:"
},
{
"code": null,
"e": 29805,
"s": 29790,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29812,
"s": 29805,
"text": "Picked"
},
{
"code": null,
"e": 29830,
"s": 29812,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29837,
"s": 29830,
"text": "Python"
},
{
"code": null,
"e": 29935,
"s": 29837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29967,
"s": 29935,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30009,
"s": 29967,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30051,
"s": 30009,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30078,
"s": 30051,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30134,
"s": 30078,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30173,
"s": 30134,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30195,
"s": 30173,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30226,
"s": 30195,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30255,
"s": 30226,
"text": "Create a directory in Python"
}
] |
GATE | GATE-CS-2017 (Set 2) | Question 30 - GeeksforGeeks
|
27 Sep, 2017
A Circular queue has been implemented using singly linked list where each node consists of a value and a pointer to next node. We maintain exactly two pointers FRONT and REAR pointing to the front node and rear node of queue. Which of the following statements is/are correct for circular queue so that insertion and deletion operations can be performed in O(1) i.e. constant time.
I. Next pointer of front node points to the rear node.
II. Next pointer of rear node points to the front node.
(A) I only
(B) II only(C) Both I and II(D) Neither I nor IIAnswer: (B)Explanation: Since, Circular queue deletes an item using Front pointer and insert an element using Rear pointer. If we want to insert an element into circular queue then we have to increment Rear pointer to next node then insert element. Then after update the next pointer of Rear node to the Front node. This method will have O(1) time for Insertion and Deletion.Only statement (ii) is true. So, option (B).Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25785,
"s": 25757,
"text": "\n27 Sep, 2017"
},
{
"code": null,
"e": 26166,
"s": 25785,
"text": "A Circular queue has been implemented using singly linked list where each node consists of a value and a pointer to next node. We maintain exactly two pointers FRONT and REAR pointing to the front node and rear node of queue. Which of the following statements is/are correct for circular queue so that insertion and deletion operations can be performed in O(1) i.e. constant time."
},
{
"code": null,
"e": 26278,
"s": 26166,
"text": "I. Next pointer of front node points to the rear node.\nII. Next pointer of rear node points to the front node.\n"
},
{
"code": null,
"e": 26289,
"s": 26278,
"text": "(A) I only"
},
{
"code": null,
"e": 26778,
"s": 26289,
"text": "(B) II only(C) Both I and II(D) Neither I nor IIAnswer: (B)Explanation: Since, Circular queue deletes an item using Front pointer and insert an element using Rear pointer. If we want to insert an element into circular queue then we have to increment Rear pointer to next node then insert element. Then after update the next pointer of Rear node to the Front node. This method will have O(1) time for Insertion and Deletion.Only statement (ii) is true. So, option (B).Quiz of this Question"
},
{
"code": null,
"e": 26799,
"s": 26778,
"text": "GATE-CS-2017 (Set 2)"
},
{
"code": null,
"e": 26825,
"s": 26799,
"text": "GATE-GATE-CS-2017 (Set 2)"
},
{
"code": null,
"e": 26830,
"s": 26825,
"text": "GATE"
},
{
"code": null,
"e": 26928,
"s": 26830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26962,
"s": 26928,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26996,
"s": 26962,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27030,
"s": 26996,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27063,
"s": 27030,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27099,
"s": 27063,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27133,
"s": 27099,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27169,
"s": 27133,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27203,
"s": 27169,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27237,
"s": 27203,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
strings.FieldsFunc() Function in Golang With Examples - GeeksforGeeks
|
19 Apr, 2020
strings.FieldsFunc() Function in Golang is used to splits the given string str at each run of Unicode code points c satisfying f(c) and returns an array of slices of str.
Syntax:
func FieldsFunc(str string, f func(rune) bool) []string
Here, str is the given string, the rune is a built-in type meant to contain a single Unicode character and f is a user-defined function.
Return: If all code points in str satisfy f(c) or the string is empty, an empty slice is returned.
Note: This function makes no guarantees about the order in which it calls f(c). If f does not return consistent results for a given c, FieldsFunc may crash.
Example 1:
// Golang program to illustrate the// strings.FieldsFunc() Function package main import ( "fmt" "strings" "unicode") func main() { // f is a function which returns true if the // c is number and false otherwise f := func(c rune) bool { return unicode.IsNumber(c) } // FieldsFunc() function splits the string passed // on the return values of the function f // String will therefore be split when a number // is encontered and returns all non-numbers fmt.Printf("Fields are: %q\n", strings.FieldsFunc("ABC123PQR456XYZ789", f))}
Output:
Fields are: ["ABC" "PQR" "XYZ"]
Example 2:
// Golang program to illustrate the// strings.FieldsFunc() Functionpackage main import ( "fmt" "strings" "unicode") func main() { // f is a function which returns true if the // c is a white space or a full stop // and returns false otherwise f := func(c rune) bool { return unicode.IsSpace(c) || c == '.' } // We can also pass a string indirectly // The string will split when a space or a // full stop is encontered and returns all non-numbers s := "We are humans. We are social animals." fmt.Printf("Fields are: %q\n", strings.FieldsFunc(s, f))}
Output:
Fields are: ["We" "are" "humans" "We" "are" "social" "animals"]
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
|
[
{
"code": null,
"e": 25717,
"s": 25689,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 25888,
"s": 25717,
"text": "strings.FieldsFunc() Function in Golang is used to splits the given string str at each run of Unicode code points c satisfying f(c) and returns an array of slices of str."
},
{
"code": null,
"e": 25896,
"s": 25888,
"text": "Syntax:"
},
{
"code": null,
"e": 25952,
"s": 25896,
"text": "func FieldsFunc(str string, f func(rune) bool) []string"
},
{
"code": null,
"e": 26089,
"s": 25952,
"text": "Here, str is the given string, the rune is a built-in type meant to contain a single Unicode character and f is a user-defined function."
},
{
"code": null,
"e": 26188,
"s": 26089,
"text": "Return: If all code points in str satisfy f(c) or the string is empty, an empty slice is returned."
},
{
"code": null,
"e": 26345,
"s": 26188,
"text": "Note: This function makes no guarantees about the order in which it calls f(c). If f does not return consistent results for a given c, FieldsFunc may crash."
},
{
"code": null,
"e": 26356,
"s": 26345,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the// strings.FieldsFunc() Function package main import ( \"fmt\" \"strings\" \"unicode\") func main() { // f is a function which returns true if the // c is number and false otherwise f := func(c rune) bool { return unicode.IsNumber(c) } // FieldsFunc() function splits the string passed // on the return values of the function f // String will therefore be split when a number // is encontered and returns all non-numbers fmt.Printf(\"Fields are: %q\\n\", strings.FieldsFunc(\"ABC123PQR456XYZ789\", f))}",
"e": 26940,
"s": 26356,
"text": null
},
{
"code": null,
"e": 26948,
"s": 26940,
"text": "Output:"
},
{
"code": null,
"e": 26980,
"s": 26948,
"text": "Fields are: [\"ABC\" \"PQR\" \"XYZ\"]"
},
{
"code": null,
"e": 26991,
"s": 26980,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the// strings.FieldsFunc() Functionpackage main import ( \"fmt\" \"strings\" \"unicode\") func main() { // f is a function which returns true if the // c is a white space or a full stop // and returns false otherwise f := func(c rune) bool { return unicode.IsSpace(c) || c == '.' } // We can also pass a string indirectly // The string will split when a space or a // full stop is encontered and returns all non-numbers s := \"We are humans. We are social animals.\" fmt.Printf(\"Fields are: %q\\n\", strings.FieldsFunc(s, f))}",
"e": 27592,
"s": 26991,
"text": null
},
{
"code": null,
"e": 27600,
"s": 27592,
"text": "Output:"
},
{
"code": null,
"e": 27664,
"s": 27600,
"text": "Fields are: [\"We\" \"are\" \"humans\" \"We\" \"are\" \"social\" \"animals\"]"
},
{
"code": null,
"e": 27678,
"s": 27664,
"text": "Golang-String"
},
{
"code": null,
"e": 27685,
"s": 27678,
"text": "Picked"
},
{
"code": null,
"e": 27697,
"s": 27685,
"text": "Go Language"
},
{
"code": null,
"e": 27795,
"s": 27697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27841,
"s": 27795,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 27854,
"s": 27841,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27887,
"s": 27854,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27904,
"s": 27887,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27916,
"s": 27904,
"text": "Golang Maps"
},
{
"code": null,
"e": 27938,
"s": 27916,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 27992,
"s": 27938,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 28013,
"s": 27992,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 28045,
"s": 28013,
"text": "How to Trim a String in Golang?"
}
] |
Reversing the vowels | Practice | GeeksforGeeks
|
Given a string consisting of lowercase english alphabets, reverse only the vowels present in it and print the resulting string.
Example 1:
Input:
S = "geeksforgeeks"
Output: geeksforgeeks
Explanation: The vowels are: e, e, o, e, e
Reverse of these is also e, e, o, e, e.
Example 2:
Input:
S = "practice"
Output: prectica
Explanation: The vowels are a, e
Reverse of these is e, a.
Example 3:
Input:
S = "bcdfg"
Output: bcdfg
Explanation: There are no vowels in S.
Your Task:
You don't need to read input or print anything. Your task is to complete the function modify() which takes the string S as input and returns the resultant string by reversing only the vowels present in S.
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(|S|).
Constraints:
1<=|S|<=105
0
sayanmazumder9992 weeks ago
JAVA---0.66/7.5 Seconds--100% Accuracy
StringBuilder str = new StringBuilder(); StringBuilder STR = new StringBuilder(s); int j = 0; char c; // catch all the vowels inside s. for(int i = 0; i <s.length(); i++) { c = s.charAt(i); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') str.append(c); } str = str.reverse(); // place those vowels in reversed form. for(int i = 0; i < STR.length(); i++) { c = STR.charAt(i); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') STR.setCharAt(i, str.charAt(j++)); } return String.valueOf(STR);
0
ishashi2 weeks ago
String modify (String s) { char[] l = s.toCharArray(); StringBuilder str = new StringBuilder(); String v ="aeiou"; for (int i = 0; i<l.length; i++){ if(v.contains(String.valueOf(l[i]))){ str.append(String.valueOf(l[i])); } } String r = str.reverse().toString(); int j =0; StringBuilder n = new StringBuilder(); for (int i = 0; i<l.length; i++){ if(v.contains(String.valueOf(l[i]))){ n.append(String.valueOf(r.charAt(j))); j = j+1; } else{ n.append(String.valueOf(l[i])); } } return n.toString() ; }
0
ishashi
This comment was deleted.
0
somiljaincse252 weeks ago
#JAVA SOLUTION
class Solution{ String modify (String s) { // your code here char[] str=s.toCharArray(); Stack<Character> st=new Stack<Character>(); for(int i=0;i<str.length;i++){ if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u'){ st.push(str[i]); str[i]='1'; } } for(int i=0;i<str.length;i++){ if(str[i]=='1'){ str[i]=st.peek(); st.pop(); } } return String.valueOf(str); }}
0
manavkanjiyanijobupdate2 weeks ago
--------------JAVA SOLUTION--------------------------ALL TEST CASE PASS
class Solution{ String modify (String s) { int[] index = new int[s.length()]; char[] afterChange = new char[s.length()]; int count = 0; char[] ch = s.toCharArray(); for(int i = 0 ; i < ch.length ; i++) { if(ch[i] == ('a') || ch[i] == ('i') || ch[i] == ('o') || ch[i] == ('u') || ch[i] == ('e')) { index[count] = i; afterChange[count] = ch[i]; count++; } } StringBuilder sb = new StringBuilder(String.valueOf(afterChange).substring(0,count)); char[] sr =sb.reverse().toString().toCharArray(); for(int i = 0; i < sr.length;i++) { ch[index[i]] = sr[i]; } return String.valueOf(ch); }}
0
neelasatyasai931 month ago
#PYTHON (accuracy is 16%) Time 0.6/9.0
class Solution: def modify(self, s): ove="" j=0 for i in s: if (i == 'a' or i=='e' or i=='i' or i=='o' or i=='u') : ove+=i c=ove[::-1] new='' for i in range(len(s)): if (s[i] == 'a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u') : new=new+c[j] j+=1 else: new=new+s[i] return new
+1
priyaranjandash1 month ago
********Java Solution************
class Solution{ String modify (String s) { String res=""; char s1[] = s.toCharArray(); for(int i=0;i<s1.length;i++) { if(s1[i] == 'a' || s1[i] == 'e' || s1[i] == 'i' || s1[i] == 'o' || s1[i] == 'u') { res+=s1[i]; s1[i]='@'; } } int n=res.length() -1; for(int i=0;i<s1.length;i++) { if(s1[i] == '@') { s1[i]= res.charAt(n); n--; } } String s2=String.valueOf(s1); return s2; }
+1
chauhankartikkc132 months ago
this problem is medium level , why it is put in school level
0
alidikme012 months ago
c++
string modify (string s) { string tempt=""; string tempt2=""; int index_start=0; int index_last=s.size(); string vowels="aeoui"; while(index_start <= index_last){ if(vowels.find(s[index_last])== std::string::npos){ index_last-=1; }else if(vowels.find(s[index_start]) == std::string::npos){ index_start+=1; }else if(vowels.find(s[index_start]) != std::string::npos && vowels.find(s[index_last] != std::string::npos)){ tempt=s[index_start]; tempt2=s[index_last]; s.replace(index_start,1,tempt2); s.replace(index_last,1,tempt); index_start++; index_last--; } } return s; }
0
shahabuddinbravo402 months ago
class Solution{ public: string modify (string s) { int i; string temp; for(i=0;i<s.size();i++){ if(s[i]=='a' || s[i]=='e' || s[i]=='o' || s[i]=='i'|| s[i]=='u'){ temp.push_back(s[i]); } } int k=0; for(i=0;i<s.size();i++){ if(s[i]=='a' || s[i]=='e' || s[i]=='o' || s[i]=='i'|| s[i]=='u'){ s[i]=temp[temp.size()-1-k]; k++; } } return s; }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 366,
"s": 238,
"text": "Given a string consisting of lowercase english alphabets, reverse only the vowels present in it and print the resulting string."
},
{
"code": null,
"e": 377,
"s": 366,
"text": "Example 1:"
},
{
"code": null,
"e": 510,
"s": 377,
"text": "Input:\nS = \"geeksforgeeks\"\nOutput: geeksforgeeks\nExplanation: The vowels are: e, e, o, e, e\nReverse of these is also e, e, o, e, e.\n"
},
{
"code": null,
"e": 522,
"s": 510,
"text": "\nExample 2:"
},
{
"code": null,
"e": 622,
"s": 522,
"text": "Input: \nS = \"practice\"\nOutput: prectica\nExplanation: The vowels are a, e\nReverse of these is e, a.\n"
},
{
"code": null,
"e": 635,
"s": 624,
"text": "Example 3:"
},
{
"code": null,
"e": 708,
"s": 635,
"text": "Input: \nS = \"bcdfg\"\nOutput: bcdfg\nExplanation: There are no vowels in S."
},
{
"code": null,
"e": 925,
"s": 708,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function modify() which takes the string S as input and returns the resultant string by reversing only the vowels present in S."
},
{
"code": null,
"e": 994,
"s": 925,
"text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(|S|)."
},
{
"code": null,
"e": 1020,
"s": 994,
"text": "\nConstraints:\n1<=|S|<=105"
},
{
"code": null,
"e": 1024,
"s": 1022,
"text": "0"
},
{
"code": null,
"e": 1052,
"s": 1024,
"text": "sayanmazumder9992 weeks ago"
},
{
"code": null,
"e": 1091,
"s": 1052,
"text": "JAVA---0.66/7.5 Seconds--100% Accuracy"
},
{
"code": null,
"e": 1644,
"s": 1091,
"text": " StringBuilder str = new StringBuilder(); StringBuilder STR = new StringBuilder(s); int j = 0; char c; // catch all the vowels inside s. for(int i = 0; i <s.length(); i++) { c = s.charAt(i); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') str.append(c); } str = str.reverse(); // place those vowels in reversed form. for(int i = 0; i < STR.length(); i++) { c = STR.charAt(i); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') STR.setCharAt(i, str.charAt(j++)); } return String.valueOf(STR);"
},
{
"code": null,
"e": 1646,
"s": 1644,
"text": "0"
},
{
"code": null,
"e": 1665,
"s": 1646,
"text": "ishashi2 weeks ago"
},
{
"code": null,
"e": 2361,
"s": 1665,
"text": " String modify (String s) { char[] l = s.toCharArray(); StringBuilder str = new StringBuilder(); String v =\"aeiou\"; for (int i = 0; i<l.length; i++){ if(v.contains(String.valueOf(l[i]))){ str.append(String.valueOf(l[i])); } } String r = str.reverse().toString(); int j =0; StringBuilder n = new StringBuilder(); for (int i = 0; i<l.length; i++){ if(v.contains(String.valueOf(l[i]))){ n.append(String.valueOf(r.charAt(j))); j = j+1; } else{ n.append(String.valueOf(l[i])); } } return n.toString() ; }"
},
{
"code": null,
"e": 2363,
"s": 2361,
"text": "0"
},
{
"code": null,
"e": 2371,
"s": 2363,
"text": "ishashi"
},
{
"code": null,
"e": 2397,
"s": 2371,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2399,
"s": 2397,
"text": "0"
},
{
"code": null,
"e": 2425,
"s": 2399,
"text": "somiljaincse252 weeks ago"
},
{
"code": null,
"e": 2440,
"s": 2425,
"text": "#JAVA SOLUTION"
},
{
"code": null,
"e": 2991,
"s": 2440,
"text": "class Solution{ String modify (String s) { // your code here char[] str=s.toCharArray(); Stack<Character> st=new Stack<Character>(); for(int i=0;i<str.length;i++){ if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u'){ st.push(str[i]); str[i]='1'; } } for(int i=0;i<str.length;i++){ if(str[i]=='1'){ str[i]=st.peek(); st.pop(); } } return String.valueOf(str); }}"
},
{
"code": null,
"e": 2993,
"s": 2991,
"text": "0"
},
{
"code": null,
"e": 3028,
"s": 2993,
"text": "manavkanjiyanijobupdate2 weeks ago"
},
{
"code": null,
"e": 3100,
"s": 3028,
"text": "--------------JAVA SOLUTION--------------------------ALL TEST CASE PASS"
},
{
"code": null,
"e": 3876,
"s": 3100,
"text": "class Solution{ String modify (String s) { int[] index = new int[s.length()]; char[] afterChange = new char[s.length()]; int count = 0; char[] ch = s.toCharArray(); for(int i = 0 ; i < ch.length ; i++) { if(ch[i] == ('a') || ch[i] == ('i') || ch[i] == ('o') || ch[i] == ('u') || ch[i] == ('e')) { index[count] = i; afterChange[count] = ch[i]; count++; } } StringBuilder sb = new StringBuilder(String.valueOf(afterChange).substring(0,count)); char[] sr =sb.reverse().toString().toCharArray(); for(int i = 0; i < sr.length;i++) { ch[index[i]] = sr[i]; } return String.valueOf(ch); }}"
},
{
"code": null,
"e": 3878,
"s": 3876,
"text": "0"
},
{
"code": null,
"e": 3905,
"s": 3878,
"text": "neelasatyasai931 month ago"
},
{
"code": null,
"e": 3951,
"s": 3905,
"text": "#PYTHON (accuracy is 16%) Time 0.6/9.0"
},
{
"code": null,
"e": 4347,
"s": 3951,
"text": "class Solution: def modify(self, s): ove=\"\" j=0 for i in s: if (i == 'a' or i=='e' or i=='i' or i=='o' or i=='u') : ove+=i c=ove[::-1] new='' for i in range(len(s)): if (s[i] == 'a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u') : new=new+c[j] j+=1 else: new=new+s[i] return new"
},
{
"code": null,
"e": 4350,
"s": 4347,
"text": "+1"
},
{
"code": null,
"e": 4377,
"s": 4350,
"text": "priyaranjandash1 month ago"
},
{
"code": null,
"e": 4427,
"s": 4377,
"text": " ********Java Solution************"
},
{
"code": null,
"e": 4844,
"s": 4427,
"text": "class Solution{ String modify (String s) { String res=\"\"; char s1[] = s.toCharArray(); for(int i=0;i<s1.length;i++) { if(s1[i] == 'a' || s1[i] == 'e' || s1[i] == 'i' || s1[i] == 'o' || s1[i] == 'u') { res+=s1[i]; s1[i]='@'; } } int n=res.length() -1; for(int i=0;i<s1.length;i++) { if(s1[i] == '@') { s1[i]= res.charAt(n); n--; } } String s2=String.valueOf(s1); return s2; }"
},
{
"code": null,
"e": 4847,
"s": 4844,
"text": "+1"
},
{
"code": null,
"e": 4877,
"s": 4847,
"text": "chauhankartikkc132 months ago"
},
{
"code": null,
"e": 4938,
"s": 4877,
"text": "this problem is medium level , why it is put in school level"
},
{
"code": null,
"e": 4940,
"s": 4938,
"text": "0"
},
{
"code": null,
"e": 4963,
"s": 4940,
"text": "alidikme012 months ago"
},
{
"code": null,
"e": 4968,
"s": 4963,
"text": "c++ "
},
{
"code": null,
"e": 5832,
"s": 4970,
"text": "string modify (string s) { string tempt=\"\"; string tempt2=\"\"; int index_start=0; int index_last=s.size(); string vowels=\"aeoui\"; while(index_start <= index_last){ if(vowels.find(s[index_last])== std::string::npos){ index_last-=1; }else if(vowels.find(s[index_start]) == std::string::npos){ index_start+=1; }else if(vowels.find(s[index_start]) != std::string::npos && vowels.find(s[index_last] != std::string::npos)){ tempt=s[index_start]; tempt2=s[index_last]; s.replace(index_start,1,tempt2); s.replace(index_last,1,tempt); index_start++; index_last--; } } return s; }"
},
{
"code": null,
"e": 5834,
"s": 5832,
"text": "0"
},
{
"code": null,
"e": 5865,
"s": 5834,
"text": "shahabuddinbravo402 months ago"
},
{
"code": null,
"e": 6414,
"s": 5865,
"text": "class Solution{ public: string modify (string s) { int i; string temp; for(i=0;i<s.size();i++){ if(s[i]=='a' || s[i]=='e' || s[i]=='o' || s[i]=='i'|| s[i]=='u'){ temp.push_back(s[i]); } } int k=0; for(i=0;i<s.size();i++){ if(s[i]=='a' || s[i]=='e' || s[i]=='o' || s[i]=='i'|| s[i]=='u'){ s[i]=temp[temp.size()-1-k]; k++; } } return s; }};"
},
{
"code": null,
"e": 6560,
"s": 6414,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6596,
"s": 6560,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6606,
"s": 6596,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6616,
"s": 6606,
"text": "\nContest\n"
},
{
"code": null,
"e": 6679,
"s": 6616,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6827,
"s": 6679,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7035,
"s": 6827,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7141,
"s": 7035,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
SAP HANA Admin - Key Commands
|
hdbsql -n localhost -i 1 -u username -p Password \s
This command will display the details of HANA database such as the host name, database, user, Kernel version, SQLDBC version, etc.
hdbsql -n localhost -i 1 -u username -p Password
"SELECT CNO,TITLE,FIRSTNAME,NAME,ZIP FROM Database_Name"
The above command displays the following result about concurrent sessions −
CNO | TITLE | FIRSTNAME | NAME | ZIP
To start and stop HANA database using HDB, you have to login to HANA system host as <sid>adm and run the following command −
/usr/sap/<SID>/HDB<instance number>/HDB start
/usr/sap/<SID>/HDB<instance number>/HDB stop
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2378,
"s": 2324,
"text": "hdbsql -n localhost -i 1 -u username -p Password \\s \n"
},
{
"code": null,
"e": 2509,
"s": 2378,
"text": "This command will display the details of HANA database such as the host name, database, user, Kernel version, SQLDBC version, etc."
},
{
"code": null,
"e": 2618,
"s": 2509,
"text": "hdbsql -n localhost -i 1 -u username -p Password \n\"SELECT CNO,TITLE,FIRSTNAME,NAME,ZIP FROM Database_Name\" \n"
},
{
"code": null,
"e": 2694,
"s": 2618,
"text": "The above command displays the following result about concurrent sessions −"
},
{
"code": null,
"e": 2733,
"s": 2694,
"text": "CNO | TITLE | FIRSTNAME | NAME | ZIP \n"
},
{
"code": null,
"e": 2858,
"s": 2733,
"text": "To start and stop HANA database using HDB, you have to login to HANA system host as <sid>adm and run the following command −"
},
{
"code": null,
"e": 2952,
"s": 2858,
"text": "/usr/sap/<SID>/HDB<instance number>/HDB start \n/usr/sap/<SID>/HDB<instance number>/HDB stop \n"
},
{
"code": null,
"e": 2985,
"s": 2952,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2999,
"s": 2985,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 3032,
"s": 2999,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3044,
"s": 3032,
"text": " Neha Gupta"
},
{
"code": null,
"e": 3079,
"s": 3044,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3094,
"s": 3079,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 3127,
"s": 3094,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3142,
"s": 3127,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 3177,
"s": 3142,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3189,
"s": 3177,
"text": " Neha Malik"
},
{
"code": null,
"e": 3224,
"s": 3189,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3236,
"s": 3224,
"text": " Neha Malik"
},
{
"code": null,
"e": 3243,
"s": 3236,
"text": " Print"
},
{
"code": null,
"e": 3254,
"s": 3243,
"text": " Add Notes"
}
] |
Machine Learning — Text Classification, Language Modelling using fast.ai | by Javaid Nabi | Towards Data Science
|
Transfer learning is a technique where instead of training a model from scratch, we reuse a pre-trained model and then fine-tune it for another related task. It has been very successful in computer vision applications. In natural language processing (NLP) transfer learning was mostly limited to the use of pre-trained word embeddings. Research in the field of using language modelling during pre-training have resulted in massive leap in state-of-the-art results for many of the NLP tasks, such as text classification, natural language inference and question-answering through various approaches such as ULMFiT, the OpenAI Transformer, ELMo and Google AI’s BERT.
In this post, we will discuss the limitations of word embedding approach in transfer learning for NLP problems and use of language model to build a text classifier using fast.ai library.
Word embeddings algorithms word2vec and GloVe provide a mapping of words to a high-dimensional continuous vector space where different words with a similar meaning have a similar vector representation. These word embeddings, pre-trained on large amounts of unlabeled data, are used to initialize the first layer of a neural network called embedding layer, the rest of the model is then trained on data of a particular task. This kind of transfer learning in NLP problems is shallow as learning is transferred to only the first layer of the model, the rest of the network still needs to be trained from scratch. A model initialized with word embeddings needs to learn from scratch not only to disambiguate words, but also to derive meaning from a sequence of words. In order to do so, NLP models initialized with these shallow representations require a huge dataset to achieve good performance, which can result in very large computational costs as well [1].
The core objective of a language modelling is of language understanding and it requires modeling complex language phenomena to deal with challenging language understanding problems such as translation, question answering and sentiment analysis. A language model attempts to learn the structure of natural language through hierarchical representations, and thus contains both low-level features (word representations) and high-level features (semantic meaning). A key feature of language modelling is that it is generative, meaning that it aims to predict the next word given a previous sequence of words. It is able to do this because language models are typically trained on very large datasets in an unsupervised manner, and hence the model can “learn” the syntactic features of language in a much deeper way than word embeddings [2].
To predict the next word of a sentence, the model actually needs to know quite a lot about the language and quite a lot of world knowledge. Here is an an example:
“I’d like to eat a hot ___”: Obviously, “dog”, right?
“It was a hot ___”: Probably “day”
As you can see, there’s not enough information here to decide what the next word probably is. But with a neural net, you absolutely can, provided you train a neural net to predict the next word of a sentence then you actually have a lot of information [3].
fastai library is focused on using pre-trained Language Models and fine-tuning them, done in below three steps:
Data pre-processing in a minimum amount of code.Create a language model with pre-trained weights that you can fine-tune to your dataset.Create other models such as classifiers on top of the language model.
Data pre-processing in a minimum amount of code.
Create a language model with pre-trained weights that you can fine-tune to your dataset.
Create other models such as classifiers on top of the language model.
Before we proceed further, we need to setup environment for fast.ai.
To install fastai:
conda install -c pytorch -c fastai fastai pytorch
In case you want to try out some ready to run options:
Colab: Free, needs installation of fast.ai
Kaggle Kernels: Free, No setup required, but not officially supported
Floydhub; No installation required, 2 hours free credit for CPU and 2 for GPU
I used Colab for initial learning but faced lot of ‘disconnected’ issues. Kaggle is another good option as well. Floydhub worked smoothly but after free credits, you need to pay for the usage. Having setup your environment let us proceed for some action.
Let us build a text classifier to classify the sentiments of IMDB movie dataset using the techniques discussed so far. IMDb dataset contains set of 25,000 movie reviews for training, and 25,000 for testing. We already have the IMDb data downloaded and saved in a csv format from the previous post. Let us load the data into a dataframe,
using below piece of code.
df_imdb = pd.read_csv(path/'movies_data.csv')df_imdb.head()#Loading only few training and validation samples, for quick training timetrn_texts = df_imdb.loc[10000:14999, 'review'].valuestrn_labels = df_imdb.loc[10000:14999, 'sentiment'].valuesval_texts = df_imdb.loc[36000:38999, 'review'].valuesval_labels = df_imdb.loc[36000:38999, 'sentiment'].valuesnp.random.seed(42)trn_idx = np.random.permutation(len(trn_texts))val_idx = np.random.permutation(len(val_texts))trn_texts = trn_texts[trn_idx]val_texts = val_texts[val_idx]trn_labels = trn_labels[trn_idx]val_labels = val_labels[val_idx]col_names = ['labels','text']df_trn = pd.DataFrame({'text':trn_texts, 'labels':trn_labels}, columns=col_names)df_val = pd.DataFrame({'text':val_texts, 'labels':val_labels}, columns=col_names)
We are using 5000 [2500 each label] from training and 3000[1500 each label] from validation examples. I am using smaller set to finish the training faster, please use full dataset for improved performance.
Creating a dataset from your raw texts is very simple. The library provides very easy to use API’s [4], depending on how our data is structured, to create a data class TextDataBunch for text processing, from_csv, from_folder,from_df refer to documentation for more details. Here we’ll use the method from_df of the TextLMDataBunch to create a language model specific data bunch:
# Language model datadata_lm = TextLMDataBunch.from_df('./', train_df=df_trn, valid_df=df_val)
This does all the necessary preprocessing behind the scene. Let us see how the data is encoded by fast.ai
data_lm.show_batch()
We can see a number of tags are applied to words as shown above. This is to retain all the information which can be used to gather an understanding of the new task’s vocabulary. All punctuation, hashtags and special characters are also retained. The text is encoded with various tokens like below:
xxbos: Begining of a sentence
xxfld: Represent separate parts of a document like title, summary etc., each one will get a separate field and so they will get numbered (e.g. xxfld 1, xxfld 2).
xxup: If there's something in all caps, it gets lower cased and a token called xxup will get added to it. Words that are fully capitalized, such as “I AM SHOUTING”, are tokenized as “xxup i xxup am xxup shouting“
xxunk: token used instead of an uncommon word.
xxmaj: token indicates that there is capitalization of the word. “The” will be tokenized as “xxmaj the“.
xxrep: token indicates repeated word, if you have 29 ! in a row, (i.e. xxrep 29 !).
Vocabulary: List of unique possible tokens is called the vocabulary. Listing below first 20 unique tokens in order of frequency:
data_lm.vocab.itos[:20]['xxunk', 'xxpad', 'xxbos', 'xxfld', 'xxmaj', 'xxup', 'xxrep', xxwrep', 'the', '.', ',', 'a', 'and', 'of', 'to', 'is', 'it', 'in', i', 'this']
Numericalization: Finally it is easier for machine to deal with the numbers so replace the tokens with the location of the token in the vocab:
The default vocab size is set to 60,000 words and min count for a word to be added to vocab is 2, to avoid getting the weight matrix huge.
Save and Load: We can save the data bunch after the pre-processing is done. We can load as well whenever we need.
# save and loaddata_lm.save('tmp_lm')data_lm = TextClasDataBunch.load('./', 'tmp_lm')
Fast.ai has a pre-trained Wikitext model, consisting of a pre-processed subset of 103 million tokens extracted from Wikipedia. It’s a model that understands a lot about language and a lot about what language describes. Next step is to fine-tune this model and do transfer learning to create a new language model that’s specifically good at predicting the next word of movie reviews.
This is the first stage of training, where we use the pre-trained language model weights and fine-tune it with the training data of IMDb movie reviews. When we create a learner, we have to pass in two things:
The data: our language model data (data_lm)
A pre-trained model: here, the pre-trained model is the Wikitext 103 model that will be downloaded for you from fastai.
# Language modellearner = language_model_learner(data_lm, pretrained_model=URLs.WT103_1, drop_mult=0.5)
drop_mult , a hyper-parameter ,used for regularization, sets the amount of dropout. If the model is over-fitting increase it, if under-fitting, you can decrease the number.
How to fine-tune the pre-trained model on our movie review data? Learning rate hyper-parameter is one of the most important parameters to train a model. Fast.ai provides a convenient utility (learn.lr_find) to search through a range of learning rates to find the optimum one for our dataset. Learning rate finder will increase the learning rate after each mini-batch. Eventually, the learning rate is too high that loss will get worse. Now look at the plot of learning rate against loss and determine the lowest point (around 1e-1 for the plot below) and go back by one magnitude and choose that as a learning rate (something around 1e-2).
Training the model:
We start training the model with learning rate 1e-2 using fit_one_cycle.
fast.ai library uses latest techniques from deep learning research and one cycle learning is from one of the recent paper and turned out to be both more accurate and faster than any previous approach. First argument ‘1’ is number of epoch runs . We get an accuracy of 29% after running just one epoch.
It trained last layers and basically left most of the model exactly as it was. But what we really want is to train the whole model. Normally after we fine-tune the last layers, the next thing we do is we go unfreeze (unfreeze the whole model for training) and train the whole thing.
learn.unfreeze()learn.fit_one_cycle(1, 1e-3)epoch train_loss valid_loss accuracy1 3.897383 3.977569 0.302463
Accuracy = 0.3 means the model is guessing the next word of the movie review correctly about a third of the time. That sounds like a pretty high number. So it’s a good sign that my language model is doing pretty well.
To evaluate our language model, we can now run learn.predict and pass in the start of a sentence and specify the number of words we want it to guess.
That is pretty decent response and looks like correct grammar. After fine-tuning we get a model that’s good at understanding movie reviews and we can fine-tune that with transfer learning to classify movie reviews to be positive or negative. Let us save the encoding of the model to be used later for classification.
learn.save_encoder('fine_enc')
The part of the model that has the understanding of the sentence is called the encoder. So we save it to later use it during the classification stage.
Now we’re ready to create our classifier. Step one, is to create a data bunch, TextClasDataBunch, passing the vocab from the language model to make sure that this data bunch is going to have exactly the same vocab. Batch size bs to be used is according to the GPU memory you have available, for a 16GB GPU around bs=64 will work fine. You can find whatever batch size fits on your card and use it accordingly.
# Classifier model datadata_clas = TextClasDataBunch.from_df('./', train_df=df_trn, valid_df=df_val, vocab=data_lm.train_ds.vocab, bs=32)
Finally we will create a text classifier learner. Load in our pre train model, the encoding part we saved earlier ‘fine_enc’.
# Classifierclassifier = text_classifier_learner(data_clas, drop_mult=0.5)classifier.load_encoder('fine_enc')
Again, we follow the same procedure to find the learning rate and train the model.
The learning rate around 2e-2 seems right, so let us train the classifier:
Wow 85% accuracy in 16 minutes of training and just using 5K training and 3K validation samples. This is the power of transfer learning.
Loss Plot: Let us plot the loss while training the model:
The loss curve seems going down smoothly and has not reached saturation point yet. fastai calculates the exponentially weighted moving average of the losses thus makes it easier to read these charts [by making the curve smoother] at the same time it might be a batch or two behind where they should be.
Let us understand the techniques fast.ai uses underneath for such impressive results.
Discriminative learning rates: Applying different learning rate to layers as you go from layer to layer. When fitting a model you can pass a list of learning rates which will apply a different rate to each layer group. When working with a Learner on which you've called split, you can set hyper-parameters in four ways:
param = [val1, val2 ..., valn] (n = number of layer groups)param = valparam = slice(start,end)param = slice(end)
param = [val1, val2 ..., valn] (n = number of layer groups)
param = val
param = slice(start,end)
param = slice(end)
If we chose to set it in way 1, we must specify a number of values exactly equal to the number of layer groups. If we chose to set it in way 2, the chosen value will be repeated for all layer groups. If you pass slice(start,end) then the first group's learning rate is start, the last is end, and the remaining are evenly spaced.
If you pass just slice(end) then the last group's learning rate is end, and all the other groups are end/10. For instance (for our learner that has 3 layer groups):
learn.lr_range(slice(1e-5,1e-3)), learn.lr_range(slice(1e-3))(array([1.e-05, 1.e-04, 1.e-03]), array([0.0001, 0.0001, 0.001 ]))
The bottom of the slice and the top of the slice is the difference between how quickly the lowest layer of the model learns versus the highest layer of the model learns. As you go from layer to layer, we decrease the learning rate. The lowest levels are given smaller learning rates so as not to disturb the weights much.
What is fit_one_cycle()? It is one cycle of learning rate, start low, go up, and then go down again. Let us plot the learning rate per batch using plot_lr
When we call fit_one_cycle, we are actually passing in a maximum learning rate. The left side plot shows learning rate change vs the batches. The learning starts slow and it increases about half the time and then it decreases about half the time. As you get close to the final answer you need to anneal your learning rate to hone in on it. The motivation behind this is that during the middle of learning when learning rate is higher, the learning rate works as regularization method and keep network from over-fitting. This helps the network to avoid steep areas of loss and land better flatter minima. Please refer to this paper by Leslie smith which talks in great detail about neural network hyper-parameter tuning and you can find most of these ideas implemented in fastai.
There is one more argument(moms=(0.8,0.7))-momentums equals 0.8,0.7. Basically for training recurrent neural networks (RNNs), it really helps to decrease the momentum a little bit.The right side above is the momentum plot. Every time our learning rate is small, our momentum is high. Why is that? Because as you are learning small learning rate, but you keep going in the same direction, you may as well go faster (higher momentum). But as you are learning high learning rate, but you keep going in the same direction, you may overshoot the target, so momentum should be slowed. This trick can help you train 10 times faster.
To improve the accuracy further, fast.ai provides some more tricks;freeze_to. Don't unfreeze the whole thing but to unfreeze one layer at a time. The below approach works very well and gives incredible results.
unfreeze the last two layers freeze_to(-2), train it a little bit more
unfreeze the next layer freeze_to(-3), train it a little bit more
unfreeze the whole thing unfreeze(), train it a little bit more
We reached an accuracy of 90%. The training loss is still higher than the validation loss so we are not over-fitting yet, there is still scope of improving accuracy by running more epochs.
In classification problems it is very useful to use something called a confusion matrix which shows you for each label, how many times was it predicted correctly. Confusion-matrix is good technique to summarize the performance of a classification algorithm.
We use ClassificationInterpretationclass to do the job for us.
Let us use our classifier and predict some movie review:
This is predicted as ‘0’, negative review. Fantastic!!!
We have previously done sentiment classification of the IMDb movie review using classical machine learning approach here and then using word embedding approach here. The language modelling approach using fast.ai is the simplest and most powerful tool, I have come across. The library provides very easy to use methods and with a few lines of code, you can achieve state-of-the-art results. Please refer to jupyter notebook here.
We discussed briefly the use of transfer learning in NLP problems. We explored the fast.ai library and different hyper-parameter tuning techniques in detail. We created a language model and later applied it on the text classification problem. I hope you enjoyed this post and learned something new and useful.
Thank you for reading.
|
[
{
"code": null,
"e": 835,
"s": 171,
"text": "Transfer learning is a technique where instead of training a model from scratch, we reuse a pre-trained model and then fine-tune it for another related task. It has been very successful in computer vision applications. In natural language processing (NLP) transfer learning was mostly limited to the use of pre-trained word embeddings. Research in the field of using language modelling during pre-training have resulted in massive leap in state-of-the-art results for many of the NLP tasks, such as text classification, natural language inference and question-answering through various approaches such as ULMFiT, the OpenAI Transformer, ELMo and Google AI’s BERT."
},
{
"code": null,
"e": 1022,
"s": 835,
"text": "In this post, we will discuss the limitations of word embedding approach in transfer learning for NLP problems and use of language model to build a text classifier using fast.ai library."
},
{
"code": null,
"e": 1980,
"s": 1022,
"text": "Word embeddings algorithms word2vec and GloVe provide a mapping of words to a high-dimensional continuous vector space where different words with a similar meaning have a similar vector representation. These word embeddings, pre-trained on large amounts of unlabeled data, are used to initialize the first layer of a neural network called embedding layer, the rest of the model is then trained on data of a particular task. This kind of transfer learning in NLP problems is shallow as learning is transferred to only the first layer of the model, the rest of the network still needs to be trained from scratch. A model initialized with word embeddings needs to learn from scratch not only to disambiguate words, but also to derive meaning from a sequence of words. In order to do so, NLP models initialized with these shallow representations require a huge dataset to achieve good performance, which can result in very large computational costs as well [1]."
},
{
"code": null,
"e": 2817,
"s": 1980,
"text": "The core objective of a language modelling is of language understanding and it requires modeling complex language phenomena to deal with challenging language understanding problems such as translation, question answering and sentiment analysis. A language model attempts to learn the structure of natural language through hierarchical representations, and thus contains both low-level features (word representations) and high-level features (semantic meaning). A key feature of language modelling is that it is generative, meaning that it aims to predict the next word given a previous sequence of words. It is able to do this because language models are typically trained on very large datasets in an unsupervised manner, and hence the model can “learn” the syntactic features of language in a much deeper way than word embeddings [2]."
},
{
"code": null,
"e": 2980,
"s": 2817,
"text": "To predict the next word of a sentence, the model actually needs to know quite a lot about the language and quite a lot of world knowledge. Here is an an example:"
},
{
"code": null,
"e": 3034,
"s": 2980,
"text": "“I’d like to eat a hot ___”: Obviously, “dog”, right?"
},
{
"code": null,
"e": 3069,
"s": 3034,
"text": "“It was a hot ___”: Probably “day”"
},
{
"code": null,
"e": 3326,
"s": 3069,
"text": "As you can see, there’s not enough information here to decide what the next word probably is. But with a neural net, you absolutely can, provided you train a neural net to predict the next word of a sentence then you actually have a lot of information [3]."
},
{
"code": null,
"e": 3438,
"s": 3326,
"text": "fastai library is focused on using pre-trained Language Models and fine-tuning them, done in below three steps:"
},
{
"code": null,
"e": 3644,
"s": 3438,
"text": "Data pre-processing in a minimum amount of code.Create a language model with pre-trained weights that you can fine-tune to your dataset.Create other models such as classifiers on top of the language model."
},
{
"code": null,
"e": 3693,
"s": 3644,
"text": "Data pre-processing in a minimum amount of code."
},
{
"code": null,
"e": 3782,
"s": 3693,
"text": "Create a language model with pre-trained weights that you can fine-tune to your dataset."
},
{
"code": null,
"e": 3852,
"s": 3782,
"text": "Create other models such as classifiers on top of the language model."
},
{
"code": null,
"e": 3921,
"s": 3852,
"text": "Before we proceed further, we need to setup environment for fast.ai."
},
{
"code": null,
"e": 3940,
"s": 3921,
"text": "To install fastai:"
},
{
"code": null,
"e": 3990,
"s": 3940,
"text": "conda install -c pytorch -c fastai fastai pytorch"
},
{
"code": null,
"e": 4045,
"s": 3990,
"text": "In case you want to try out some ready to run options:"
},
{
"code": null,
"e": 4088,
"s": 4045,
"text": "Colab: Free, needs installation of fast.ai"
},
{
"code": null,
"e": 4158,
"s": 4088,
"text": "Kaggle Kernels: Free, No setup required, but not officially supported"
},
{
"code": null,
"e": 4236,
"s": 4158,
"text": "Floydhub; No installation required, 2 hours free credit for CPU and 2 for GPU"
},
{
"code": null,
"e": 4491,
"s": 4236,
"text": "I used Colab for initial learning but faced lot of ‘disconnected’ issues. Kaggle is another good option as well. Floydhub worked smoothly but after free credits, you need to pay for the usage. Having setup your environment let us proceed for some action."
},
{
"code": null,
"e": 4828,
"s": 4491,
"text": "Let us build a text classifier to classify the sentiments of IMDB movie dataset using the techniques discussed so far. IMDb dataset contains set of 25,000 movie reviews for training, and 25,000 for testing. We already have the IMDb data downloaded and saved in a csv format from the previous post. Let us load the data into a dataframe,"
},
{
"code": null,
"e": 4855,
"s": 4828,
"text": "using below piece of code."
},
{
"code": null,
"e": 5636,
"s": 4855,
"text": "df_imdb = pd.read_csv(path/'movies_data.csv')df_imdb.head()#Loading only few training and validation samples, for quick training timetrn_texts = df_imdb.loc[10000:14999, 'review'].valuestrn_labels = df_imdb.loc[10000:14999, 'sentiment'].valuesval_texts = df_imdb.loc[36000:38999, 'review'].valuesval_labels = df_imdb.loc[36000:38999, 'sentiment'].valuesnp.random.seed(42)trn_idx = np.random.permutation(len(trn_texts))val_idx = np.random.permutation(len(val_texts))trn_texts = trn_texts[trn_idx]val_texts = val_texts[val_idx]trn_labels = trn_labels[trn_idx]val_labels = val_labels[val_idx]col_names = ['labels','text']df_trn = pd.DataFrame({'text':trn_texts, 'labels':trn_labels}, columns=col_names)df_val = pd.DataFrame({'text':val_texts, 'labels':val_labels}, columns=col_names)"
},
{
"code": null,
"e": 5842,
"s": 5636,
"text": "We are using 5000 [2500 each label] from training and 3000[1500 each label] from validation examples. I am using smaller set to finish the training faster, please use full dataset for improved performance."
},
{
"code": null,
"e": 6221,
"s": 5842,
"text": "Creating a dataset from your raw texts is very simple. The library provides very easy to use API’s [4], depending on how our data is structured, to create a data class TextDataBunch for text processing, from_csv, from_folder,from_df refer to documentation for more details. Here we’ll use the method from_df of the TextLMDataBunch to create a language model specific data bunch:"
},
{
"code": null,
"e": 6316,
"s": 6221,
"text": "# Language model datadata_lm = TextLMDataBunch.from_df('./', train_df=df_trn, valid_df=df_val)"
},
{
"code": null,
"e": 6422,
"s": 6316,
"text": "This does all the necessary preprocessing behind the scene. Let us see how the data is encoded by fast.ai"
},
{
"code": null,
"e": 6443,
"s": 6422,
"text": "data_lm.show_batch()"
},
{
"code": null,
"e": 6741,
"s": 6443,
"text": "We can see a number of tags are applied to words as shown above. This is to retain all the information which can be used to gather an understanding of the new task’s vocabulary. All punctuation, hashtags and special characters are also retained. The text is encoded with various tokens like below:"
},
{
"code": null,
"e": 6771,
"s": 6741,
"text": "xxbos: Begining of a sentence"
},
{
"code": null,
"e": 6933,
"s": 6771,
"text": "xxfld: Represent separate parts of a document like title, summary etc., each one will get a separate field and so they will get numbered (e.g. xxfld 1, xxfld 2)."
},
{
"code": null,
"e": 7146,
"s": 6933,
"text": "xxup: If there's something in all caps, it gets lower cased and a token called xxup will get added to it. Words that are fully capitalized, such as “I AM SHOUTING”, are tokenized as “xxup i xxup am xxup shouting“"
},
{
"code": null,
"e": 7193,
"s": 7146,
"text": "xxunk: token used instead of an uncommon word."
},
{
"code": null,
"e": 7298,
"s": 7193,
"text": "xxmaj: token indicates that there is capitalization of the word. “The” will be tokenized as “xxmaj the“."
},
{
"code": null,
"e": 7382,
"s": 7298,
"text": "xxrep: token indicates repeated word, if you have 29 ! in a row, (i.e. xxrep 29 !)."
},
{
"code": null,
"e": 7511,
"s": 7382,
"text": "Vocabulary: List of unique possible tokens is called the vocabulary. Listing below first 20 unique tokens in order of frequency:"
},
{
"code": null,
"e": 7677,
"s": 7511,
"text": "data_lm.vocab.itos[:20]['xxunk', 'xxpad', 'xxbos', 'xxfld', 'xxmaj', 'xxup', 'xxrep', xxwrep', 'the', '.', ',', 'a', 'and', 'of', 'to', 'is', 'it', 'in', i', 'this']"
},
{
"code": null,
"e": 7820,
"s": 7677,
"text": "Numericalization: Finally it is easier for machine to deal with the numbers so replace the tokens with the location of the token in the vocab:"
},
{
"code": null,
"e": 7959,
"s": 7820,
"text": "The default vocab size is set to 60,000 words and min count for a word to be added to vocab is 2, to avoid getting the weight matrix huge."
},
{
"code": null,
"e": 8073,
"s": 7959,
"text": "Save and Load: We can save the data bunch after the pre-processing is done. We can load as well whenever we need."
},
{
"code": null,
"e": 8159,
"s": 8073,
"text": "# save and loaddata_lm.save('tmp_lm')data_lm = TextClasDataBunch.load('./', 'tmp_lm')"
},
{
"code": null,
"e": 8542,
"s": 8159,
"text": "Fast.ai has a pre-trained Wikitext model, consisting of a pre-processed subset of 103 million tokens extracted from Wikipedia. It’s a model that understands a lot about language and a lot about what language describes. Next step is to fine-tune this model and do transfer learning to create a new language model that’s specifically good at predicting the next word of movie reviews."
},
{
"code": null,
"e": 8751,
"s": 8542,
"text": "This is the first stage of training, where we use the pre-trained language model weights and fine-tune it with the training data of IMDb movie reviews. When we create a learner, we have to pass in two things:"
},
{
"code": null,
"e": 8795,
"s": 8751,
"text": "The data: our language model data (data_lm)"
},
{
"code": null,
"e": 8915,
"s": 8795,
"text": "A pre-trained model: here, the pre-trained model is the Wikitext 103 model that will be downloaded for you from fastai."
},
{
"code": null,
"e": 9019,
"s": 8915,
"text": "# Language modellearner = language_model_learner(data_lm, pretrained_model=URLs.WT103_1, drop_mult=0.5)"
},
{
"code": null,
"e": 9192,
"s": 9019,
"text": "drop_mult , a hyper-parameter ,used for regularization, sets the amount of dropout. If the model is over-fitting increase it, if under-fitting, you can decrease the number."
},
{
"code": null,
"e": 9832,
"s": 9192,
"text": "How to fine-tune the pre-trained model on our movie review data? Learning rate hyper-parameter is one of the most important parameters to train a model. Fast.ai provides a convenient utility (learn.lr_find) to search through a range of learning rates to find the optimum one for our dataset. Learning rate finder will increase the learning rate after each mini-batch. Eventually, the learning rate is too high that loss will get worse. Now look at the plot of learning rate against loss and determine the lowest point (around 1e-1 for the plot below) and go back by one magnitude and choose that as a learning rate (something around 1e-2)."
},
{
"code": null,
"e": 9852,
"s": 9832,
"text": "Training the model:"
},
{
"code": null,
"e": 9925,
"s": 9852,
"text": "We start training the model with learning rate 1e-2 using fit_one_cycle."
},
{
"code": null,
"e": 10227,
"s": 9925,
"text": "fast.ai library uses latest techniques from deep learning research and one cycle learning is from one of the recent paper and turned out to be both more accurate and faster than any previous approach. First argument ‘1’ is number of epoch runs . We get an accuracy of 29% after running just one epoch."
},
{
"code": null,
"e": 10510,
"s": 10227,
"text": "It trained last layers and basically left most of the model exactly as it was. But what we really want is to train the whole model. Normally after we fine-tune the last layers, the next thing we do is we go unfreeze (unfreeze the whole model for training) and train the whole thing."
},
{
"code": null,
"e": 10633,
"s": 10510,
"text": "learn.unfreeze()learn.fit_one_cycle(1, 1e-3)epoch train_loss valid_loss accuracy1 3.897383 3.977569 0.302463"
},
{
"code": null,
"e": 10851,
"s": 10633,
"text": "Accuracy = 0.3 means the model is guessing the next word of the movie review correctly about a third of the time. That sounds like a pretty high number. So it’s a good sign that my language model is doing pretty well."
},
{
"code": null,
"e": 11001,
"s": 10851,
"text": "To evaluate our language model, we can now run learn.predict and pass in the start of a sentence and specify the number of words we want it to guess."
},
{
"code": null,
"e": 11318,
"s": 11001,
"text": "That is pretty decent response and looks like correct grammar. After fine-tuning we get a model that’s good at understanding movie reviews and we can fine-tune that with transfer learning to classify movie reviews to be positive or negative. Let us save the encoding of the model to be used later for classification."
},
{
"code": null,
"e": 11349,
"s": 11318,
"text": "learn.save_encoder('fine_enc')"
},
{
"code": null,
"e": 11500,
"s": 11349,
"text": "The part of the model that has the understanding of the sentence is called the encoder. So we save it to later use it during the classification stage."
},
{
"code": null,
"e": 11910,
"s": 11500,
"text": "Now we’re ready to create our classifier. Step one, is to create a data bunch, TextClasDataBunch, passing the vocab from the language model to make sure that this data bunch is going to have exactly the same vocab. Batch size bs to be used is according to the GPU memory you have available, for a 16GB GPU around bs=64 will work fine. You can find whatever batch size fits on your card and use it accordingly."
},
{
"code": null,
"e": 12048,
"s": 11910,
"text": "# Classifier model datadata_clas = TextClasDataBunch.from_df('./', train_df=df_trn, valid_df=df_val, vocab=data_lm.train_ds.vocab, bs=32)"
},
{
"code": null,
"e": 12174,
"s": 12048,
"text": "Finally we will create a text classifier learner. Load in our pre train model, the encoding part we saved earlier ‘fine_enc’."
},
{
"code": null,
"e": 12284,
"s": 12174,
"text": "# Classifierclassifier = text_classifier_learner(data_clas, drop_mult=0.5)classifier.load_encoder('fine_enc')"
},
{
"code": null,
"e": 12367,
"s": 12284,
"text": "Again, we follow the same procedure to find the learning rate and train the model."
},
{
"code": null,
"e": 12442,
"s": 12367,
"text": "The learning rate around 2e-2 seems right, so let us train the classifier:"
},
{
"code": null,
"e": 12579,
"s": 12442,
"text": "Wow 85% accuracy in 16 minutes of training and just using 5K training and 3K validation samples. This is the power of transfer learning."
},
{
"code": null,
"e": 12637,
"s": 12579,
"text": "Loss Plot: Let us plot the loss while training the model:"
},
{
"code": null,
"e": 12940,
"s": 12637,
"text": "The loss curve seems going down smoothly and has not reached saturation point yet. fastai calculates the exponentially weighted moving average of the losses thus makes it easier to read these charts [by making the curve smoother] at the same time it might be a batch or two behind where they should be."
},
{
"code": null,
"e": 13026,
"s": 12940,
"text": "Let us understand the techniques fast.ai uses underneath for such impressive results."
},
{
"code": null,
"e": 13346,
"s": 13026,
"text": "Discriminative learning rates: Applying different learning rate to layers as you go from layer to layer. When fitting a model you can pass a list of learning rates which will apply a different rate to each layer group. When working with a Learner on which you've called split, you can set hyper-parameters in four ways:"
},
{
"code": null,
"e": 13459,
"s": 13346,
"text": "param = [val1, val2 ..., valn] (n = number of layer groups)param = valparam = slice(start,end)param = slice(end)"
},
{
"code": null,
"e": 13519,
"s": 13459,
"text": "param = [val1, val2 ..., valn] (n = number of layer groups)"
},
{
"code": null,
"e": 13531,
"s": 13519,
"text": "param = val"
},
{
"code": null,
"e": 13556,
"s": 13531,
"text": "param = slice(start,end)"
},
{
"code": null,
"e": 13575,
"s": 13556,
"text": "param = slice(end)"
},
{
"code": null,
"e": 13905,
"s": 13575,
"text": "If we chose to set it in way 1, we must specify a number of values exactly equal to the number of layer groups. If we chose to set it in way 2, the chosen value will be repeated for all layer groups. If you pass slice(start,end) then the first group's learning rate is start, the last is end, and the remaining are evenly spaced."
},
{
"code": null,
"e": 14070,
"s": 13905,
"text": "If you pass just slice(end) then the last group's learning rate is end, and all the other groups are end/10. For instance (for our learner that has 3 layer groups):"
},
{
"code": null,
"e": 14198,
"s": 14070,
"text": "learn.lr_range(slice(1e-5,1e-3)), learn.lr_range(slice(1e-3))(array([1.e-05, 1.e-04, 1.e-03]), array([0.0001, 0.0001, 0.001 ]))"
},
{
"code": null,
"e": 14520,
"s": 14198,
"text": "The bottom of the slice and the top of the slice is the difference between how quickly the lowest layer of the model learns versus the highest layer of the model learns. As you go from layer to layer, we decrease the learning rate. The lowest levels are given smaller learning rates so as not to disturb the weights much."
},
{
"code": null,
"e": 14675,
"s": 14520,
"text": "What is fit_one_cycle()? It is one cycle of learning rate, start low, go up, and then go down again. Let us plot the learning rate per batch using plot_lr"
},
{
"code": null,
"e": 15454,
"s": 14675,
"text": "When we call fit_one_cycle, we are actually passing in a maximum learning rate. The left side plot shows learning rate change vs the batches. The learning starts slow and it increases about half the time and then it decreases about half the time. As you get close to the final answer you need to anneal your learning rate to hone in on it. The motivation behind this is that during the middle of learning when learning rate is higher, the learning rate works as regularization method and keep network from over-fitting. This helps the network to avoid steep areas of loss and land better flatter minima. Please refer to this paper by Leslie smith which talks in great detail about neural network hyper-parameter tuning and you can find most of these ideas implemented in fastai."
},
{
"code": null,
"e": 16080,
"s": 15454,
"text": "There is one more argument(moms=(0.8,0.7))-momentums equals 0.8,0.7. Basically for training recurrent neural networks (RNNs), it really helps to decrease the momentum a little bit.The right side above is the momentum plot. Every time our learning rate is small, our momentum is high. Why is that? Because as you are learning small learning rate, but you keep going in the same direction, you may as well go faster (higher momentum). But as you are learning high learning rate, but you keep going in the same direction, you may overshoot the target, so momentum should be slowed. This trick can help you train 10 times faster."
},
{
"code": null,
"e": 16291,
"s": 16080,
"text": "To improve the accuracy further, fast.ai provides some more tricks;freeze_to. Don't unfreeze the whole thing but to unfreeze one layer at a time. The below approach works very well and gives incredible results."
},
{
"code": null,
"e": 16362,
"s": 16291,
"text": "unfreeze the last two layers freeze_to(-2), train it a little bit more"
},
{
"code": null,
"e": 16428,
"s": 16362,
"text": "unfreeze the next layer freeze_to(-3), train it a little bit more"
},
{
"code": null,
"e": 16492,
"s": 16428,
"text": "unfreeze the whole thing unfreeze(), train it a little bit more"
},
{
"code": null,
"e": 16681,
"s": 16492,
"text": "We reached an accuracy of 90%. The training loss is still higher than the validation loss so we are not over-fitting yet, there is still scope of improving accuracy by running more epochs."
},
{
"code": null,
"e": 16939,
"s": 16681,
"text": "In classification problems it is very useful to use something called a confusion matrix which shows you for each label, how many times was it predicted correctly. Confusion-matrix is good technique to summarize the performance of a classification algorithm."
},
{
"code": null,
"e": 17002,
"s": 16939,
"text": "We use ClassificationInterpretationclass to do the job for us."
},
{
"code": null,
"e": 17059,
"s": 17002,
"text": "Let us use our classifier and predict some movie review:"
},
{
"code": null,
"e": 17115,
"s": 17059,
"text": "This is predicted as ‘0’, negative review. Fantastic!!!"
},
{
"code": null,
"e": 17544,
"s": 17115,
"text": "We have previously done sentiment classification of the IMDb movie review using classical machine learning approach here and then using word embedding approach here. The language modelling approach using fast.ai is the simplest and most powerful tool, I have come across. The library provides very easy to use methods and with a few lines of code, you can achieve state-of-the-art results. Please refer to jupyter notebook here."
},
{
"code": null,
"e": 17854,
"s": 17544,
"text": "We discussed briefly the use of transfer learning in NLP problems. We explored the fast.ai library and different hyper-parameter tuning techniques in detail. We created a language model and later applied it on the text classification problem. I hope you enjoyed this post and learned something new and useful."
}
] |
Python Data Persistence - SQLAlchemy
|
Any relational database holds data in tables. The table structure defines data type of attributes which are basically of primary data types only which are mapped to corresponding built-in data types of Python. However, Python's user-defined objects can't be persistently stored and retrieved to/from SQL tables.
This is a disparity between SQL types and object oriented programming languages such as Python. SQL doesn't have equivalent data type for others such as dict, tuple, list, or any user defined class.
If you have to store an object in a relational database, it's instance attributes should be deconstructed into SQL data types first, before executing INSERT query. On the other hand, data retrieved from a SQL table is in primary types. A Python object of desired type will have to be constructed by using for use in Python script. This is where Object Relational Mappers are useful.
An Object Relation Mapper (ORM) is an interface between a class and a SQL table. A Python class is mapped to a certain table in database, so that conversion between object and SQL types is automatically performed.
The Students class written in Python code is mapped to Students table in the database. As a result, all CRUD operations are done by calling respective methods of the class. This eliminates need to execute hard coded SQL queries in Python script.
ORM library thus acts as an abstraction layer over the raw SQL queries and can be of help in rapid application development. SQLAlchemy is a popular object relational mapper for Python. Any manipulation of state of model object is synchronized with its related row in the database table.
SQLALchemy library includes ORM API and SQL Expression Language (SQLAlchemy Core). Expression language executes primitive constructs of the relational database directly.
ORM is a high level and abstracted pattern of usage constructed on top of the SQL Expression Language. It can be said that ORM is an applied usage of the Expression Language. We shall discuss SQLAlchemy ORM API and use SQLite database in this topic.
SQLAlchemy communicates with various types of databases through their respective DBAPI implementations using a dialect system. All dialects require that an appropriate DBAPI driver is installed. Dialects for following type of databases are included −
Firebird
Microsoft SQL Server
MySQL
Oracle
PostgreSQL
SQLite
Sybase
Installation of SQLAlchemy is easy and straightforward, using pip utility.
pip install sqlalchemy
To check if SQLalchemy is properly installed and its version, enter following on Python prompt −
>>> import sqlalchemy
>>>sqlalchemy.__version__
'1.3.11'
Interactions with database are done through Engine object obtained as a return value of create_engine() function.
engine =create_engine('sqlite:///mydb.sqlite')
SQLite allows creation of in-memory database. SQLAlchemy engine for in-memory database is created as follows −
from sqlalchemy import create_engine
engine=create_engine('sqlite:///:memory:')
If you intend to use MySQL database instead, use its DB-API module – pymysql and respective dialect driver.
engine = create_engine('mysql+pymydsql://root@localhost/mydb')
The create_engine has an optional echo argument. If set to true, the SQL queries generated by engine will be echoed on the terminal.
SQLAlchemy contains declarative base class. It acts as a catalog of model classes and mapped tables.
from sqlalchemy.ext.declarative import declarative_base
base=declarative_base()
Next step is to define a model class. It must be derived from base – object of declarative_base class as above.
Set __tablename__ property to name of the table you want to be created in the database. Other attributes correspond to the fields. Each one is a Column object in SQLAlchemy and its data type is from one of the list below −
BigInteger
Boolean
Date
DateTime
Float
Integer
Numeric
SmallInteger
String
Text
Time
Following code is the model class named as Student that is mapped to Students table.
#myclasses.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Numeric
base=declarative_base()
class Student(base):
__tablename__='Students'
StudentID=Column(Integer, primary_key=True)
name=Column(String)
age=Column(Integer)
marks=Column(Numeric)
To create a Students table that has a corresponding structure, execute create_all() method defined for base class.
base.metadata.create_all(engine)
We now have to declare an object of our Student class. All database transactions such as add, delete or retrieve data from database, etc., are handled by a Session object.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
sessionobj = Session()
Data stored in Student object is physically added in underlying table by session’s add() method.
s1 = Student(name='Juhi', age=25, marks=200)
sessionobj.add(s1)
sessionobj.commit()
Here, is the entire code for adding record in students table. As it is executed, corresponding SQL statement log is displayed on console.
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from myclasses import Student, base
engine = create_engine('sqlite:///college.db', echo=True)
base.metadata.create_all(engine)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
sessionobj = Session()
s1 = Student(name='Juhi', age=25, marks=200)
sessionobj.add(s1)
sessionobj.commit()
CREATE TABLE "Students" (
"StudentID" INTEGER NOT NULL,
name VARCHAR,
age INTEGER,
marks NUMERIC,
PRIMARY KEY ("StudentID")
)
INFO sqlalchemy.engine.base.Engine ()
INFO sqlalchemy.engine.base.Engine COMMIT
INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
INFO sqlalchemy.engine.base.Engine INSERT INTO "Students" (name, age, marks) VALUES (?, ?, ?)
INFO sqlalchemy.engine.base.Engine ('Juhi', 25, 200.0)
INFO sqlalchemy.engine.base.Engine COMMIT
The session object also provides add_all() method to insert more than one objects in a single transaction.
sessionobj.add_all([s2,s3,s4,s5])
sessionobj.commit()
Now that, records are added in the table, we would like to fetch from it just as SELECT query does. The session object has query() method to perform the task. Query object is returned by query() method on our Student model.
qry=seesionobj.query(Student)
Use the get() method of this Query object fetches object corresponding to given primary key.
S1=qry.get(1)
While this statement is executed, its corresponding SQL statement echoed on the console will be as follows −
BEGIN (implicit)
SELECT "Students"."StudentID" AS "Students_StudentID", "Students".name AS
"Students_name", "Students".age AS "Students_age",
"Students".marks AS "Students_marks"
FROM "Students"
WHERE "Products"."Students" = ?
sqlalchemy.engine.base.Engine (1,)
The query.all() method returns a list of all objects which can be traversed using a loop.
from sqlalchemy import Column, Integer, String, Numeric
from sqlalchemy import create_engine
from myclasses import Student,base
engine = create_engine('sqlite:///college.db', echo=True)
base.metadata.create_all(engine)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
sessionobj = Session()
qry=sessionobj.query(Students)
rows=qry.all()
for row in rows:
print (row)
Updating a record in the mapped table is very easy. All you have to do is fetch a record using get() method, assign a new value to desired attribute and then commit the changes using session object. Below we change marks of Juhi student to 100.
S1=qry.get(1)
S1.marks=100
sessionobj.commit()
Deleting a record is just as easy, by deleting desired object from the session.
S1=qry.get(1)
Sessionobj.delete(S1)
sessionobj.commit()
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": 2667,
"s": 2355,
"text": "Any relational database holds data in tables. The table structure defines data type of attributes which are basically of primary data types only which are mapped to corresponding built-in data types of Python. However, Python's user-defined objects can't be persistently stored and retrieved to/from SQL tables."
},
{
"code": null,
"e": 2866,
"s": 2667,
"text": "This is a disparity between SQL types and object oriented programming languages such as Python. SQL doesn't have equivalent data type for others such as dict, tuple, list, or any user defined class."
},
{
"code": null,
"e": 3249,
"s": 2866,
"text": "If you have to store an object in a relational database, it's instance attributes should be deconstructed into SQL data types first, before executing INSERT query. On the other hand, data retrieved from a SQL table is in primary types. A Python object of desired type will have to be constructed by using for use in Python script. This is where Object Relational Mappers are useful."
},
{
"code": null,
"e": 3463,
"s": 3249,
"text": "An Object Relation Mapper (ORM) is an interface between a class and a SQL table. A Python class is mapped to a certain table in database, so that conversion between object and SQL types is automatically performed."
},
{
"code": null,
"e": 3709,
"s": 3463,
"text": "The Students class written in Python code is mapped to Students table in the database. As a result, all CRUD operations are done by calling respective methods of the class. This eliminates need to execute hard coded SQL queries in Python script."
},
{
"code": null,
"e": 3996,
"s": 3709,
"text": "ORM library thus acts as an abstraction layer over the raw SQL queries and can be of help in rapid application development. SQLAlchemy is a popular object relational mapper for Python. Any manipulation of state of model object is synchronized with its related row in the database table."
},
{
"code": null,
"e": 4166,
"s": 3996,
"text": "SQLALchemy library includes ORM API and SQL Expression Language (SQLAlchemy Core). Expression language executes primitive constructs of the relational database directly."
},
{
"code": null,
"e": 4416,
"s": 4166,
"text": "ORM is a high level and abstracted pattern of usage constructed on top of the SQL Expression Language. It can be said that ORM is an applied usage of the Expression Language. We shall discuss SQLAlchemy ORM API and use SQLite database in this topic."
},
{
"code": null,
"e": 4667,
"s": 4416,
"text": "SQLAlchemy communicates with various types of databases through their respective DBAPI implementations using a dialect system. All dialects require that an appropriate DBAPI driver is installed. Dialects for following type of databases are included −"
},
{
"code": null,
"e": 4676,
"s": 4667,
"text": "Firebird"
},
{
"code": null,
"e": 4697,
"s": 4676,
"text": "Microsoft SQL Server"
},
{
"code": null,
"e": 4703,
"s": 4697,
"text": "MySQL"
},
{
"code": null,
"e": 4710,
"s": 4703,
"text": "Oracle"
},
{
"code": null,
"e": 4721,
"s": 4710,
"text": "PostgreSQL"
},
{
"code": null,
"e": 4728,
"s": 4721,
"text": "SQLite"
},
{
"code": null,
"e": 4735,
"s": 4728,
"text": "Sybase"
},
{
"code": null,
"e": 4810,
"s": 4735,
"text": "Installation of SQLAlchemy is easy and straightforward, using pip utility."
},
{
"code": null,
"e": 4834,
"s": 4810,
"text": "pip install sqlalchemy\n"
},
{
"code": null,
"e": 4931,
"s": 4834,
"text": "To check if SQLalchemy is properly installed and its version, enter following on Python prompt −"
},
{
"code": null,
"e": 4989,
"s": 4931,
"text": ">>> import sqlalchemy\n>>>sqlalchemy.__version__\n'1.3.11'\n"
},
{
"code": null,
"e": 5103,
"s": 4989,
"text": "Interactions with database are done through Engine object obtained as a return value of create_engine() function."
},
{
"code": null,
"e": 5151,
"s": 5103,
"text": "engine =create_engine('sqlite:///mydb.sqlite')\n"
},
{
"code": null,
"e": 5262,
"s": 5151,
"text": "SQLite allows creation of in-memory database. SQLAlchemy engine for in-memory database is created as follows −"
},
{
"code": null,
"e": 5343,
"s": 5262,
"text": "from sqlalchemy import create_engine\nengine=create_engine('sqlite:///:memory:')\n"
},
{
"code": null,
"e": 5451,
"s": 5343,
"text": "If you intend to use MySQL database instead, use its DB-API module – pymysql and respective dialect driver."
},
{
"code": null,
"e": 5515,
"s": 5451,
"text": "engine = create_engine('mysql+pymydsql://root@localhost/mydb')\n"
},
{
"code": null,
"e": 5648,
"s": 5515,
"text": "The create_engine has an optional echo argument. If set to true, the SQL queries generated by engine will be echoed on the terminal."
},
{
"code": null,
"e": 5749,
"s": 5648,
"text": "SQLAlchemy contains declarative base class. It acts as a catalog of model classes and mapped tables."
},
{
"code": null,
"e": 5830,
"s": 5749,
"text": "from sqlalchemy.ext.declarative import declarative_base\nbase=declarative_base()\n"
},
{
"code": null,
"e": 5942,
"s": 5830,
"text": "Next step is to define a model class. It must be derived from base – object of declarative_base class as above."
},
{
"code": null,
"e": 6165,
"s": 5942,
"text": "Set __tablename__ property to name of the table you want to be created in the database. Other attributes correspond to the fields. Each one is a Column object in SQLAlchemy and its data type is from one of the list below −"
},
{
"code": null,
"e": 6176,
"s": 6165,
"text": "BigInteger"
},
{
"code": null,
"e": 6184,
"s": 6176,
"text": "Boolean"
},
{
"code": null,
"e": 6189,
"s": 6184,
"text": "Date"
},
{
"code": null,
"e": 6198,
"s": 6189,
"text": "DateTime"
},
{
"code": null,
"e": 6204,
"s": 6198,
"text": "Float"
},
{
"code": null,
"e": 6212,
"s": 6204,
"text": "Integer"
},
{
"code": null,
"e": 6220,
"s": 6212,
"text": "Numeric"
},
{
"code": null,
"e": 6233,
"s": 6220,
"text": "SmallInteger"
},
{
"code": null,
"e": 6240,
"s": 6233,
"text": "String"
},
{
"code": null,
"e": 6245,
"s": 6240,
"text": "Text"
},
{
"code": null,
"e": 6250,
"s": 6245,
"text": "Time"
},
{
"code": null,
"e": 6335,
"s": 6250,
"text": "Following code is the model class named as Student that is mapped to Students table."
},
{
"code": null,
"e": 6653,
"s": 6335,
"text": "#myclasses.py\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Numeric\nbase=declarative_base()\nclass Student(base):\n __tablename__='Students'\n StudentID=Column(Integer, primary_key=True)\n name=Column(String)\n age=Column(Integer)\n marks=Column(Numeric) "
},
{
"code": null,
"e": 6768,
"s": 6653,
"text": "To create a Students table that has a corresponding structure, execute create_all() method defined for base class."
},
{
"code": null,
"e": 6802,
"s": 6768,
"text": "base.metadata.create_all(engine)\n"
},
{
"code": null,
"e": 6974,
"s": 6802,
"text": "We now have to declare an object of our Student class. All database transactions such as add, delete or retrieve data from database, etc., are handled by a Session object."
},
{
"code": null,
"e": 7074,
"s": 6974,
"text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsessionobj = Session()\n"
},
{
"code": null,
"e": 7171,
"s": 7074,
"text": "Data stored in Student object is physically added in underlying table by session’s add() method."
},
{
"code": null,
"e": 7256,
"s": 7171,
"text": "s1 = Student(name='Juhi', age=25, marks=200)\nsessionobj.add(s1)\nsessionobj.commit()\n"
},
{
"code": null,
"e": 7394,
"s": 7256,
"text": "Here, is the entire code for adding record in students table. As it is executed, corresponding SQL statement log is displayed on console."
},
{
"code": null,
"e": 7789,
"s": 7394,
"text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nfrom myclasses import Student, base\nengine = create_engine('sqlite:///college.db', echo=True)\nbase.metadata.create_all(engine)\n\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsessionobj = Session()\ns1 = Student(name='Juhi', age=25, marks=200)\nsessionobj.add(s1)\nsessionobj.commit()"
},
{
"code": null,
"e": 8253,
"s": 7789,
"text": "CREATE TABLE \"Students\" (\n \"StudentID\" INTEGER NOT NULL,\n name VARCHAR,\n age INTEGER,\n marks NUMERIC,\n PRIMARY KEY (\"StudentID\")\n)\nINFO sqlalchemy.engine.base.Engine ()\nINFO sqlalchemy.engine.base.Engine COMMIT\nINFO sqlalchemy.engine.base.Engine BEGIN (implicit)\nINFO sqlalchemy.engine.base.Engine INSERT INTO \"Students\" (name, age, marks) VALUES (?, ?, ?)\nINFO sqlalchemy.engine.base.Engine ('Juhi', 25, 200.0)\nINFO sqlalchemy.engine.base.Engine COMMIT"
},
{
"code": null,
"e": 8360,
"s": 8253,
"text": "The session object also provides add_all() method to insert more than one objects in a single transaction."
},
{
"code": null,
"e": 8415,
"s": 8360,
"text": "sessionobj.add_all([s2,s3,s4,s5])\nsessionobj.commit()\n"
},
{
"code": null,
"e": 8639,
"s": 8415,
"text": "Now that, records are added in the table, we would like to fetch from it just as SELECT query does. The session object has query() method to perform the task. Query object is returned by query() method on our Student model."
},
{
"code": null,
"e": 8670,
"s": 8639,
"text": "qry=seesionobj.query(Student)\n"
},
{
"code": null,
"e": 8763,
"s": 8670,
"text": "Use the get() method of this Query object fetches object corresponding to given primary key."
},
{
"code": null,
"e": 8778,
"s": 8763,
"text": "S1=qry.get(1)\n"
},
{
"code": null,
"e": 8887,
"s": 8778,
"text": "While this statement is executed, its corresponding SQL statement echoed on the console will be as follows −"
},
{
"code": null,
"e": 9157,
"s": 8887,
"text": "BEGIN (implicit)\nSELECT \"Students\".\"StudentID\" AS \"Students_StudentID\", \"Students\".name AS \n \"Students_name\", \"Students\".age AS \"Students_age\", \n \"Students\".marks AS \"Students_marks\"\nFROM \"Students\"\nWHERE \"Products\".\"Students\" = ?\nsqlalchemy.engine.base.Engine (1,)"
},
{
"code": null,
"e": 9247,
"s": 9157,
"text": "The query.all() method returns a list of all objects which can be traversed using a loop."
},
{
"code": null,
"e": 9643,
"s": 9247,
"text": "from sqlalchemy import Column, Integer, String, Numeric\nfrom sqlalchemy import create_engine\nfrom myclasses import Student,base\nengine = create_engine('sqlite:///college.db', echo=True)\nbase.metadata.create_all(engine)\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsessionobj = Session()\nqry=sessionobj.query(Students)\nrows=qry.all()\nfor row in rows:\n print (row)"
},
{
"code": null,
"e": 9888,
"s": 9643,
"text": "Updating a record in the mapped table is very easy. All you have to do is fetch a record using get() method, assign a new value to desired attribute and then commit the changes using session object. Below we change marks of Juhi student to 100."
},
{
"code": null,
"e": 9935,
"s": 9888,
"text": "S1=qry.get(1)\nS1.marks=100\nsessionobj.commit()"
},
{
"code": null,
"e": 10015,
"s": 9935,
"text": "Deleting a record is just as easy, by deleting desired object from the session."
},
{
"code": null,
"e": 10071,
"s": 10015,
"text": "S1=qry.get(1)\nSessionobj.delete(S1)\nsessionobj.commit()"
},
{
"code": null,
"e": 10108,
"s": 10071,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 10124,
"s": 10108,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10157,
"s": 10124,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10176,
"s": 10157,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10211,
"s": 10176,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 10233,
"s": 10211,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 10267,
"s": 10233,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 10295,
"s": 10267,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10330,
"s": 10295,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 10344,
"s": 10330,
"text": " Lets Kode It"
},
{
"code": null,
"e": 10377,
"s": 10344,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10394,
"s": 10377,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10401,
"s": 10394,
"text": " Print"
},
{
"code": null,
"e": 10412,
"s": 10401,
"text": " Add Notes"
}
] |
Probably the Best Practice of Object-Oriented Python — Attr | by Christopher Tao | Towards Data Science
|
It is known that Python is very flexible that can be written in functional, procedural and object-oriented. Honestly, I rarely write classes in Python unless I have to, just because most of the time I don’t want to over-engineered the problems. For example, it probably does not make too much sense to use object-oriented programming when we use Python to perform some ad-hoc data analysis.
However, things got changed when I knew the library called “Attrs”. It makes Python be programmed in object-oriented mode even easier (I think Python’s object-oriented programming is already very concise and easy). In this article, I will introduce this library regarding how it can facilitate Pythonic Object-Oriented Programming.
www.attrs.org
Like most of the Python libraries, we can simply install attrs using pip.
pip install attrs
Now, let’s code a class in Python without any libraries.
class Person(object): def __init__(self, name, age): self.name = name self.age = age p1 = Person('Chris', 32)p2 = Person('Chris', 32)
Please note that I have also instantiated two instances with the same values the attributes.
When we output the instance, we can only get the name of the class. Also, the two instances with the same values of their attributes will not be considered equal because they are not pointing to the same memory address.
Then, what attrs can do for us? Let’s do the same thing here.
from attr import attrs, attrib@attrsclass Person(object): name = attrib() age = attrib() p1 = Person('Chris', 32)p2 = Person('Chris', 32)
Something needs to have a simple explanation I guess. Firstly, the @attrs is the annotation that tells this class is going to be declared with the attrs library. Then, for each attribute, we only need to define them as attrib() and it is not necessary to have a __init__() method. After that, we can simply instantiate the class just like there was an __init__ method.
Let’s also try output and equal testing.
Obviously, we have a very meaningful output of the object, as well as we can test the equality between objects.
You may have a question now. What if there is such an attribute that we don’t want to initialise it during instantiation but probably assign value to it later? Of course, if you still use attrib() as follows, it will not work.
With attrs, you can achieve this by passing the init argument with False.
@attrsclass Person(object): name = attrib() age = attrib() skills = attrib(init=False) p1 = Person('Chris', 32)
As shown, we don’t have to give the value of skills initially, but we can assign it later on.
You may also ask how about I want to give default values to the attributes? Yes, with attrs you can do that easily.
@attrsclass Person(object): name = attrib(default='Chris') age = attrib(default=32) p1 = Person()p2 = Person('Chris', 32)
As shown, we give both the attributes default values. Then, the instance without any arguments passed in is exactly the same as the other one that is explicitly initialised with arguments.
What if we want to have an attribute with an empty collection as a default value? Usually, we don’t want to pass an [] in as an argument, this is one of the famous traps of Python that may cause a lot of unexpected problems. Don’t worry, attrs provides a “factory” for us.
@attrsclass Person(object): name = attrib(default='Chris') age = attrib(default=32) skills = attrib(factory=list)
As shown, the attribute skills was empty initially, but later on, we can append values to it.
Now, we want to add some validation to the attributes to make sure that the values we passed in are valid. It is also very easy to implemented using attrs.
@attrsclass Student(object): name = attrib() age = attrib() student_id = attrib() @student_id.validator def check_student_id(self, attribute, value): if len(str(value)) != 6: raise ValueError(f'student_id must be 6 characters! got {len(str(value))}')
In the above example, we have declared a “Student” class with the attribute “student_id”. Suppose that we want to validate the student id that it must be 6 characters long.
Note that we need to define a function to do this. The function needs to be annotated as @<attribute_name>.validator. Therefore, in our case, this should be @student_id.validator. Then, we can raise an exception in this validating function as above shown.
Let’s have a simple test.
The first instance s1 doesn’t have any problem because its student_id has a length of 6, but the second instance s2 won’t pass because the length is 5, and the exception with a pre-defined error message is correctly displayed.
In plain Python, we have to use the super() function in the __init__() function to achieve inheritance. This will be super complex when we want a multi-inheritance. attrs makes it extremely easy.
@attrsclass Person(object): name = attrib() age = attrib() def get_name(self): return self.name @attrsclass User(object): user_id = attrib() def get_user_id(self): return self.user_id @attrsclass Student(Person, User): student_id = attrib() def get_student_id(self): return self.student_idstudent = Student(name='Chris', age=32, user_id='ctao', student_id=123456)
In the above example, Student inherits from both Person and User. In the Student class, we only need to define its specific attribute student_id, and the other attributes from both Person and User will be automatically inherited directly without any verbose definitions.
As shown above, the functions are inherited without problems too.
The attrs library can also help us to easily serialise the instances to dictionaries. After that, you may use that in JSON and do whatever you want to do.
attr.asdict(student)
In this article, I have introduced the library attrs and some of the basic usage. I like this library because it makes Python even simpler and more concise. It is highly recommended to try it out if you haven’t used it before. Hope you will like it, too.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
|
[
{
"code": null,
"e": 438,
"s": 47,
"text": "It is known that Python is very flexible that can be written in functional, procedural and object-oriented. Honestly, I rarely write classes in Python unless I have to, just because most of the time I don’t want to over-engineered the problems. For example, it probably does not make too much sense to use object-oriented programming when we use Python to perform some ad-hoc data analysis."
},
{
"code": null,
"e": 770,
"s": 438,
"text": "However, things got changed when I knew the library called “Attrs”. It makes Python be programmed in object-oriented mode even easier (I think Python’s object-oriented programming is already very concise and easy). In this article, I will introduce this library regarding how it can facilitate Pythonic Object-Oriented Programming."
},
{
"code": null,
"e": 784,
"s": 770,
"text": "www.attrs.org"
},
{
"code": null,
"e": 858,
"s": 784,
"text": "Like most of the Python libraries, we can simply install attrs using pip."
},
{
"code": null,
"e": 876,
"s": 858,
"text": "pip install attrs"
},
{
"code": null,
"e": 933,
"s": 876,
"text": "Now, let’s code a class in Python without any libraries."
},
{
"code": null,
"e": 1091,
"s": 933,
"text": "class Person(object): def __init__(self, name, age): self.name = name self.age = age p1 = Person('Chris', 32)p2 = Person('Chris', 32)"
},
{
"code": null,
"e": 1184,
"s": 1091,
"text": "Please note that I have also instantiated two instances with the same values the attributes."
},
{
"code": null,
"e": 1404,
"s": 1184,
"text": "When we output the instance, we can only get the name of the class. Also, the two instances with the same values of their attributes will not be considered equal because they are not pointing to the same memory address."
},
{
"code": null,
"e": 1466,
"s": 1404,
"text": "Then, what attrs can do for us? Let’s do the same thing here."
},
{
"code": null,
"e": 1613,
"s": 1466,
"text": "from attr import attrs, attrib@attrsclass Person(object): name = attrib() age = attrib() p1 = Person('Chris', 32)p2 = Person('Chris', 32)"
},
{
"code": null,
"e": 1982,
"s": 1613,
"text": "Something needs to have a simple explanation I guess. Firstly, the @attrs is the annotation that tells this class is going to be declared with the attrs library. Then, for each attribute, we only need to define them as attrib() and it is not necessary to have a __init__() method. After that, we can simply instantiate the class just like there was an __init__ method."
},
{
"code": null,
"e": 2023,
"s": 1982,
"text": "Let’s also try output and equal testing."
},
{
"code": null,
"e": 2135,
"s": 2023,
"text": "Obviously, we have a very meaningful output of the object, as well as we can test the equality between objects."
},
{
"code": null,
"e": 2362,
"s": 2135,
"text": "You may have a question now. What if there is such an attribute that we don’t want to initialise it during instantiation but probably assign value to it later? Of course, if you still use attrib() as follows, it will not work."
},
{
"code": null,
"e": 2436,
"s": 2362,
"text": "With attrs, you can achieve this by passing the init argument with False."
},
{
"code": null,
"e": 2560,
"s": 2436,
"text": "@attrsclass Person(object): name = attrib() age = attrib() skills = attrib(init=False) p1 = Person('Chris', 32)"
},
{
"code": null,
"e": 2654,
"s": 2560,
"text": "As shown, we don’t have to give the value of skills initially, but we can assign it later on."
},
{
"code": null,
"e": 2770,
"s": 2654,
"text": "You may also ask how about I want to give default values to the attributes? Yes, with attrs you can do that easily."
},
{
"code": null,
"e": 2901,
"s": 2770,
"text": "@attrsclass Person(object): name = attrib(default='Chris') age = attrib(default=32) p1 = Person()p2 = Person('Chris', 32)"
},
{
"code": null,
"e": 3090,
"s": 2901,
"text": "As shown, we give both the attributes default values. Then, the instance without any arguments passed in is exactly the same as the other one that is explicitly initialised with arguments."
},
{
"code": null,
"e": 3363,
"s": 3090,
"text": "What if we want to have an attribute with an empty collection as a default value? Usually, we don’t want to pass an [] in as an argument, this is one of the famous traps of Python that may cause a lot of unexpected problems. Don’t worry, attrs provides a “factory” for us."
},
{
"code": null,
"e": 3486,
"s": 3363,
"text": "@attrsclass Person(object): name = attrib(default='Chris') age = attrib(default=32) skills = attrib(factory=list)"
},
{
"code": null,
"e": 3580,
"s": 3486,
"text": "As shown, the attribute skills was empty initially, but later on, we can append values to it."
},
{
"code": null,
"e": 3736,
"s": 3580,
"text": "Now, we want to add some validation to the attributes to make sure that the values we passed in are valid. It is also very easy to implemented using attrs."
},
{
"code": null,
"e": 4024,
"s": 3736,
"text": "@attrsclass Student(object): name = attrib() age = attrib() student_id = attrib() @student_id.validator def check_student_id(self, attribute, value): if len(str(value)) != 6: raise ValueError(f'student_id must be 6 characters! got {len(str(value))}')"
},
{
"code": null,
"e": 4197,
"s": 4024,
"text": "In the above example, we have declared a “Student” class with the attribute “student_id”. Suppose that we want to validate the student id that it must be 6 characters long."
},
{
"code": null,
"e": 4453,
"s": 4197,
"text": "Note that we need to define a function to do this. The function needs to be annotated as @<attribute_name>.validator. Therefore, in our case, this should be @student_id.validator. Then, we can raise an exception in this validating function as above shown."
},
{
"code": null,
"e": 4479,
"s": 4453,
"text": "Let’s have a simple test."
},
{
"code": null,
"e": 4706,
"s": 4479,
"text": "The first instance s1 doesn’t have any problem because its student_id has a length of 6, but the second instance s2 won’t pass because the length is 5, and the exception with a pre-defined error message is correctly displayed."
},
{
"code": null,
"e": 4902,
"s": 4706,
"text": "In plain Python, we have to use the super() function in the __init__() function to achieve inheritance. This will be super complex when we want a multi-inheritance. attrs makes it extremely easy."
},
{
"code": null,
"e": 5326,
"s": 4902,
"text": "@attrsclass Person(object): name = attrib() age = attrib() def get_name(self): return self.name @attrsclass User(object): user_id = attrib() def get_user_id(self): return self.user_id @attrsclass Student(Person, User): student_id = attrib() def get_student_id(self): return self.student_idstudent = Student(name='Chris', age=32, user_id='ctao', student_id=123456)"
},
{
"code": null,
"e": 5597,
"s": 5326,
"text": "In the above example, Student inherits from both Person and User. In the Student class, we only need to define its specific attribute student_id, and the other attributes from both Person and User will be automatically inherited directly without any verbose definitions."
},
{
"code": null,
"e": 5663,
"s": 5597,
"text": "As shown above, the functions are inherited without problems too."
},
{
"code": null,
"e": 5818,
"s": 5663,
"text": "The attrs library can also help us to easily serialise the instances to dictionaries. After that, you may use that in JSON and do whatever you want to do."
},
{
"code": null,
"e": 5839,
"s": 5818,
"text": "attr.asdict(student)"
},
{
"code": null,
"e": 6094,
"s": 5839,
"text": "In this article, I have introduced the library attrs and some of the basic usage. I like this library because it makes Python even simpler and more concise. It is highly recommended to try it out if you haven’t used it before. Hope you will like it, too."
},
{
"code": null,
"e": 6105,
"s": 6094,
"text": "medium.com"
}
] |
What is the significant difference between MySQL TRUNCATE and DROP command?
|
The most significant difference between MySQL TRUNCATE and DROP command is that TRUNCATE command will not destroy table’s structure but in contrast DROP command will destroy table’s structure too.
mysql> Create table testing(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,Name Varchar(20));
Query OK, 0 rows affected (0.24 sec)
mysql> Insert into testing(Name) Values('Ram'),('Mohan'),('John');
Query OK, 3 rows affected (0.12 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+-------+
| id | Name |
+----+-------+
| 1 | Ram |
| 2 | Mohan |
| 3 | John |
+----+-------+
3 rows in set (0.00 sec)
Now after TRUNCATING the ‘testing’ table as follows, still its structure remains in the database and it also initializes the PRIMARY KEY.
mysql> Truncate table testing;
Query OK, 0 rows affected (0.04 sec)
mysql> DESCRIBE testing;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| Name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.21 sec)
But when we apply DROP command on a table then the structure also deleted from the database.
mysql> Drop table testing;
Query OK, 0 rows affected (0.08 sec)
mysql> DESCRIBE testing;
ERROR 1146 (42S02): Table 'query.testing' doesn't exist
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "The most significant difference between MySQL TRUNCATE and DROP command is that TRUNCATE command will not destroy table’s structure but in contrast DROP command will destroy table’s structure too."
},
{
"code": null,
"e": 1689,
"s": 1259,
"text": "mysql> Create table testing(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,Name Varchar(20));\nQuery OK, 0 rows affected (0.24 sec)\n\nmysql> Insert into testing(Name) Values('Ram'),('Mohan'),('John');\nQuery OK, 3 rows affected (0.12 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\n\nmysql> Select * from testing;\n+----+-------+\n| id | Name |\n+----+-------+\n| 1 | Ram |\n| 2 | Mohan |\n| 3 | John |\n+----+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1827,
"s": 1689,
"text": "Now after TRUNCATING the ‘testing’ table as follows, still its structure remains in the database and it also initializes the PRIMARY KEY."
},
{
"code": null,
"e": 2330,
"s": 1827,
"text": "mysql> Truncate table testing;\nQuery OK, 0 rows affected (0.04 sec)\n\nmysql> DESCRIBE testing;\n+-------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+---------+----------------+\n| id | int(11) | NO | PRI | NULL | auto_increment |\n| Name | varchar(20) | YES | | NULL | |\n+-------+-------------+------+-----+---------+----------------+\n2 rows in set (0.21 sec)"
},
{
"code": null,
"e": 2423,
"s": 2330,
"text": "But when we apply DROP command on a table then the structure also deleted from the database."
},
{
"code": null,
"e": 2569,
"s": 2423,
"text": "mysql> Drop table testing;\nQuery OK, 0 rows affected (0.08 sec)\n\nmysql> DESCRIBE testing;\nERROR 1146 (42S02): Table 'query.testing' doesn't exist"
}
] |
Autorun a Python script on windows startup?
|
Appending a Python script to windows start-up basically indicates the python script will run as the windows boots up. This can be accomplished by two step processes -
Step #1: Appending or Adding script to windows Startup folder
After booting up of the windows, it executes (equivalent to double-clicking) all the application present in its startup folder or directory.
C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
By default, the AppData directory or folder under the current_user is hidden that enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Besides this the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing.
Step #2: Appending or adding script to windows Registry
This process may be risky if not accomplished properly, it includes editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry consists of the list of programs that must execute once the user Login. Registry Path−
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
# Python code to append or add current script to the registry
# module to modify or edit the windows registry
importwinreg as reg1
importos
# in python __file__ is denoeted as the instant of
# file path where it was run or executed
# so if it was executed from desktop,
# then __file__ will be
# c:\users\current_user\desktop
pth1 =os.path.dirname(os.path.realpath(__file__))
# Python file name with extension
s_name1="mYscript.py"
# The file name is joined to end of path address
address1=os.join(pth1,s_name1)
# key we want to modify or change is HKEY_CURRENT_USER
# key value is Software\Microsoft\Windows\CurrentVersion\Run
key1 =HKEY_CURRENT_USER
key_value1 ="Software\Microsoft\Windows\CurrentVersion\Run"
# open the key to make modifications or changes to
open=reg1.OpenKey(key1,key_value1,0,reg1.KEY_ALL_ACCESS)
# change or modifiy the opened key
reg1.SetValueEx(open,"any_name",0,reg1.REG_SZ,address1)
# now close the opened key
reg1.CloseKey(open)
# Driver Code
if__name__=="__main__":
AddToRegistry()
|
[
{
"code": null,
"e": 1229,
"s": 1062,
"text": "Appending a Python script to windows start-up basically indicates the python script will run as the windows boots up. This can be accomplished by two step processes -"
},
{
"code": null,
"e": 1291,
"s": 1229,
"text": "Step #1: Appending or Adding script to windows Startup folder"
},
{
"code": null,
"e": 1432,
"s": 1291,
"text": "After booting up of the windows, it executes (equivalent to double-clicking) all the application present in its startup folder or directory."
},
{
"code": null,
"e": 1517,
"s": 1432,
"text": "C:\\Users\\current_user\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\"
},
{
"code": null,
"e": 1837,
"s": 1517,
"text": "By default, the AppData directory or folder under the current_user is hidden that enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Besides this the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing."
},
{
"code": null,
"e": 1893,
"s": 1837,
"text": "Step #2: Appending or adding script to windows Registry"
},
{
"code": null,
"e": 2144,
"s": 1893,
"text": "This process may be risky if not accomplished properly, it includes editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry consists of the list of programs that must execute once the user Login. Registry Path−"
},
{
"code": null,
"e": 2208,
"s": 2144,
"text": "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
},
{
"code": null,
"e": 2348,
"s": 2208,
"text": "# Python code to append or add current script to the registry\n# module to modify or edit the windows registry\nimportwinreg as reg1\nimportos"
},
{
"code": null,
"e": 3280,
"s": 2348,
"text": " # in python __file__ is denoeted as the instant of\n # file path where it was run or executed\n # so if it was executed from desktop,\n # then __file__ will be\n # c:\\users\\current_user\\desktop\n pth1 =os.path.dirname(os.path.realpath(__file__))\n # Python file name with extension\n s_name1=\"mYscript.py\"\n # The file name is joined to end of path address\n address1=os.join(pth1,s_name1)\n # key we want to modify or change is HKEY_CURRENT_USER\n # key value is Software\\Microsoft\\Windows\\CurrentVersion\\Run\n key1 =HKEY_CURRENT_USER\n key_value1 =\"Software\\Microsoft\\Windows\\CurrentVersion\\Run\"\n # open the key to make modifications or changes to\n open=reg1.OpenKey(key1,key_value1,0,reg1.KEY_ALL_ACCESS)\n # change or modifiy the opened key\n reg1.SetValueEx(open,\"any_name\",0,reg1.REG_SZ,address1)\n # now close the opened key\n reg1.CloseKey(open)\n# Driver Code\nif__name__==\"__main__\":\nAddToRegistry()"
}
] |
Kotlin Data Types
|
In Kotlin, the type of a variable is decided by its value:
val myNum = 5 // Int
val myDoubleNum = 5.99 // Double
val myLetter = 'D' // Char
val myBoolean = true // Boolean
val myText = "Hello" // String
However, you learned from the previous chapter that it is possible to specify the type if you want:
val myNum: Int = 5 // Int
val myDoubleNum: Double = 5.99 // Double
val myLetter: Char = 'D' // Char
val myBoolean: Boolean = true // Boolean
val myText: String = "Hello" // String
Sometimes you have to specify the type, and often you don't. Anyhow, it is
good to know what the different types represent.
You will learn more about when you need to specify the type later.
Data types are divided into different groups:
Numbers
Characters
Booleans
Strings
Arrays
Number types are divided into two groups:
Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are Byte,
Short, Int
and Long.
Floating point types represent numbers with a fractional part,
containing one or more decimals. There are two types:
Float and Double.
If you don't specify the type for a numeric variable, it is most often
returned as Int for whole numbers and Double for floating point numbers.
The Byte data type can store whole numbers
from -128 to 127. This can be used instead of Int or other integer types to
save memory when you are certain that the value will be within -128 and 127:
val myNum: Byte = 100
println(myNum)
The Short data type can store whole numbers from -32768 to 32767:
val myNum: Short = 5000
println(myNum)
The Int data type can store whole numbers
from -2147483648 to 2147483647:
val myNum: Int = 100000
println(myNum)
The Long data type can store whole numbers from -9223372036854775807 to 9223372036854775807. This is used when
Int is not large enough to store the value.
Optionally, you can end the value with an "L":
val myNum: Long = 15000000000L
println(myNum)
A whole number is an Int as long as it is up to 2147483647. If it goes beyond
that, it is defined as Long:
val myNum1 = 2147483647 // Int
val myNum2 = 2147483648 // Long
Floating point types represent numbers with a decimal, such as 9.99 or 3.14515.
The Float and Double data types can store fractional numbers:
val myNum: Float = 5.75F
println(myNum)
val myNum: Double = 19.99
println(myNum)
Use Float or Double?
The precision of a floating point value indicates how many digits the value can have
after the decimal point.
The precision of Float is only six or seven
decimal digits, while Double variables have a precision
of about 15 digits. Therefore it is safer to use Double for most calculations.
Also note that you should end the value of a Float type with an "F".
A floating point number can also be a scientific number with an "e" or "E" to indicate the power of 10:
val myNum1: Float = 35E3F
val myNum2: Double = 12E4
println(myNum1)
println(myNum2)
The Boolean data type and can only take the values true or false:
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun) // Outputs true
println(isFishTasty) // Outputs false
Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.
The Char data type is used to store a
single character. A char value must be
surrounded by single quotes, like 'A' or 'c':
val myGrade: Char = 'B'
println(myGrade)
Unlike Java, you cannot use ASCII values to display certain characters. The
value 66 would output a "B" in Java, but will generate an error in Kotlin:
val myLetter: Char = 66
println(myLetter) // Error
The String data type is used to store a sequence of characters (text). String values must be surrounded by
double quotes:
val myText: String = "Hello World"
println(myText)
You will learn more about strings in the Strings chapter.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
You will learn more about arrays in the Arrays chapter.
Type conversion is when you convert the value of one data type to another type.
In Kotlin, numeric type conversion is different from Java. For example, it is not possible to convert an Int type to a Long type with the following code:
val x: Int = 5
val y: Long = x
println(y) // Error: Type mismatch
To convert a numeric data type to another type, you must use one of the following functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble() or toChar():
val x: Int = 5
val y: Long = x.toLong()
println(y)
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": 59,
"s": 0,
"text": "In Kotlin, the type of a variable is decided by its value:"
},
{
"code": null,
"e": 235,
"s": 59,
"text": "val myNum = 5 // Int\nval myDoubleNum = 5.99 // Double\nval myLetter = 'D' // Char\nval myBoolean = true // Boolean\nval myText = \"Hello\" // String"
},
{
"code": null,
"e": 335,
"s": 235,
"text": "However, you learned from the previous chapter that it is possible to specify the type if you want:"
},
{
"code": null,
"e": 551,
"s": 335,
"text": "val myNum: Int = 5 // Int\nval myDoubleNum: Double = 5.99 // Double\nval myLetter: Char = 'D' // Char\nval myBoolean: Boolean = true // Boolean\nval myText: String = \"Hello\" // String"
},
{
"code": null,
"e": 677,
"s": 551,
"text": "Sometimes you have to specify the type, and often you don't. Anyhow, it is \ngood to know what the different types represent.\n"
},
{
"code": null,
"e": 744,
"s": 677,
"text": "You will learn more about when you need to specify the type later."
},
{
"code": null,
"e": 790,
"s": 744,
"text": "Data types are divided into different groups:"
},
{
"code": null,
"e": 798,
"s": 790,
"text": "Numbers"
},
{
"code": null,
"e": 809,
"s": 798,
"text": "Characters"
},
{
"code": null,
"e": 818,
"s": 809,
"text": "Booleans"
},
{
"code": null,
"e": 826,
"s": 818,
"text": "Strings"
},
{
"code": null,
"e": 833,
"s": 826,
"text": "Arrays"
},
{
"code": null,
"e": 875,
"s": 833,
"text": "Number types are divided into two groups:"
},
{
"code": null,
"e": 1018,
"s": 875,
"text": "Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals. \nValid types are Byte, \nShort, Int \nand Long."
},
{
"code": null,
"e": 1155,
"s": 1018,
"text": "Floating point types represent numbers with a fractional part, \ncontaining one or more decimals. There are two types: \nFloat and Double."
},
{
"code": null,
"e": 1300,
"s": 1155,
"text": "If you don't specify the type for a numeric variable, it is most often \nreturned as Int for whole numbers and Double for floating point numbers."
},
{
"code": null,
"e": 1498,
"s": 1300,
"text": "The Byte data type can store whole numbers \nfrom -128 to 127. This can be used instead of Int or other integer types to \nsave memory when you are certain that the value will be within -128 and 127:"
},
{
"code": null,
"e": 1535,
"s": 1498,
"text": "val myNum: Byte = 100\nprintln(myNum)"
},
{
"code": null,
"e": 1601,
"s": 1535,
"text": "The Short data type can store whole numbers from -32768 to 32767:"
},
{
"code": null,
"e": 1640,
"s": 1601,
"text": "val myNum: Short = 5000\nprintln(myNum)"
},
{
"code": null,
"e": 1715,
"s": 1640,
"text": "The Int data type can store whole numbers \nfrom -2147483648 to 2147483647:"
},
{
"code": null,
"e": 1754,
"s": 1715,
"text": "val myNum: Int = 100000\nprintln(myNum)"
},
{
"code": null,
"e": 1958,
"s": 1754,
"text": "The Long data type can store whole numbers from -9223372036854775807 to 9223372036854775807. This is used when \nInt is not large enough to store the value. \nOptionally, you can end the value with an \"L\":"
},
{
"code": null,
"e": 2004,
"s": 1958,
"text": "val myNum: Long = 15000000000L\nprintln(myNum)"
},
{
"code": null,
"e": 2112,
"s": 2004,
"text": "A whole number is an Int as long as it is up to 2147483647. If it goes beyond \nthat, it is defined as Long:"
},
{
"code": null,
"e": 2177,
"s": 2112,
"text": "val myNum1 = 2147483647 // Int\nval myNum2 = 2147483648 // Long"
},
{
"code": null,
"e": 2257,
"s": 2177,
"text": "Floating point types represent numbers with a decimal, such as 9.99 or 3.14515."
},
{
"code": null,
"e": 2319,
"s": 2257,
"text": "The Float and Double data types can store fractional numbers:"
},
{
"code": null,
"e": 2359,
"s": 2319,
"text": "val myNum: Float = 5.75F\nprintln(myNum)"
},
{
"code": null,
"e": 2400,
"s": 2359,
"text": "val myNum: Double = 19.99\nprintln(myNum)"
},
{
"code": null,
"e": 2421,
"s": 2400,
"text": "Use Float or Double?"
},
{
"code": null,
"e": 2713,
"s": 2421,
"text": "The precision of a floating point value indicates how many digits the value can have \nafter the decimal point.\nThe precision of Float is only six or seven \ndecimal digits, while Double variables have a precision \nof about 15 digits. Therefore it is safer to use Double for most calculations."
},
{
"code": null,
"e": 2782,
"s": 2713,
"text": "Also note that you should end the value of a Float type with an \"F\"."
},
{
"code": null,
"e": 2886,
"s": 2782,
"text": "A floating point number can also be a scientific number with an \"e\" or \"E\" to indicate the power of 10:"
},
{
"code": null,
"e": 2970,
"s": 2886,
"text": "val myNum1: Float = 35E3F\nval myNum2: Double = 12E4\nprintln(myNum1)\nprintln(myNum2)"
},
{
"code": null,
"e": 3036,
"s": 2970,
"text": "The Boolean data type and can only take the values true or false:"
},
{
"code": null,
"e": 3181,
"s": 3036,
"text": "val isKotlinFun: Boolean = true\nval isFishTasty: Boolean = false\nprintln(isKotlinFun) // Outputs true\nprintln(isFishTasty) // Outputs false "
},
{
"code": null,
"e": 3289,
"s": 3181,
"text": "Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter."
},
{
"code": null,
"e": 3414,
"s": 3289,
"text": "The Char data type is used to store a \nsingle character. A char value must be \nsurrounded by single quotes, like 'A' or 'c':"
},
{
"code": null,
"e": 3455,
"s": 3414,
"text": "val myGrade: Char = 'B'\nprintln(myGrade)"
},
{
"code": null,
"e": 3607,
"s": 3455,
"text": "Unlike Java, you cannot use ASCII values to display certain characters. The \nvalue 66 would output a \"B\" in Java, but will generate an error in Kotlin:"
},
{
"code": null,
"e": 3658,
"s": 3607,
"text": "val myLetter: Char = 66\nprintln(myLetter) // Error"
},
{
"code": null,
"e": 3781,
"s": 3658,
"text": "The String data type is used to store a sequence of characters (text). String values must be surrounded by \ndouble quotes:"
},
{
"code": null,
"e": 3832,
"s": 3781,
"text": "val myText: String = \"Hello World\"\nprintln(myText)"
},
{
"code": null,
"e": 3890,
"s": 3832,
"text": "You will learn more about strings in the Strings chapter."
},
{
"code": null,
"e": 4009,
"s": 3890,
"text": "Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value."
},
{
"code": null,
"e": 4065,
"s": 4009,
"text": "You will learn more about arrays in the Arrays chapter."
},
{
"code": null,
"e": 4145,
"s": 4065,
"text": "Type conversion is when you convert the value of one data type to another type."
},
{
"code": null,
"e": 4299,
"s": 4145,
"text": "In Kotlin, numeric type conversion is different from Java. For example, it is not possible to convert an Int type to a Long type with the following code:"
},
{
"code": null,
"e": 4366,
"s": 4299,
"text": "val x: Int = 5\nval y: Long = x\nprintln(y) // Error: Type mismatch "
},
{
"code": null,
"e": 4534,
"s": 4366,
"text": "To convert a numeric data type to another type, you must use one of the following functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble() or toChar():"
},
{
"code": null,
"e": 4585,
"s": 4534,
"text": "val x: Int = 5\nval y: Long = x.toLong()\nprintln(y)"
},
{
"code": null,
"e": 4618,
"s": 4585,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4660,
"s": 4618,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4767,
"s": 4660,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 4786,
"s": 4767,
"text": "help@w3schools.com"
}
] |
Add Count and Percentage Labels on Top of Histogram Bars in R - GeeksforGeeks
|
30 Jun, 2021
A histogram denotes the frequencies or contingency of values of the specified variable segregated into ranges. It groups the values into continuous ranges. Each bar of the histogram is used to denote the height, that is the number of values present in that specific range.
The hist() method in base R is used to display a histogram of the given data values. It takes as input a vector of the data values and outputs a corresponding histogram for the same.
Syntax:
hist ( x , labels)
Parameter :
x – The set of data points to plot
labels – By default, FALSE. If true, it is used to denote a set of counts on the top of bars. It can also take a function , a character or numeric vector .
Let us first create a regular histogram so that the difference is apparent.
Example:
R
# setting the seed valueset.seed(67832) # define x values using the# rnorm methodxpos <- rnorm(50) # plotting the histogram hist(xpos , ylim=c(0,20))
Output
In order to compute the counts of the number of values encountered in each range, the labels attribute can be set to TRUE.
Syntax:
hist(..., labels=TRUE,..)
Example:
R
# setting the seed valueset.seed(67832) # define x values using the # rnorm methodxpos <- rnorm(50) # plotting the histogram hist(xpos , labels = TRUE, ylim=c(0,20))
Output
The percentage can be computed using mathematical functions. Initially, the histogram without any labels is stored in a variable. Its counts can be accessed using the counts attribute of the extracted histogram variable. This returns an integer vector of values each of which is divided by the length of the input data vector. These values are multiplied by 100 to turn into decimal values.
The decimal values can be rounded off to a specific number of digits using the round() method in R programming language.
Syntax:
round(num , digits)
The paste0() method can be used to concatenate values together and append a “%” sign to the corresponding values. In this method, the separator is an empty string by default.
Syntax:
paste0(val , “%”)
Example:
R
# setting the seed valueset.seed(67832) # define x values using the rnorm methodxpos <- rnorm(50) # computing length of x labelslen <- length(xpos) # drawing a histogram without labelshist_init <- hist(xpos, plot = FALSE) # round the percentage to two placesrounded <- round(hist_init$counts / len * 100, 2) # drawing a histogram # adding % symbol in the valuehist(xpos, labels = paste0(rounded , "%"), ylim=c(0,20))
Output
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25124,
"s": 24851,
"text": "A histogram denotes the frequencies or contingency of values of the specified variable segregated into ranges. It groups the values into continuous ranges. Each bar of the histogram is used to denote the height, that is the number of values present in that specific range."
},
{
"code": null,
"e": 25308,
"s": 25124,
"text": "The hist() method in base R is used to display a histogram of the given data values. It takes as input a vector of the data values and outputs a corresponding histogram for the same. "
},
{
"code": null,
"e": 25316,
"s": 25308,
"text": "Syntax:"
},
{
"code": null,
"e": 25335,
"s": 25316,
"text": "hist ( x , labels)"
},
{
"code": null,
"e": 25348,
"s": 25335,
"text": "Parameter : "
},
{
"code": null,
"e": 25383,
"s": 25348,
"text": "x – The set of data points to plot"
},
{
"code": null,
"e": 25539,
"s": 25383,
"text": "labels – By default, FALSE. If true, it is used to denote a set of counts on the top of bars. It can also take a function , a character or numeric vector ."
},
{
"code": null,
"e": 25615,
"s": 25539,
"text": "Let us first create a regular histogram so that the difference is apparent."
},
{
"code": null,
"e": 25624,
"s": 25615,
"text": "Example:"
},
{
"code": null,
"e": 25626,
"s": 25624,
"text": "R"
},
{
"code": "# setting the seed valueset.seed(67832) # define x values using the# rnorm methodxpos <- rnorm(50) # plotting the histogram hist(xpos , ylim=c(0,20))",
"e": 25778,
"s": 25626,
"text": null
},
{
"code": null,
"e": 25785,
"s": 25778,
"text": "Output"
},
{
"code": null,
"e": 25909,
"s": 25785,
"text": "In order to compute the counts of the number of values encountered in each range, the labels attribute can be set to TRUE. "
},
{
"code": null,
"e": 25917,
"s": 25909,
"text": "Syntax:"
},
{
"code": null,
"e": 25943,
"s": 25917,
"text": "hist(..., labels=TRUE,..)"
},
{
"code": null,
"e": 25952,
"s": 25943,
"text": "Example:"
},
{
"code": null,
"e": 25954,
"s": 25952,
"text": "R"
},
{
"code": "# setting the seed valueset.seed(67832) # define x values using the # rnorm methodxpos <- rnorm(50) # plotting the histogram hist(xpos , labels = TRUE, ylim=c(0,20))",
"e": 26122,
"s": 25954,
"text": null
},
{
"code": null,
"e": 26129,
"s": 26122,
"text": "Output"
},
{
"code": null,
"e": 26521,
"s": 26129,
"text": "The percentage can be computed using mathematical functions. Initially, the histogram without any labels is stored in a variable. Its counts can be accessed using the counts attribute of the extracted histogram variable. This returns an integer vector of values each of which is divided by the length of the input data vector. These values are multiplied by 100 to turn into decimal values. "
},
{
"code": null,
"e": 26642,
"s": 26521,
"text": "The decimal values can be rounded off to a specific number of digits using the round() method in R programming language."
},
{
"code": null,
"e": 26651,
"s": 26642,
"text": "Syntax: "
},
{
"code": null,
"e": 26671,
"s": 26651,
"text": "round(num , digits)"
},
{
"code": null,
"e": 26847,
"s": 26671,
"text": "The paste0() method can be used to concatenate values together and append a “%” sign to the corresponding values. In this method, the separator is an empty string by default. "
},
{
"code": null,
"e": 26855,
"s": 26847,
"text": "Syntax:"
},
{
"code": null,
"e": 26873,
"s": 26855,
"text": "paste0(val , “%”)"
},
{
"code": null,
"e": 26882,
"s": 26873,
"text": "Example:"
},
{
"code": null,
"e": 26884,
"s": 26882,
"text": "R"
},
{
"code": "# setting the seed valueset.seed(67832) # define x values using the rnorm methodxpos <- rnorm(50) # computing length of x labelslen <- length(xpos) # drawing a histogram without labelshist_init <- hist(xpos, plot = FALSE) # round the percentage to two placesrounded <- round(hist_init$counts / len * 100, 2) # drawing a histogram # adding % symbol in the valuehist(xpos, labels = paste0(rounded , \"%\"), ylim=c(0,20))",
"e": 27337,
"s": 26884,
"text": null
},
{
"code": null,
"e": 27344,
"s": 27337,
"text": "Output"
},
{
"code": null,
"e": 27351,
"s": 27344,
"text": "Picked"
},
{
"code": null,
"e": 27360,
"s": 27351,
"text": "R-Charts"
},
{
"code": null,
"e": 27369,
"s": 27360,
"text": "R-Graphs"
},
{
"code": null,
"e": 27377,
"s": 27369,
"text": "R-plots"
},
{
"code": null,
"e": 27388,
"s": 27377,
"text": "R Language"
},
{
"code": null,
"e": 27486,
"s": 27388,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27495,
"s": 27486,
"text": "Comments"
},
{
"code": null,
"e": 27508,
"s": 27495,
"text": "Old Comments"
},
{
"code": null,
"e": 27560,
"s": 27508,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27598,
"s": 27560,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27633,
"s": 27598,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27691,
"s": 27633,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27734,
"s": 27691,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27783,
"s": 27734,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27833,
"s": 27783,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27850,
"s": 27833,
"text": "R - if statement"
},
{
"code": null,
"e": 27887,
"s": 27850,
"text": "How to import an Excel File into R ?"
}
] |
Python - Tkinter place() Method
|
This geometry manager organizes widgets by placing them in a specific position in the parent widget.
widget.place( place_options )
Here is the list of possible options −
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
height, width − Height and width in pixels.
height, width − Height and width in pixels.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
x, y − Horizontal and vertical offset in pixels.
x, y − Horizontal and vertical offset in pixels.
Try the following example by moving cursor on different buttons −
from Tkinter import *
import tkMessageBox
import Tkinter
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
B.place(bordermode=OUTSIDE, height=100, width=100)
top.mainloop()
When the above code is executed, it produces the following result −
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": 2345,
"s": 2244,
"text": "This geometry manager organizes widgets by placing them in a specific position in the parent widget."
},
{
"code": null,
"e": 2376,
"s": 2345,
"text": "widget.place( place_options )\n"
},
{
"code": null,
"e": 2415,
"s": 2376,
"text": "Here is the list of possible options −"
},
{
"code": null,
"e": 2622,
"s": 2415,
"text": "anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)"
},
{
"code": null,
"e": 2829,
"s": 2622,
"text": "anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)"
},
{
"code": null,
"e": 2974,
"s": 2829,
"text": "bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise."
},
{
"code": null,
"e": 3119,
"s": 2974,
"text": "bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise."
},
{
"code": null,
"e": 3163,
"s": 3119,
"text": "height, width − Height and width in pixels."
},
{
"code": null,
"e": 3207,
"s": 3163,
"text": "height, width − Height and width in pixels."
},
{
"code": null,
"e": 3338,
"s": 3207,
"text": "relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3469,
"s": 3338,
"text": "relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3605,
"s": 3469,
"text": "relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3741,
"s": 3605,
"text": "relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3790,
"s": 3741,
"text": "x, y − Horizontal and vertical offset in pixels."
},
{
"code": null,
"e": 3839,
"s": 3790,
"text": "x, y − Horizontal and vertical offset in pixels."
},
{
"code": null,
"e": 3905,
"s": 3839,
"text": "Try the following example by moving cursor on different buttons −"
},
{
"code": null,
"e": 4202,
"s": 3905,
"text": "from Tkinter import *\nimport tkMessageBox\nimport Tkinter\n\ntop = Tkinter.Tk()\n\ndef helloCallBack():\n tkMessageBox.showinfo( \"Hello Python\", \"Hello World\")\n\nB = Tkinter.Button(top, text =\"Hello\", command = helloCallBack)\n\nB.pack()\nB.place(bordermode=OUTSIDE, height=100, width=100)\ntop.mainloop()"
},
{
"code": null,
"e": 4271,
"s": 4202,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4308,
"s": 4271,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4324,
"s": 4308,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4357,
"s": 4324,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4376,
"s": 4357,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4411,
"s": 4376,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4433,
"s": 4411,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4467,
"s": 4433,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4495,
"s": 4467,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4530,
"s": 4495,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4544,
"s": 4530,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4577,
"s": 4544,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4594,
"s": 4577,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4601,
"s": 4594,
"text": " Print"
},
{
"code": null,
"e": 4612,
"s": 4601,
"text": " Add Notes"
}
] |
Predicting the Maliciousness of URLs | by Ruth Eneyi Ikwu | Towards Data Science
|
In this article, we walk through developing a simple feature set representation for identifying malicious URLs. We will create feature vectors for URLs and use these to develop a classification model for identifying malicious URLs. To evaluate how good the features are in separating malicious URLs from benign URLs, we build a Decision-Tree based machine learning model to predict the maliciousness of a given URL.
Malicious websites are well-known threats in cybersecurity. They act as an efficient tool for propagating viruses, worms, and other types of malicious codes online and are responsible for over 60% of most cyber attacks. Malicious URLs can be delivered via email links, text messages, browser pop-ups, page advertisements, etc. These URLs may be links to dodgy websites or most likely have embedded ‘downloadables’. These embedded downloads can be spy-wares, key-loggers, viruses, worms, etc. As such it has become a priority for cyber defenders to detect and mitigate the spread of malicious codes within their networks promptly. Various techniques for malicious URL detectors have previously relied mainly on URL blacklisting or signature blacklisting. Most of these techniques offer ‘after-the-fact’ solutions. To improve the timeliness and abstraction of malicious URL detection methods, machine learning techniques are increasingly being accepted.
To develop a machine learning model, we need a feature extraction framework for featurizing URLs or converting URLs into feature vectors. In this article, We will collect samples of known malicious URLs and known benign URLs. We then develop a fingerprinting framework and extract a given set of M features for all URLs in the sample. We test the usefulness of these features in separating malicious URLs from benign URLs by developing a simple predictive model with these features. Finally, we measure the model’s ability to predict the maliciousness of URLs as the effectiveness of the features in separating malicious URLs from benign URLs.
The image below is an overview of the methodological process in this article.
We collected data from two sources: Alexa Top 1000 sites and phishtank.com. 1000 assumed benign URLs were crawled from Alexa top 1000 websites and 1000 suspected malicious URLs were crawled from phishtank.com. Due to virustotal API limit rates, we randomly sample 500 assumed benign URLs and 500 assumed malicious URLs. The URLs were then scanned through virustotal. URLs with 0 malicious detections were labeled as benign (b_urlX) and URLs with at least 8 detections were labeled as malicious (m_urlX). we dumped the JSON results of each scan in corresponding files ‘b_urlX.json’, ‘m_urlX.json’. You can find these files here.
from requests import getfrom os import listdirimport pandas as pdimport numpy as npfrom pandas.io.json import json_normalizeimport seaborn as snsimport matplotlib.pyplot as pltimport mathfrom datetime import datetimeplt.rcParams["figure.figsize"] = (20,20)
To confirm that malicious URLs in the sample are malicious, we need to send multiple requests to VirusTotal. VirustTotal provides aggregated results from multiple virus scan engines. Also, we pass URLs through (Shodan)[shodan.io]. Shodan is a search engine for all devices connected to the internet providing service-based features of the URL’s server. VirusTotal and Shodan currently have API rate limits of 4 requests per minute and at least 10,000 requests per month respectively per API key. While the number of URL requests for the data fell within the Shodan API request limits, VirusTotal proved a little more difficult. This is addressed by creating several VT API Keys (be kind, 4 at most) and randomly sampling them in each request. In addition to limits on the number of API requests, sending multiple requests within a short period will lead to IP blocking from VT and Shodan servers. We write a small crawler to get the latest set of elite IP addresses from https://free-proxy-list.net/ and create a new proxy-list on each request given the very short lifespan of free proxies. In addition to IP pooling, we use Python’s FakeUserAgent library to switch User-Agents on each request.
Finally, For each request, we can send 16 requests per minute as opposed to the previous 4, with a new proxy and user agent. Each request has the following request parameters:
1 VirusTotal Key: Sample from VT API keys pool.
1 Shodan Key: Sample from Shodan API keys pool.
1 IP: Send a request to https://free-proxy-list.net/ to get the latest free elite proxy.
1 User-Agent: Sample useable user agents from Python’s (Fake User-Agent)[https://pypi.org/project/fake-useragent/]
The scanning from Shodan and VT produced the following dataset. From shodan, we extract the following features:
numServices: Total number of services (open ports) running on the host
robotstxt: Is the site has robots txt enabled
The final dataset after scanning is available here. You can download this data and run your analysis.
The goal is to extract URL characteristics that are important in separating malicious URLs from good URLs. First, let’s look at the relevant parts in the structure of a URL.
A URL (short for Uniform Resource Locator) is a reference that specifies the location of a web resource on a computer network and a mechanism for retrieving it. The URL is made up of different components as shown in the figure below. The protocol or scheme specifies how (or what is needed for) information is to be transferred. The hostname is a human-readable unique reference of the computer’s IP address on the computer network. The Domain Name Service (DNS) naming hierarchy maps an IP address to a hostname. Compromised URLs are used to perpetrate cyber-attacks online. These attacks may be in any or more forms of phishing emails, spam emails, and drive-by downloads.
Regarding domains, owners buy domains that people find easier to remember. Owners would normally want names that are specific to a brand, product, or service which they are delivering. This part (the domain)of the URL cannot be changed once set. Malicious domain owners may opt for multiple cheap domain names for example ‘xsertyh.com’.
The free URL parameters are parts of a URL that can be changed to create new URLs. These include directory names, file paths, and URL parameters. These free URL parameters are usually manipulated by attackers to create new URLs, embed malicious codes and propagate them.
There are many techniques for malicious URL detection, two main techniques being a) Blacklisting Techniques, and b) Machine Learning Techniques. Blacklisting involves maintaining a database of known malicious domains and comparing the hostname of a new URL to hostnames in that database. This has an ‘after-the-fact’ problem. It will be unable to detect new and unseen malicious URL, which will only be added to the blacklist after it has been observed as malicious from a victim. Machine learning approaches, on the other hand, provide a predictive approach that is generalizable across platforms and independent of prior knowledge of known signatures. Given a sample of malicious and benign malware samples, ML techniques will extract features of known good and bad URLs and generalize these features to identify new and unseen good or bad URLs.
The URL fingerprinting process targets 3 types of URL features:
URL String Characteristics: Features derived from the URL string itself.
URL Domain Characteristics: Domain characteristics of the URLs domain. These include whois information and shodan information.
Page Content Characteristics: Features extracted from the URL’s page (if any)
A summary of all features extracted are shown in the table below:
Running the script above produces the following data with 23 features. We will separate integers, booleans, and object column names into separate lists for easier data access.
objects = [i for i in data.columns if 'object' in str(data.dtypes[i])]booleans = [i for i in data.columns if 'bool' in str(data.dtypes[i])]ints = [i for i in data.columns if 'int' in str(data.dtypes[i]) or 'float' in str(data.dtypes[i])]
The most linear analysis assumes non-multicollinearity between predictor variables i.e pairs of predictor features must not be correlated. The intuition behind this assumption is that there is no additional information added to a model with multiple correlated features as the same information is captured by one of the features.
Multi-correlated features are also indicative of redundant features in the data and dropping them is a good first step for data dimension reduction. By removing correlated features (and only keeping, one of the groups of observed correlated features), we can address the issues of feature redundancy and collinearity between predictors.
Let’s create a simple correlation grid to observe the correlation between the derived features for malicious and benign URL and remove one or more of highly correlated features.
corr = data[ints+booleans].corr()# Generate a mask for the upper trianglemask = np.triu(np.ones_like(corr, dtype=np.bool))# Set up the matplotlib figuref, ax = plt.subplots(figsize=(20, 15))# Generate a custom diverging colormapcmap = sns.diverging_palette(220, 10, as_cmap=True)# Draw the heatmap with the mask and correct aspect ratiosns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=True)
However, we do not want to remove all correlated variables-only those with a very strong correlation that do not add extra information to the model. For this, we define a certain ‘threshold’ (0.7) for positive and negative correlation observed.
We see that most of the highly correlated features are negatively correlated. For example, there is a 0.56 negative correlation coefficient between the number of characters in a URL and the entropy of the URL which suggests that shorter URLs have
Here we will create a function to identify and drop one of multiple correlated features.
Modeling builds a blueprint for explaining data, from previously observed patterns in the data. Modeling is often predictive in that it tries to use this developed ‘blueprint’ in predicting the values of future or new observations based on what it has observed in the past.
Based on the extracted features, we want the best predictive model that tells us if an unseen URL is malicious or benign. Therefore, we seek a unique combination of useful features to accurately separate malicious from benign URLs. We will go through two stages, feature selection, where we select only features useful in predicting the target variable and modeling with decision trees to develop a predictive model for malicious and benign URLs.
What variables are most useful in identifying a URL as ‘malicious’ or ‘benign’? Computationally, we can automatically select what variables are most useful by testing which ones ‘improves’ or ‘fails to improve’ the overall performance of the prediction model. This process is called ‘Feature Selection’. Feature selection also serves the purpose of reducing the dimension of data, addressing issues of computational complexity and model performance. The goal of feature selection is to obtain a useful subset of the original data that is predictive of the target feature in such a way that useful information is not lost (considering all predictors together). Although feature selection goes beyond simple correlation elimination, for this article, we limit our feature selection method simply retaining these features. Let’s create a subset of the original data that contain only uncorrelated features.
predictor_columns = data2.columnsd = data2[predictor_columns]x, y = d[predictor_columns], data['vt_class']
We keep only features that are unique in their contribution to the model. We can now start developing the model with 70% of the original sample and these 14 features. We will keep 30% of the sample to evaluate the model’s performance on new data.
numServices
entropy
numDigits
numParams
bodyLength
numTitles
numImages
numLinks
dsr
dse
sscr
sbr
robots
hasHttp
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 100)
from sklearn import treefrom sklearn.metrics import accuracy_scorefrom sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplus
There are multiple machine learning algorithms (classification) algorithms that can be applied to identifying malicious URLs. After converting URLs to a representative feature vector, we model the ‘malicious URL identification problem’ as a binary classification problem. A binary classification model trains a predictive model for a class with only two outcomes ‘Malicious’ and ‘Benign’. Batch learning algorithms are machine learning algorithms that work under the following assumptions:
- the entire training data is available before model development and
- the target variable is known before the model training task.
Batch algorithms are ideal and effective in that they are explainable discriminative learning models that use simple loss minimization between training data points. Decision trees are one such batch learning algorithms in machine learning.
In decision analysis, a decision tree is a visual representation of a model’s decision-making process to arrive at certain conclusions. The basic idea behind decision trees is an attempt to understand what factors influence class membership or why a data point belongs to a class label. A decision tree explicitly shows the conditions on which class members are made. Therefore they are a visual representation of the decision-making process.
Decision tree builds predictive models by breaking down the data set into smaller and smaller parts. The decision to split a subset is based on maximizing the information gain or minimizing information loss from splitting. Starting with the root node (the purest feature with no uncertainty), the tree is formed by creating various leaf nodes based on the purity of the subset.
In this case, the decision tree will explain class boundaries for each feature to classify a URL as malicious or benign. There are two main factors to consider when building a decision tree:
- a) What criteria to use in splitting or creating leaf nodes and- b) tree pruning to control how long a tree is allowed to grow to control the risk of over-fitting.
The criterion parameter of the decision tree algorithm specifies what criteria (Gini or entropy) to control for while the max_depth parameter controls how far the tree is allowed to grow. Gini measurement is the probability of a random sample being classified incorrectly if we randomly pick a label according to the distribution in a branch. Entropy is a measurement of information (or rather lack thereof).
Unfortunately, since there is no prior knowledge of the right combination of criteria and tree depth, we would have to iteratively test for the optimal values of these two parameters. We test a max_depth for 50 iterations for both criteria and visualize the model accuracy scores.
It seems the best model is the simplest one with the Gini index and a max depth of 4 with 84% out of sample accuracy. Also, maximizing the entropy does not seem to produce good results suggesting that new parameters added to the model do not necessarily give new information but may produce improved node probability purity. So we can fit and visualize the tree with max_depth = 4 and Gini criteria to identify which features are most important in separating malicious and benign URLs.
Build the model....
###create decision tree classifier objectDT = tree.DecisionTreeClassifier(criterion="gini", max_depth=4)##fit decision tree model with training dataDT.fit(X_train, y_train)##test data predictionDT_expost_preds = DT.predict(X_test)
Visualize the tree ...
dot_data = StringIO()export_graphviz(DT, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names=X_train.columns, class_names=DT.classes_)graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png())
The accuracy of prediction models is very sensitive to parameter tuning of the max_depth (tree pruning) and split quality criteria (node splitting). This also helps in achieving the simplest parsimonious model that prevents over-fitting and performs just as well on unseen data. These parameters are specific to different data problems and it is good practice to test a combination of different parameter values.
The model shows that malicious URLs have a lower script to special character ratio (sscr) and URL characters that are relatively more ‘ordered’ or more monotonous. Additionally, malicious URLs may have domains that have expired somewhere between 5–9 months ago. We also know of issues of ‘malvertising’ where scammers take ownership of expired legitimate domains to distribute downloadable malicious codes. Finally, probably the most distinguishing feature of benign URLs is longevity. They seem to moderate script to special character ratio in HTML body content with longer domain lifetime of 4–8 years.
|
[
{
"code": null,
"e": 587,
"s": 171,
"text": "In this article, we walk through developing a simple feature set representation for identifying malicious URLs. We will create feature vectors for URLs and use these to develop a classification model for identifying malicious URLs. To evaluate how good the features are in separating malicious URLs from benign URLs, we build a Decision-Tree based machine learning model to predict the maliciousness of a given URL."
},
{
"code": null,
"e": 1539,
"s": 587,
"text": "Malicious websites are well-known threats in cybersecurity. They act as an efficient tool for propagating viruses, worms, and other types of malicious codes online and are responsible for over 60% of most cyber attacks. Malicious URLs can be delivered via email links, text messages, browser pop-ups, page advertisements, etc. These URLs may be links to dodgy websites or most likely have embedded ‘downloadables’. These embedded downloads can be spy-wares, key-loggers, viruses, worms, etc. As such it has become a priority for cyber defenders to detect and mitigate the spread of malicious codes within their networks promptly. Various techniques for malicious URL detectors have previously relied mainly on URL blacklisting or signature blacklisting. Most of these techniques offer ‘after-the-fact’ solutions. To improve the timeliness and abstraction of malicious URL detection methods, machine learning techniques are increasingly being accepted."
},
{
"code": null,
"e": 2183,
"s": 1539,
"text": "To develop a machine learning model, we need a feature extraction framework for featurizing URLs or converting URLs into feature vectors. In this article, We will collect samples of known malicious URLs and known benign URLs. We then develop a fingerprinting framework and extract a given set of M features for all URLs in the sample. We test the usefulness of these features in separating malicious URLs from benign URLs by developing a simple predictive model with these features. Finally, we measure the model’s ability to predict the maliciousness of URLs as the effectiveness of the features in separating malicious URLs from benign URLs."
},
{
"code": null,
"e": 2261,
"s": 2183,
"text": "The image below is an overview of the methodological process in this article."
},
{
"code": null,
"e": 2889,
"s": 2261,
"text": "We collected data from two sources: Alexa Top 1000 sites and phishtank.com. 1000 assumed benign URLs were crawled from Alexa top 1000 websites and 1000 suspected malicious URLs were crawled from phishtank.com. Due to virustotal API limit rates, we randomly sample 500 assumed benign URLs and 500 assumed malicious URLs. The URLs were then scanned through virustotal. URLs with 0 malicious detections were labeled as benign (b_urlX) and URLs with at least 8 detections were labeled as malicious (m_urlX). we dumped the JSON results of each scan in corresponding files ‘b_urlX.json’, ‘m_urlX.json’. You can find these files here."
},
{
"code": null,
"e": 3146,
"s": 2889,
"text": "from requests import getfrom os import listdirimport pandas as pdimport numpy as npfrom pandas.io.json import json_normalizeimport seaborn as snsimport matplotlib.pyplot as pltimport mathfrom datetime import datetimeplt.rcParams[\"figure.figsize\"] = (20,20)"
},
{
"code": null,
"e": 4341,
"s": 3146,
"text": "To confirm that malicious URLs in the sample are malicious, we need to send multiple requests to VirusTotal. VirustTotal provides aggregated results from multiple virus scan engines. Also, we pass URLs through (Shodan)[shodan.io]. Shodan is a search engine for all devices connected to the internet providing service-based features of the URL’s server. VirusTotal and Shodan currently have API rate limits of 4 requests per minute and at least 10,000 requests per month respectively per API key. While the number of URL requests for the data fell within the Shodan API request limits, VirusTotal proved a little more difficult. This is addressed by creating several VT API Keys (be kind, 4 at most) and randomly sampling them in each request. In addition to limits on the number of API requests, sending multiple requests within a short period will lead to IP blocking from VT and Shodan servers. We write a small crawler to get the latest set of elite IP addresses from https://free-proxy-list.net/ and create a new proxy-list on each request given the very short lifespan of free proxies. In addition to IP pooling, we use Python’s FakeUserAgent library to switch User-Agents on each request."
},
{
"code": null,
"e": 4517,
"s": 4341,
"text": "Finally, For each request, we can send 16 requests per minute as opposed to the previous 4, with a new proxy and user agent. Each request has the following request parameters:"
},
{
"code": null,
"e": 4565,
"s": 4517,
"text": "1 VirusTotal Key: Sample from VT API keys pool."
},
{
"code": null,
"e": 4613,
"s": 4565,
"text": "1 Shodan Key: Sample from Shodan API keys pool."
},
{
"code": null,
"e": 4702,
"s": 4613,
"text": "1 IP: Send a request to https://free-proxy-list.net/ to get the latest free elite proxy."
},
{
"code": null,
"e": 4817,
"s": 4702,
"text": "1 User-Agent: Sample useable user agents from Python’s (Fake User-Agent)[https://pypi.org/project/fake-useragent/]"
},
{
"code": null,
"e": 4929,
"s": 4817,
"text": "The scanning from Shodan and VT produced the following dataset. From shodan, we extract the following features:"
},
{
"code": null,
"e": 5000,
"s": 4929,
"text": "numServices: Total number of services (open ports) running on the host"
},
{
"code": null,
"e": 5046,
"s": 5000,
"text": "robotstxt: Is the site has robots txt enabled"
},
{
"code": null,
"e": 5148,
"s": 5046,
"text": "The final dataset after scanning is available here. You can download this data and run your analysis."
},
{
"code": null,
"e": 5322,
"s": 5148,
"text": "The goal is to extract URL characteristics that are important in separating malicious URLs from good URLs. First, let’s look at the relevant parts in the structure of a URL."
},
{
"code": null,
"e": 5997,
"s": 5322,
"text": "A URL (short for Uniform Resource Locator) is a reference that specifies the location of a web resource on a computer network and a mechanism for retrieving it. The URL is made up of different components as shown in the figure below. The protocol or scheme specifies how (or what is needed for) information is to be transferred. The hostname is a human-readable unique reference of the computer’s IP address on the computer network. The Domain Name Service (DNS) naming hierarchy maps an IP address to a hostname. Compromised URLs are used to perpetrate cyber-attacks online. These attacks may be in any or more forms of phishing emails, spam emails, and drive-by downloads."
},
{
"code": null,
"e": 6334,
"s": 5997,
"text": "Regarding domains, owners buy domains that people find easier to remember. Owners would normally want names that are specific to a brand, product, or service which they are delivering. This part (the domain)of the URL cannot be changed once set. Malicious domain owners may opt for multiple cheap domain names for example ‘xsertyh.com’."
},
{
"code": null,
"e": 6605,
"s": 6334,
"text": "The free URL parameters are parts of a URL that can be changed to create new URLs. These include directory names, file paths, and URL parameters. These free URL parameters are usually manipulated by attackers to create new URLs, embed malicious codes and propagate them."
},
{
"code": null,
"e": 7453,
"s": 6605,
"text": "There are many techniques for malicious URL detection, two main techniques being a) Blacklisting Techniques, and b) Machine Learning Techniques. Blacklisting involves maintaining a database of known malicious domains and comparing the hostname of a new URL to hostnames in that database. This has an ‘after-the-fact’ problem. It will be unable to detect new and unseen malicious URL, which will only be added to the blacklist after it has been observed as malicious from a victim. Machine learning approaches, on the other hand, provide a predictive approach that is generalizable across platforms and independent of prior knowledge of known signatures. Given a sample of malicious and benign malware samples, ML techniques will extract features of known good and bad URLs and generalize these features to identify new and unseen good or bad URLs."
},
{
"code": null,
"e": 7517,
"s": 7453,
"text": "The URL fingerprinting process targets 3 types of URL features:"
},
{
"code": null,
"e": 7590,
"s": 7517,
"text": "URL String Characteristics: Features derived from the URL string itself."
},
{
"code": null,
"e": 7717,
"s": 7590,
"text": "URL Domain Characteristics: Domain characteristics of the URLs domain. These include whois information and shodan information."
},
{
"code": null,
"e": 7795,
"s": 7717,
"text": "Page Content Characteristics: Features extracted from the URL’s page (if any)"
},
{
"code": null,
"e": 7861,
"s": 7795,
"text": "A summary of all features extracted are shown in the table below:"
},
{
"code": null,
"e": 8037,
"s": 7861,
"text": "Running the script above produces the following data with 23 features. We will separate integers, booleans, and object column names into separate lists for easier data access."
},
{
"code": null,
"e": 8275,
"s": 8037,
"text": "objects = [i for i in data.columns if 'object' in str(data.dtypes[i])]booleans = [i for i in data.columns if 'bool' in str(data.dtypes[i])]ints = [i for i in data.columns if 'int' in str(data.dtypes[i]) or 'float' in str(data.dtypes[i])]"
},
{
"code": null,
"e": 8605,
"s": 8275,
"text": "The most linear analysis assumes non-multicollinearity between predictor variables i.e pairs of predictor features must not be correlated. The intuition behind this assumption is that there is no additional information added to a model with multiple correlated features as the same information is captured by one of the features."
},
{
"code": null,
"e": 8942,
"s": 8605,
"text": "Multi-correlated features are also indicative of redundant features in the data and dropping them is a good first step for data dimension reduction. By removing correlated features (and only keeping, one of the groups of observed correlated features), we can address the issues of feature redundancy and collinearity between predictors."
},
{
"code": null,
"e": 9120,
"s": 8942,
"text": "Let’s create a simple correlation grid to observe the correlation between the derived features for malicious and benign URL and remove one or more of highly correlated features."
},
{
"code": null,
"e": 9591,
"s": 9120,
"text": "corr = data[ints+booleans].corr()# Generate a mask for the upper trianglemask = np.triu(np.ones_like(corr, dtype=np.bool))# Set up the matplotlib figuref, ax = plt.subplots(figsize=(20, 15))# Generate a custom diverging colormapcmap = sns.diverging_palette(220, 10, as_cmap=True)# Draw the heatmap with the mask and correct aspect ratiosns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={\"shrink\": .5}, annot=True)"
},
{
"code": null,
"e": 9836,
"s": 9591,
"text": "However, we do not want to remove all correlated variables-only those with a very strong correlation that do not add extra information to the model. For this, we define a certain ‘threshold’ (0.7) for positive and negative correlation observed."
},
{
"code": null,
"e": 10083,
"s": 9836,
"text": "We see that most of the highly correlated features are negatively correlated. For example, there is a 0.56 negative correlation coefficient between the number of characters in a URL and the entropy of the URL which suggests that shorter URLs have"
},
{
"code": null,
"e": 10172,
"s": 10083,
"text": "Here we will create a function to identify and drop one of multiple correlated features."
},
{
"code": null,
"e": 10446,
"s": 10172,
"text": "Modeling builds a blueprint for explaining data, from previously observed patterns in the data. Modeling is often predictive in that it tries to use this developed ‘blueprint’ in predicting the values of future or new observations based on what it has observed in the past."
},
{
"code": null,
"e": 10893,
"s": 10446,
"text": "Based on the extracted features, we want the best predictive model that tells us if an unseen URL is malicious or benign. Therefore, we seek a unique combination of useful features to accurately separate malicious from benign URLs. We will go through two stages, feature selection, where we select only features useful in predicting the target variable and modeling with decision trees to develop a predictive model for malicious and benign URLs."
},
{
"code": null,
"e": 11797,
"s": 10893,
"text": "What variables are most useful in identifying a URL as ‘malicious’ or ‘benign’? Computationally, we can automatically select what variables are most useful by testing which ones ‘improves’ or ‘fails to improve’ the overall performance of the prediction model. This process is called ‘Feature Selection’. Feature selection also serves the purpose of reducing the dimension of data, addressing issues of computational complexity and model performance. The goal of feature selection is to obtain a useful subset of the original data that is predictive of the target feature in such a way that useful information is not lost (considering all predictors together). Although feature selection goes beyond simple correlation elimination, for this article, we limit our feature selection method simply retaining these features. Let’s create a subset of the original data that contain only uncorrelated features."
},
{
"code": null,
"e": 11904,
"s": 11797,
"text": "predictor_columns = data2.columnsd = data2[predictor_columns]x, y = d[predictor_columns], data['vt_class']"
},
{
"code": null,
"e": 12151,
"s": 11904,
"text": "We keep only features that are unique in their contribution to the model. We can now start developing the model with 70% of the original sample and these 14 features. We will keep 30% of the sample to evaluate the model’s performance on new data."
},
{
"code": null,
"e": 12163,
"s": 12151,
"text": "numServices"
},
{
"code": null,
"e": 12171,
"s": 12163,
"text": "entropy"
},
{
"code": null,
"e": 12181,
"s": 12171,
"text": "numDigits"
},
{
"code": null,
"e": 12191,
"s": 12181,
"text": "numParams"
},
{
"code": null,
"e": 12202,
"s": 12191,
"text": "bodyLength"
},
{
"code": null,
"e": 12212,
"s": 12202,
"text": "numTitles"
},
{
"code": null,
"e": 12222,
"s": 12212,
"text": "numImages"
},
{
"code": null,
"e": 12231,
"s": 12222,
"text": "numLinks"
},
{
"code": null,
"e": 12235,
"s": 12231,
"text": "dsr"
},
{
"code": null,
"e": 12239,
"s": 12235,
"text": "dse"
},
{
"code": null,
"e": 12244,
"s": 12239,
"text": "sscr"
},
{
"code": null,
"e": 12248,
"s": 12244,
"text": "sbr"
},
{
"code": null,
"e": 12255,
"s": 12248,
"text": "robots"
},
{
"code": null,
"e": 12263,
"s": 12255,
"text": "hasHttp"
},
{
"code": null,
"e": 12410,
"s": 12263,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 100)"
},
{
"code": null,
"e": 12612,
"s": 12410,
"text": "from sklearn import treefrom sklearn.metrics import accuracy_scorefrom sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplus"
},
{
"code": null,
"e": 13102,
"s": 12612,
"text": "There are multiple machine learning algorithms (classification) algorithms that can be applied to identifying malicious URLs. After converting URLs to a representative feature vector, we model the ‘malicious URL identification problem’ as a binary classification problem. A binary classification model trains a predictive model for a class with only two outcomes ‘Malicious’ and ‘Benign’. Batch learning algorithms are machine learning algorithms that work under the following assumptions:"
},
{
"code": null,
"e": 13171,
"s": 13102,
"text": "- the entire training data is available before model development and"
},
{
"code": null,
"e": 13234,
"s": 13171,
"text": "- the target variable is known before the model training task."
},
{
"code": null,
"e": 13474,
"s": 13234,
"text": "Batch algorithms are ideal and effective in that they are explainable discriminative learning models that use simple loss minimization between training data points. Decision trees are one such batch learning algorithms in machine learning."
},
{
"code": null,
"e": 13917,
"s": 13474,
"text": "In decision analysis, a decision tree is a visual representation of a model’s decision-making process to arrive at certain conclusions. The basic idea behind decision trees is an attempt to understand what factors influence class membership or why a data point belongs to a class label. A decision tree explicitly shows the conditions on which class members are made. Therefore they are a visual representation of the decision-making process."
},
{
"code": null,
"e": 14295,
"s": 13917,
"text": "Decision tree builds predictive models by breaking down the data set into smaller and smaller parts. The decision to split a subset is based on maximizing the information gain or minimizing information loss from splitting. Starting with the root node (the purest feature with no uncertainty), the tree is formed by creating various leaf nodes based on the purity of the subset."
},
{
"code": null,
"e": 14486,
"s": 14295,
"text": "In this case, the decision tree will explain class boundaries for each feature to classify a URL as malicious or benign. There are two main factors to consider when building a decision tree:"
},
{
"code": null,
"e": 14652,
"s": 14486,
"text": "- a) What criteria to use in splitting or creating leaf nodes and- b) tree pruning to control how long a tree is allowed to grow to control the risk of over-fitting."
},
{
"code": null,
"e": 15061,
"s": 14652,
"text": "The criterion parameter of the decision tree algorithm specifies what criteria (Gini or entropy) to control for while the max_depth parameter controls how far the tree is allowed to grow. Gini measurement is the probability of a random sample being classified incorrectly if we randomly pick a label according to the distribution in a branch. Entropy is a measurement of information (or rather lack thereof)."
},
{
"code": null,
"e": 15342,
"s": 15061,
"text": "Unfortunately, since there is no prior knowledge of the right combination of criteria and tree depth, we would have to iteratively test for the optimal values of these two parameters. We test a max_depth for 50 iterations for both criteria and visualize the model accuracy scores."
},
{
"code": null,
"e": 15828,
"s": 15342,
"text": "It seems the best model is the simplest one with the Gini index and a max depth of 4 with 84% out of sample accuracy. Also, maximizing the entropy does not seem to produce good results suggesting that new parameters added to the model do not necessarily give new information but may produce improved node probability purity. So we can fit and visualize the tree with max_depth = 4 and Gini criteria to identify which features are most important in separating malicious and benign URLs."
},
{
"code": null,
"e": 15848,
"s": 15828,
"text": "Build the model...."
},
{
"code": null,
"e": 16079,
"s": 15848,
"text": "###create decision tree classifier objectDT = tree.DecisionTreeClassifier(criterion=\"gini\", max_depth=4)##fit decision tree model with training dataDT.fit(X_train, y_train)##test data predictionDT_expost_preds = DT.predict(X_test)"
},
{
"code": null,
"e": 16102,
"s": 16079,
"text": "Visualize the tree ..."
},
{
"code": null,
"e": 16386,
"s": 16102,
"text": "dot_data = StringIO()export_graphviz(DT, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names=X_train.columns, class_names=DT.classes_)graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png())"
},
{
"code": null,
"e": 16799,
"s": 16386,
"text": "The accuracy of prediction models is very sensitive to parameter tuning of the max_depth (tree pruning) and split quality criteria (node splitting). This also helps in achieving the simplest parsimonious model that prevents over-fitting and performs just as well on unseen data. These parameters are specific to different data problems and it is good practice to test a combination of different parameter values."
}
] |
Text Data Augmentation. A brief introduction to TextAttack and... | by Chetan Ambi | Towards Data Science
|
Data Augmentation is the process that enables us to increase the size of the training data without actually collecting the data. But why do we need more data? The answer is simple — the more data we have, the better the performance of the model.
Image data augmentation steps such as flipping, cropping, rotation, blurring, zooming, etc. helped tremendously in computer vision. Also, it is relatively easy to create augmented images but the same is not the case with Natural Language Processing (NLP) due to the complexities inherent in the language. (For example, we can not replace every word by its synonym, and even if we replace it, the meaning of the sentence might change completely). Based on my findings/research, I haven’t seen as much research around text data augmentation as image augmentation.
However, in this article, we will go thru 2 libraries TextAttack & Googletrans I have come across recently when I was trying augmentation for text data. So, let’s get started.
We will apply the augmentation techniques we are going to learn on these quotes of Simon Sinek.
“Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it.”
“The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen”
- Simon Sinek
TextAttack is a Python framework for adversarial attacks, adversarial training, and data augmentation in NLP. In this article, we will focus only on data augmentation.
!pip install textattack
The textattack.Augmenter class provides six methods for data augmentation. You can find the detailed description of these methods in the official documentation.
WordNetAugmenterEmbeddingAugmenterCharSwapAugmenterEasyDataAugmenterCheckListAugmenterCLAREAugmenter
WordNetAugmenter
EmbeddingAugmenter
CharSwapAugmenter
EasyDataAugmenter
CheckListAugmenter
CLAREAugmenter
Let’s look at the data augmentation results using these four methods. Note that pct_words_to_swap=0.1, transformations_per_example=4 are passed to each of these methods by default. We can modify these default values as needed.
!pip install pyarrow==0.16.0
Collecting pyarrow==0.16.0
Downloading https://files.pythonhosted.org/packages/00/d2/695bab1e1e7a4554b6dbd287d55cca096214bd441037058a432afd724bb1/pyarrow-0.16.0-cp36-cp36m-manylinux2014_x86_64.whl (63.1MB)
|████████████████████████████████| 63.2MB 63kB/s
Requirement already satisfied: six>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from pyarrow==0.16.0) (1.15.0)
Requirement already satisfied: numpy>=1.14 in /usr/local/lib/python3.6/dist-packages (from pyarrow==0.16.0) (1.18.5)
Installing collected packages: pyarrow
Found existing installation: pyarrow 0.14.1
Uninstalling pyarrow-0.14.1:
Successfully uninstalled pyarrow-0.14.1
Successfully installed pyarrow-0.16.0
!pip install textattack
Collecting textattack
Downloading https://files.pythonhosted.org/packages/df/eb/bb9793f290f0ca40c725f15144171318c1b1e1952ee249cecb66ed5fe841/textattack-0.2.4-py3-none-any.whl (207kB)
|████████████████████████████████| 215kB 2.7MB/s
Collecting flair>=0.5.1
Downloading https://files.pythonhosted.org/packages/60/8f/51d1f2eb5f9b09beb1e6858b4c174a087bc3b05893438e2cd3ffbf9c6e8b/flair-0.5.1-py3-none-any.whl (201kB)
|████████████████████████████████| 204kB 8.0MB/s
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from textattack) (0.22.2.post1)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from textattack) (4.41.1)
Requirement already satisfied: pandas>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from textattack) (1.0.5)
Collecting visdom
Downloading https://files.pythonhosted.org/packages/c9/75/e078f5a2e1df7e0d3044749089fc2823e62d029cc027ed8ae5d71fafcbdc/visdom-0.1.8.9.tar.gz (676kB)
|████████████████████████████████| 686kB 11.4MB/s
Collecting wandb
Downloading https://files.pythonhosted.org/packages/94/19/f8db9eff4b0173adf6dd2e8b0c3d8de0bfe10ec9ed63d247665980d82258/wandb-0.9.4-py2.py3-none-any.whl (1.4MB)
|████████████████████████████████| 1.4MB 17.9MB/s
Collecting tensorboardX
Downloading https://files.pythonhosted.org/packages/af/0c/4f41bcd45db376e6fe5c619c01100e9b7531c55791b7244815bac6eac32c/tensorboardX-2.1-py2.py3-none-any.whl (308kB)
|████████████████████████████████| 317kB 22.5MB/s
Collecting lemminflect
Downloading https://files.pythonhosted.org/packages/8d/c5/62e8dd0b6cbfea212cf55a2338838d85a819dbda9462ba53a415dcf19b86/lemminflect-0.2.1-py3-none-any.whl (769kB)
|████████████████████████████████| 778kB 26.6MB/s
Collecting tokenizers==0.8.1-rc1
Downloading https://files.pythonhosted.org/packages/40/d0/30d5f8d221a0ed981a186c8eb986ce1c94e3a6e87f994eae9f4aa5250217/tokenizers-0.8.1rc1-cp36-cp36m-manylinux1_x86_64.whl (3.0MB)
|████████████████████████████████| 3.0MB 37.0MB/s
Collecting nlp
Downloading https://files.pythonhosted.org/packages/09/e3/bcdc59f3434b224040c1047769c47b82705feca2b89ebbc28311e3764782/nlp-0.4.0-py3-none-any.whl (1.7MB)
|████████████████████████████████| 1.7MB 33.8MB/s
Requirement already satisfied: scipy==1.4.1 in /usr/local/lib/python3.6/dist-packages (from textattack) (1.4.1)
Requirement already satisfied: pyarrow<1.0 in /usr/local/lib/python3.6/dist-packages (from textattack) (0.16.0)
Requirement already satisfied: tensorflow>=2 in /usr/local/lib/python3.6/dist-packages (from textattack) (2.3.0)
Collecting terminaltables
Downloading https://files.pythonhosted.org/packages/9b/c4/4a21174f32f8a7e1104798c445dacdc1d4df86f2f26722767034e4de4bff/terminaltables-3.1.0.tar.gz
Collecting language-tool-python
Downloading https://files.pythonhosted.org/packages/d2/4a/95ee8562f40bb8e72f6da43f888e3577711cb49cf62ffedff2b6316d25b5/language_tool_python-2.3.1-py3-none-any.whl
Requirement already satisfied: editdistance in /usr/local/lib/python3.6/dist-packages (from textattack) (0.5.3)
Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from textattack) (1.6.0+cu101)
Collecting transformers==3.0.2
Downloading https://files.pythonhosted.org/packages/27/3c/91ed8f5c4e7ef3227b4119200fc0ed4b4fd965b1f0172021c25701087825/transformers-3.0.2-py3-none-any.whl (769kB)
|████████████████████████████████| 778kB 37.4MB/s
Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from textattack) (3.2.5)
Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from textattack) (3.0.12)
Collecting sentence-transformers>0.2.6
Downloading https://files.pythonhosted.org/packages/ee/71/acfb3f1016f83d90590130dc2ee0d8cd36b005aa7afa45b465837b711070/sentence-transformers-0.3.3.tar.gz (65kB)
|████████████████████████████████| 71kB 7.9MB/s
Collecting lru-dict
Downloading https://files.pythonhosted.org/packages/00/a5/32ed6e10246cd341ca8cc205acea5d208e4053f48a4dced2b1b31d45ba3f/lru-dict-1.1.6.tar.gz
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from textattack) (1.18.5)
Requirement already satisfied: tensorflow-hub in /usr/local/lib/python3.6/dist-packages (from textattack) (0.8.0)
Collecting bert-score
Downloading https://files.pythonhosted.org/packages/50/8c/70244d0f351176c9984643e2037edc18b9124491b47ad19191039a18d2bd/bert_score-0.3.5-py3-none-any.whl (52kB)
|████████████████████████████████| 61kB 6.9MB/s
Collecting langdetect
Downloading https://files.pythonhosted.org/packages/56/a3/8407c1e62d5980188b4acc45ef3d94b933d14a2ebc9ef3505f22cf772570/langdetect-1.0.8.tar.gz (981kB)
|████████████████████████████████| 983kB 43.8MB/s
Collecting pytest>=5.3.2
Downloading https://files.pythonhosted.org/packages/98/db/712bee56f9ab20373508a5a1c662e1db49b407dacf03b5224c6171ed0a3d/pytest-6.0.1-py3-none-any.whl (270kB)
|████████████████████████████████| 276kB 44.2MB/s
Collecting segtok>=1.5.7
Downloading https://files.pythonhosted.org/packages/41/08/582dab5f4b1d5ca23bc6927b4bb977c8ff7f3a87a3b98844ef833e2f5623/segtok-1.5.10.tar.gz
Collecting sqlitedict>=1.6.0
Downloading https://files.pythonhosted.org/packages/0f/1c/c757b93147a219cf1e25cef7e1ad9b595b7f802159493c45ce116521caff/sqlitedict-1.6.0.tar.gz
Requirement already satisfied: matplotlib>=2.2.3 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (3.2.2)
Collecting mpld3==0.3
Downloading https://files.pythonhosted.org/packages/91/95/a52d3a83d0a29ba0d6898f6727e9858fe7a43f6c2ce81a5fe7e05f0f4912/mpld3-0.3.tar.gz (788kB)
|████████████████████████████████| 798kB 40.0MB/s
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (2.8.1)
Requirement already satisfied: gensim>=3.4.0 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (3.6.0)
Collecting deprecated>=1.2.4
Downloading https://files.pythonhosted.org/packages/76/a1/05d7f62f956d77b23a640efc650f80ce24483aa2f85a09c03fb64f49e879/Deprecated-1.2.10-py2.py3-none-any.whl
Requirement already satisfied: hyperopt>=0.1.1 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (0.1.2)
Collecting bpemb>=0.2.9
Downloading https://files.pythonhosted.org/packages/91/77/3f0f53856e86af32b1d3c86652815277f7b5f880002584eb30db115b6df5/bpemb-0.3.2-py3-none-any.whl
Requirement already satisfied: regex in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (2019.12.20)
Collecting sentencepiece!=0.1.92
Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)
|████████████████████████████████| 1.1MB 30.7MB/s
Requirement already satisfied: tabulate in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (0.8.7)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->textattack) (0.16.0)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=1.0.1->textattack) (2018.9)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (2.23.0)
Requirement already satisfied: tornado in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (5.1.1)
Requirement already satisfied: pyzmq in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (19.0.2)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (1.15.0)
Collecting jsonpatch
Downloading https://files.pythonhosted.org/packages/4f/d0/34b0f59ac08de9c1e07876cfecd80aec650600177b4bd445124c755499a7/jsonpatch-1.26-py2.py3-none-any.whl
Collecting torchfile
Downloading https://files.pythonhosted.org/packages/91/af/5b305f86f2d218091af657ddb53f984ecbd9518ca9fe8ef4103a007252c9/torchfile-0.1.0.tar.gz
Collecting websocket-client
Downloading https://files.pythonhosted.org/packages/4c/5f/f61b420143ed1c8dc69f9eaec5ff1ac36109d52c80de49d66e0c36c3dfdf/websocket_client-0.57.0-py2.py3-none-any.whl (200kB)
|████████████████████████████████| 204kB 38.4MB/s
Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (7.0.0)
Collecting subprocess32>=3.5.3
Downloading https://files.pythonhosted.org/packages/32/c8/564be4d12629b912ea431f1a50eb8b3b9d00f1a0b1ceff17f266be190007/subprocess32-3.5.4.tar.gz (97kB)
|████████████████████████████████| 102kB 11.4MB/s
Collecting watchdog>=0.8.3
Downloading https://files.pythonhosted.org/packages/0e/06/121302598a4fc01aca942d937f4a2c33430b7181137b35758913a8db10ad/watchdog-0.10.3.tar.gz (94kB)
|████████████████████████████████| 102kB 10.0MB/s
Collecting docker-pycreds>=0.4.0
Downloading https://files.pythonhosted.org/packages/f5/e8/f6bd1eee09314e7e6dee49cbe2c5e22314ccdb38db16c9fc72d2fa80d054/docker_pycreds-0.4.0-py2.py3-none-any.whl
Collecting GitPython>=1.0.0
Downloading https://files.pythonhosted.org/packages/f9/1e/a45320cab182bf1c8656107b3d4c042e659742822fc6bff150d769a984dd/GitPython-3.1.7-py3-none-any.whl (158kB)
|████████████████████████████████| 163kB 34.9MB/s
Requirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (3.13)
Requirement already satisfied: nvidia-ml-py3>=7.352.0 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (7.352.0)
Collecting shortuuid>=0.5.0
Downloading https://files.pythonhosted.org/packages/25/a6/2ecc1daa6a304e7f1b216f0896b26156b78e7c38e1211e9b798b4716c53d/shortuuid-1.0.1-py3-none-any.whl
Collecting configparser>=3.8.1
Downloading https://files.pythonhosted.org/packages/4b/6b/01baa293090240cf0562cc5eccb69c6f5006282127f2b846fad011305c79/configparser-5.0.0-py3-none-any.whl
Requirement already satisfied: psutil>=5.0.0 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (5.4.8)
Collecting gql==0.2.0
Downloading https://files.pythonhosted.org/packages/c4/6f/cf9a3056045518f06184e804bae89390eb706168349daa9dff8ac609962a/gql-0.2.0.tar.gz
Collecting sentry-sdk>=0.4.0
Downloading https://files.pythonhosted.org/packages/4b/23/811fcdfc9d67fea7e47c91dd553081218d53dda744c28384f4d2f69206c9/sentry_sdk-0.16.3-py2.py3-none-any.whl (110kB)
|████████████████████████████████| 112kB 40.6MB/s
Requirement already satisfied: Click>=7.0 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (7.1.2)
Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorboardX->textattack) (3.12.4)
Requirement already satisfied: dataclasses; python_version < "3.7" in /usr/local/lib/python3.6/dist-packages (from nlp->textattack) (0.7)
Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from nlp->textattack) (0.3.2)
Collecting xxhash
Downloading https://files.pythonhosted.org/packages/f7/73/826b19f3594756cb1c6c23d2fbd8ca6a77a9cd3b650c9dec5acc85004c38/xxhash-2.0.0-cp36-cp36m-manylinux2010_x86_64.whl (242kB)
|████████████████████████████████| 245kB 41.7MB/s
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.6.3)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (3.3.0)
Requirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (2.3.0)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.3.3)
Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.9.0)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.34.2)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (2.10.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.1.0)
Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.1.2)
Requirement already satisfied: tensorflow-estimator<2.4.0,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (2.3.0)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.30.0)
Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.2.0)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.12.1)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch->textattack) (0.16.0)
Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers==3.0.2->textattack) (20.4)
Collecting sacremoses
Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)
|████████████████████████████████| 890kB 36.1MB/s
Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (8.4.0)
Collecting pluggy<1.0,>=0.12
Downloading https://files.pythonhosted.org/packages/a0/28/85c7aa31b80d150b772fbe4a229487bc6644da9ccb7e427dd8cc60cb8a62/pluggy-0.13.1-py2.py3-none-any.whl
Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (0.10.1)
Requirement already satisfied: py>=1.8.2 in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (1.9.0)
Requirement already satisfied: iniconfig in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (1.0.1)
Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (19.3.0)
Requirement already satisfied: importlib-metadata>=0.12; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (1.7.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2.3->flair>=0.5.1->textattack) (1.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2.3->flair>=0.5.1->textattack) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2.3->flair>=0.5.1->textattack) (0.10.0)
Requirement already satisfied: smart-open>=1.2.1 in /usr/local/lib/python3.6/dist-packages (from gensim>=3.4.0->flair>=0.5.1->textattack) (2.1.0)
Requirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from hyperopt>=0.1.1->flair>=0.5.1->textattack) (2.4)
Requirement already satisfied: pymongo in /usr/local/lib/python3.6/dist-packages (from hyperopt>=0.1.1->flair>=0.5.1->textattack) (3.11.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (1.24.3)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (2020.6.20)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (2.10)
Collecting jsonpointer>=1.9
Downloading https://files.pythonhosted.org/packages/18/b0/a80d29577c08eea401659254dfaed87f1af45272899e1812d7e01b679bc5/jsonpointer-2.0-py2.py3-none-any.whl
Collecting pathtools>=0.1.1
Downloading https://files.pythonhosted.org/packages/e7/7f/470d6fcdf23f9f3518f6b0b76be9df16dcc8630ad409947f8be2eb0ed13a/pathtools-0.1.2.tar.gz
Collecting gitdb<5,>=4.0.1
Downloading https://files.pythonhosted.org/packages/48/11/d1800bca0a3bae820b84b7d813ad1eff15a48a64caea9c823fc8c1b119e8/gitdb-4.0.5-py3-none-any.whl (63kB)
|████████████████████████████████| 71kB 7.6MB/s
Collecting graphql-core<2,>=0.5.0
Downloading https://files.pythonhosted.org/packages/b0/89/00ad5e07524d8c523b14d70c685e0299a8b0de6d0727e368c41b89b7ed0b/graphql-core-1.1.tar.gz (70kB)
|████████████████████████████████| 71kB 6.5MB/s
Requirement already satisfied: promise<3,>=2.0 in /usr/local/lib/python3.6/dist-packages (from gql==0.2.0->wandb->textattack) (2.3)
Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.8.0->tensorboardX->textattack) (49.2.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.7.0)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.0.1)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (3.2.2)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (0.4.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.17.2)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.12; python_version < "3.8"->pytest>=5.3.2->flair>=0.5.1->textattack) (3.1.0)
Requirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (1.14.33)
Requirement already satisfied: boto in /usr/local/lib/python3.6/dist-packages (from smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (2.49.0)
Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->hyperopt>=0.1.1->flair>=0.5.1->textattack) (4.4.2)
Collecting smmap<4,>=3.0.1
Downloading https://files.pythonhosted.org/packages/b0/9a/4d409a6234eb940e6a78dfdfc66156e7522262f5f2fecca07dc55915952d/smmap-3.0.4-py2.py3-none-any.whl
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.3.0)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (0.2.8)
Requirement already satisfied: rsa<5,>=3.1.4; python_version >= "3" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (4.6)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (4.1.1)
Requirement already satisfied: botocore<1.18.0,>=1.17.33 in /usr/local/lib/python3.6/dist-packages (from boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (1.17.33)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (0.10.0)
Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (0.3.3)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (3.1.0)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (0.4.8)
Requirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.18.0,>=1.17.33->boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (0.15.2)
Building wheels for collected packages: visdom, terminaltables, sentence-transformers, lru-dict, langdetect, segtok, sqlitedict, mpld3, torchfile, subprocess32, watchdog, gql, sacremoses, pathtools, graphql-core
Building wheel for visdom (setup.py) ... done
Created wheel for visdom: filename=visdom-0.1.8.9-cp36-none-any.whl size=655250 sha256=021ecf255f934787d40fdc3808b5cb6f59e53c7bdd18f1aa58119bb494c8230b
Stored in directory: /root/.cache/pip/wheels/70/19/a7/6d589ed967f4dfefd33bc166d081257bd4ed0cb618dccfd62a
Building wheel for terminaltables (setup.py) ... done
Created wheel for terminaltables: filename=terminaltables-3.1.0-cp36-none-any.whl size=15356 sha256=11bd424019d47ef03b9b055f4ae0c5de6f5b953e14a30ef54218857a638c2613
Stored in directory: /root/.cache/pip/wheels/30/6b/50/6c75775b681fb36cdfac7f19799888ef9d8813aff9e379663e
Building wheel for sentence-transformers (setup.py) ... done
Created wheel for sentence-transformers: filename=sentence_transformers-0.3.3-cp36-none-any.whl size=97299 sha256=d1d4f8047c37c1616c94c6f24f0e2ee327c3768200f4f13256bd6d306ccbcddc
Stored in directory: /root/.cache/pip/wheels/75/d6/0a/cab163b21d0597cc1580bc344487b11ad405e0d1d314725f2b
Building wheel for lru-dict (setup.py) ... done
Created wheel for lru-dict: filename=lru_dict-1.1.6-cp36-cp36m-linux_x86_64.whl size=25864 sha256=9f0c1af722bacbb05e34202cf6d062f406cf508e65b623a56ba51c9a3747462e
Stored in directory: /root/.cache/pip/wheels/b7/ef/06/fbdd555907a7d438fb33e4c8675f771ff1cf41917284c51ebf
Building wheel for langdetect (setup.py) ... done
Created wheel for langdetect: filename=langdetect-1.0.8-cp36-none-any.whl size=993193 sha256=f6806cc32d2d54c50fd8cd5eb9c4ee3634002c089e479143004248b6213c4324
Stored in directory: /root/.cache/pip/wheels/8d/b3/aa/6d99de9f3841d7d3d40a60ea06e6d669e8e5012e6c8b947a57
Building wheel for segtok (setup.py) ... done
Created wheel for segtok: filename=segtok-1.5.10-cp36-none-any.whl size=25020 sha256=f3bb5a27e2e5f9411305807610b17562f95896e7cb1de79520e393f17153e09f
Stored in directory: /root/.cache/pip/wheels/b4/39/f6/9ca1c5cabde964d728023b5751c3a206a5c8cc40252321fb6b
Building wheel for sqlitedict (setup.py) ... done
Created wheel for sqlitedict: filename=sqlitedict-1.6.0-cp36-none-any.whl size=14689 sha256=dadddd2a944c7e9e4b9e25deb4a0661d03f882ed71f84c73c5938900f5a02397
Stored in directory: /root/.cache/pip/wheels/bd/57/d3/907c3ee02d35e66f674ad0106e61f06eeeb98f6ee66a6cc3fe
Building wheel for mpld3 (setup.py) ... done
Created wheel for mpld3: filename=mpld3-0.3-cp36-none-any.whl size=116679 sha256=083b76dbbce87fafde4618a05fb9f26a3c88856b4e01b9158b82fa0db216ac1d
Stored in directory: /root/.cache/pip/wheels/c0/47/fb/8a64f89aecfe0059830479308ad42d62e898a3e3cefdf6ba28
Building wheel for torchfile (setup.py) ... done
Created wheel for torchfile: filename=torchfile-0.1.0-cp36-none-any.whl size=5712 sha256=e181fea9479102f59cc0172804beea0549594ba49f2b0e6a2e4d20316e732089
Stored in directory: /root/.cache/pip/wheels/b1/c3/d6/9a1cc8f3a99a0fc1124cae20153f36af59a6e683daca0a0814
Building wheel for subprocess32 (setup.py) ... done
Created wheel for subprocess32: filename=subprocess32-3.5.4-cp36-none-any.whl size=6489 sha256=cee805c7291b55f24d0b4e4fcfa06915bfbe93e6bf9a4eaa9cab87633fd34ff2
Stored in directory: /root/.cache/pip/wheels/68/39/1a/5e402bdfdf004af1786c8b853fd92f8c4a04f22aad179654d1
Building wheel for watchdog (setup.py) ... done
Created wheel for watchdog: filename=watchdog-0.10.3-cp36-none-any.whl size=73870 sha256=1a2896b9c4d89700d00421232ec98119340bbbf2bfb98daba4d4c947c5f33624
Stored in directory: /root/.cache/pip/wheels/a8/1d/38/2c19bb311f67cc7b4d07a2ec5ea36ab1a0a0ea50db994a5bc7
Building wheel for gql (setup.py) ... done
Created wheel for gql: filename=gql-0.2.0-cp36-none-any.whl size=7630 sha256=f90f7f403b9d2af02e220bd61968c7f7d4aeeb52a756f6527e8c751662a4c743
Stored in directory: /root/.cache/pip/wheels/ce/0e/7b/58a8a5268655b3ad74feef5aa97946f0addafb3cbb6bd2da23
Building wheel for sacremoses (setup.py) ... done
Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893260 sha256=7a42b3f6968d9cd8a928f232911a1e4c188a1d737be201eb142410cba4c28641
Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45
Building wheel for pathtools (setup.py) ... done
Created wheel for pathtools: filename=pathtools-0.1.2-cp36-none-any.whl size=8784 sha256=40e6d9de6b3e8584a9780536a67a3276ca90f8f63e13faa1e5cadcfaf2f336c5
Stored in directory: /root/.cache/pip/wheels/0b/04/79/c3b0c3a0266a3cb4376da31e5bfe8bba0c489246968a68e843
Building wheel for graphql-core (setup.py) ... done
Created wheel for graphql-core: filename=graphql_core-1.1-cp36-none-any.whl size=104650 sha256=44a8e1a804ae3d4a17feb1b3ba836f04df2aa7d51acb2fe79ee72e8316ec2496
Stored in directory: /root/.cache/pip/wheels/45/99/d7/c424029bb0fe910c63b68dbf2aa20d3283d023042521bcd7d5
Successfully built visdom terminaltables sentence-transformers lru-dict langdetect segtok sqlitedict mpld3 torchfile subprocess32 watchdog gql sacremoses pathtools graphql-core
ERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.
Installing collected packages: langdetect, pluggy, pytest, segtok, sqlitedict, mpld3, deprecated, sentencepiece, bpemb, tokenizers, sacremoses, transformers, flair, jsonpointer, jsonpatch, torchfile, websocket-client, visdom, subprocess32, pathtools, watchdog, docker-pycreds, smmap, gitdb, GitPython, shortuuid, configparser, graphql-core, gql, sentry-sdk, wandb, tensorboardX, lemminflect, xxhash, nlp, terminaltables, language-tool-python, sentence-transformers, lru-dict, bert-score, textattack
Found existing installation: pluggy 0.7.1
Uninstalling pluggy-0.7.1:
Successfully uninstalled pluggy-0.7.1
Found existing installation: pytest 3.6.4
Uninstalling pytest-3.6.4:
Successfully uninstalled pytest-3.6.4
Successfully installed GitPython-3.1.7 bert-score-0.3.5 bpemb-0.3.2 configparser-5.0.0 deprecated-1.2.10 docker-pycreds-0.4.0 flair-0.5.1 gitdb-4.0.5 gql-0.2.0 graphql-core-1.1 jsonpatch-1.26 jsonpointer-2.0 langdetect-1.0.8 language-tool-python-2.3.1 lemminflect-0.2.1 lru-dict-1.1.6 mpld3-0.3 nlp-0.4.0 pathtools-0.1.2 pluggy-0.13.1 pytest-6.0.1 sacremoses-0.0.43 segtok-1.5.10 sentence-transformers-0.3.3 sentencepiece-0.1.91 sentry-sdk-0.16.3 shortuuid-1.0.1 smmap-3.0.4 sqlitedict-1.6.0 subprocess32-3.5.4 tensorboardX-2.1 terminaltables-3.1.0 textattack-0.2.4 tokenizers-0.8.1rc1 torchfile-0.1.0 transformers-3.0.2 visdom-0.1.8.9 wandb-0.9.4 watchdog-0.10.3 websocket-client-0.57.0 xxhash-2.0.0
from textattack.augmentation import WordNetAugmenter, EmbeddingAugmenter, EasyDataAugmenter, CharSwapAugmenter
textattack: First time running textattack: downloading remaining required packages.
textattack: Downloading NLTK required packages.
[nltk_data] Downloading package wordnet to /root/nltk_data...
[nltk_data] Unzipping corpora/wordnet.zip.
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data] /root/nltk_data...
[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.
[nltk_data] Downloading package universal_tagset to /root/nltk_data...
[nltk_data] Unzipping taggers/universal_tagset.zip.
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data] Unzipping corpora/stopwords.zip.
wandb: WARNING W&B installed but not logged in. Run `wandb login` or set the WANDB_API_KEY env variable.
Example 1:
text = "Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it."
aug = WordNetAugmenter()
aug.augment(text)
['Leadership requires two things: a imaginativeness of the world that does not yet survive and the ability to communicate it.']
aug = EmbeddingAugmenter()
aug.augment(text)
textattack: Downloading https://textattack.s3.amazonaws.com/word_embeddings/paragramcf.
100%|██████████| 481M/481M [00:09<00:00, 52.4MB/s]
textattack: Unzipping file /root/.cache/textattack/tmppu06z0jb.zip to /root/.cache/textattack/word_embeddings/paragramcf.
textattack: Successfully saved word_embeddings/paragramcf to cache.
['Leadership requires deux things: a vision of the world that does not yet exist and the capacities to communicate it.']
aug = EasyDataAugmenter()
aug.augment(text)
['Leadership requires two things: a vision of the world that does not yet be and the power to communicate it.',
'Leadership requires two: a of the world that does not yet exist and the ability to communicate it.',
'Leadership requires two things: a vision of the world that it communicate yet exist and the ability to not does.',
'Leadership requires two live things: a vision of the world that withal does not yet exist and the ability to communicate it.']
aug = CharSwapAugmenter()
aug.augment(text)
['Leadership requires two things: a visoin of the worl that does not yet exist and the ability to communicate it.']
Example 2:
text = "The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen."
aug = WordNetAugmenter()
aug.augment(text)
['The persona of a leader is not to come up with all the great theme. The role of a leader is to create an environment in which great ideas can hap.']
aug = EmbeddingAugmenter()
aug.augment(text)
['The role of a leader is not to come up with all the great ideas. The role of a leader is to creations an environment in which grand insights can happen.']
aug = EasyDataAugmenter()
aug.augment(text)
['The role of a leader is not to come up with all the great estimate. The function of a leader is to make an environment in which great ideas can happen.',
'The role environment great leader is not to come up with all the a ideas. The role of a leader is to create an of in which great ideas happen can.',
'The role of a leader is not to come up with all the great improving ideas. The role of make a leader is to be create an environment in which great ideas can happen.',
'role of a leader is not to come up with all the great ideas. The role of a leader is create an environment in which great can happen.']
aug = CharSwapAugmenter()
aug.augment(text)
['The role of a Sleader is not to come up with all the great ideas. The role of a lXader is to create an environment in which great ides can happen.']
We can apply these methods to real-world data to increase the size of the data. The sample code is given below. Here the originaltrain dataframe is copied to the train_aug dataframe and then augmentation is applied on train_aug. And finally, train_aug is appended to the original train dataset.
train_aug = train.copy()from textattack.augmentation import EmbeddingAugmenteraug = EmbeddingAugmenter()train_aug['text'] = train_aug['text'].apply(lambda x: str(aug.augment(x)))train = train.append(train_copy, ignore_index=True)
Googletrans is built on top of Google Translate API. This uses Google Translate Ajax API for language detection and translation.
!pip install googletrans
The key parameters to translate() method are:
src: source language. Optional parameter as googletrans will detect it.
dest: destination language. Mandatory parameter.
text: the text to be translated from source language to the destination language. Mandatory parameter.
As we can see, the given text is first translated from English to Italian and then translated to back to English. During this back translation, as we can see, there is a slight change in the sentence between the original text and the back-translated text but the overall meaning of the sentence is still retained.
!pip install googletrans
Collecting googletrans
Downloading https://files.pythonhosted.org/packages/71/3a/3b19effdd4c03958b90f40fe01c93de6d5280e03843cc5adf6956bfc9512/googletrans-3.0.0.tar.gz
Collecting httpx==0.13.3
Downloading https://files.pythonhosted.org/packages/54/b4/698b284c6aed4d7c2b4fe3ba5df1fcf6093612423797e76fbb24890dd22f/httpx-0.13.3-py3-none-any.whl (55kB)
|████████████████████████████████| 61kB 2.9MB/s
Requirement already satisfied: chardet==3.* in /usr/local/lib/python3.6/dist-packages (from httpx==0.13.3->googletrans) (3.0.4)
Collecting rfc3986<2,>=1.3
Downloading https://files.pythonhosted.org/packages/78/be/7b8b99fd74ff5684225f50dd0e865393d2265656ef3b4ba9eaaaffe622b8/rfc3986-1.4.0-py2.py3-none-any.whl
Collecting hstspreload
Downloading https://files.pythonhosted.org/packages/45/c1/732c4f4dd2f1340388e36d6fd9ae601013e93595890497d3854f533307c6/hstspreload-2020.8.8-py3-none-any.whl (930kB)
|████████████████████████████████| 931kB 7.9MB/s
Collecting httpcore==0.9.*
Downloading https://files.pythonhosted.org/packages/dd/d5/e4ff9318693ac6101a2095e580908b591838c6f33df8d3ee8dd953ba96a8/httpcore-0.9.1-py3-none-any.whl (42kB)
|████████████████████████████████| 51kB 7.4MB/s
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from httpx==0.13.3->googletrans) (2020.6.20)
Collecting sniffio
Downloading https://files.pythonhosted.org/packages/b3/82/4bd4b7d9c0d1dc0fbfbc2a1e00138e7f3ab85bc239358fe9b78aa2ab586d/sniffio-1.1.0-py3-none-any.whl
Requirement already satisfied: idna==2.* in /usr/local/lib/python3.6/dist-packages (from httpx==0.13.3->googletrans) (2.10)
Collecting h11<0.10,>=0.8
Downloading https://files.pythonhosted.org/packages/5a/fd/3dad730b0f95e78aeeb742f96fa7bbecbdd56a58e405d3da440d5bfb90c6/h11-0.9.0-py2.py3-none-any.whl (53kB)
|████████████████████████████████| 61kB 7.5MB/s
Collecting h2==3.*
Downloading https://files.pythonhosted.org/packages/25/de/da019bcc539eeab02f6d45836f23858ac467f584bfec7a526ef200242afe/h2-3.2.0-py2.py3-none-any.whl (65kB)
|████████████████████████████████| 71kB 8.3MB/s
Collecting contextvars>=2.1; python_version < "3.7"
Downloading https://files.pythonhosted.org/packages/83/96/55b82d9f13763be9d672622e1b8106c85acb83edd7cc2fa5bc67cd9877e9/contextvars-2.4.tar.gz
Collecting hpack<4,>=3.0
Downloading https://files.pythonhosted.org/packages/8a/cc/e53517f4a1e13f74776ca93271caef378dadec14d71c61c949d759d3db69/hpack-3.0.0-py2.py3-none-any.whl
Collecting hyperframe<6,>=5.2.0
Downloading https://files.pythonhosted.org/packages/19/0c/bf88182bcb5dce3094e2f3e4fe20db28a9928cb7bd5b08024030e4b140db/hyperframe-5.2.0-py2.py3-none-any.whl
Collecting immutables>=0.9
Downloading https://files.pythonhosted.org/packages/99/e0/ea6fd4697120327d26773b5a84853f897a68e33d3f9376b00a8ff96e4f63/immutables-0.14-cp36-cp36m-manylinux1_x86_64.whl (98kB)
|████████████████████████████████| 102kB 9.1MB/s
Building wheels for collected packages: googletrans, contextvars
Building wheel for googletrans (setup.py) ... done
Created wheel for googletrans: filename=googletrans-3.0.0-cp36-none-any.whl size=15736 sha256=ff7b2a4e87aa0b1a99d73d7fc65f520eda57c43d965be132208c22d2ed63b9b8
Stored in directory: /root/.cache/pip/wheels/28/1a/a7/eaf4d7a3417a0c65796c547cff4deb6d79c7d14c2abd29273e
Building wheel for contextvars (setup.py) ... done
Created wheel for contextvars: filename=contextvars-2.4-cp36-none-any.whl size=7666 sha256=20946ee05dbf98289686f0fd61c06e941485fac64829c40a417616d44bc2efae
Stored in directory: /root/.cache/pip/wheels/a5/7d/68/1ebae2668bda2228686e3c1cf16f2c2384cea6e9334ad5f6de
Successfully built googletrans contextvars
Installing collected packages: rfc3986, hstspreload, immutables, contextvars, sniffio, h11, hpack, hyperframe, h2, httpcore, httpx, googletrans
Successfully installed contextvars-2.4 googletrans-3.0.0 h11-0.9.0 h2-3.2.0 hpack-3.0.0 hstspreload-2020.8.8 httpcore-0.9.1 httpx-0.13.3 hyperframe-5.2.0 immutables-0.14 rfc3986-1.4.0 sniffio-1.1.0
from googletrans import Translator
translator = Translator()
Example 1:
origin_text = "Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it."
print(origin_text)
Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it.
# translate from English to Italian
text_trans = translator.translate(text=origin_text, dest='it').text
print(text_trans)
La leadership richiede due cose: una visione del mondo che ancora non esiste e la capacità di comunicarlo.
# translate back to Englisht from Italian
translator.translate(text=text_trans, dest='en').text
'Leadership requires two things: a view of the world that does not yet exist and the ability to communicate it.'
Example 2:
origin_text = "The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen"
print(origin_text)
The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen
# translate from English to Italian
text_trans = translator.translate(text=origin_text, dest='it').text
print(text_trans)
Il ruolo di un leader non è quello di trovare tutte le grandi idee. Il ruolo di un leader è creare un ambiente in cui possano nascere grandi idee
# translate back to English from Italian
translator.translate(text=text_trans, dest='en').text
'The role of a leader is not to find all the great ideas. The role of a leader is to create an environment where great ideas can arise'
We can apply this technique to real-world data. The sample code is given below. Here the original train dataframe is copied to tran_aug dataframe and then back-translation is applied on train_aug dataframe. And finally, train_aug is appended to the original train dataframe. Note that we are translating original text from English to Italian and then from Italian to English.
train_aug = train.copy()from googletrans import Translatortranslator = Translator()train_aug['text'] = train_aug['text'].apply(lambda x: translator.translate(translator.translate(x, dest='it').text, dest='en').text)train = train.append(train_aug, ignore_index=True)
Now you know how to make use of TextAttack and Googletrans libraries for your data science projects for text data augmentation.
To read more such interesting articles on Python and Data Science, subscribe to my blog www.pythonsimplified.com. You can also reach me on LinkedIn.
|
[
{
"code": null,
"e": 418,
"s": 172,
"text": "Data Augmentation is the process that enables us to increase the size of the training data without actually collecting the data. But why do we need more data? The answer is simple — the more data we have, the better the performance of the model."
},
{
"code": null,
"e": 980,
"s": 418,
"text": "Image data augmentation steps such as flipping, cropping, rotation, blurring, zooming, etc. helped tremendously in computer vision. Also, it is relatively easy to create augmented images but the same is not the case with Natural Language Processing (NLP) due to the complexities inherent in the language. (For example, we can not replace every word by its synonym, and even if we replace it, the meaning of the sentence might change completely). Based on my findings/research, I haven’t seen as much research around text data augmentation as image augmentation."
},
{
"code": null,
"e": 1156,
"s": 980,
"text": "However, in this article, we will go thru 2 libraries TextAttack & Googletrans I have come across recently when I was trying augmentation for text data. So, let’s get started."
},
{
"code": null,
"e": 1252,
"s": 1156,
"text": "We will apply the augmentation techniques we are going to learn on these quotes of Simon Sinek."
},
{
"code": null,
"e": 1367,
"s": 1252,
"text": "“Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it.”"
},
{
"code": null,
"e": 1515,
"s": 1367,
"text": "“The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen”"
},
{
"code": null,
"e": 1529,
"s": 1515,
"text": "- Simon Sinek"
},
{
"code": null,
"e": 1697,
"s": 1529,
"text": "TextAttack is a Python framework for adversarial attacks, adversarial training, and data augmentation in NLP. In this article, we will focus only on data augmentation."
},
{
"code": null,
"e": 1721,
"s": 1697,
"text": "!pip install textattack"
},
{
"code": null,
"e": 1882,
"s": 1721,
"text": "The textattack.Augmenter class provides six methods for data augmentation. You can find the detailed description of these methods in the official documentation."
},
{
"code": null,
"e": 1983,
"s": 1882,
"text": "WordNetAugmenterEmbeddingAugmenterCharSwapAugmenterEasyDataAugmenterCheckListAugmenterCLAREAugmenter"
},
{
"code": null,
"e": 2000,
"s": 1983,
"text": "WordNetAugmenter"
},
{
"code": null,
"e": 2019,
"s": 2000,
"text": "EmbeddingAugmenter"
},
{
"code": null,
"e": 2037,
"s": 2019,
"text": "CharSwapAugmenter"
},
{
"code": null,
"e": 2055,
"s": 2037,
"text": "EasyDataAugmenter"
},
{
"code": null,
"e": 2074,
"s": 2055,
"text": "CheckListAugmenter"
},
{
"code": null,
"e": 2089,
"s": 2074,
"text": "CLAREAugmenter"
},
{
"code": null,
"e": 2316,
"s": 2089,
"text": "Let’s look at the data augmentation results using these four methods. Note that pct_words_to_swap=0.1, transformations_per_example=4 are passed to each of these methods by default. We can modify these default values as needed."
},
{
"code": null,
"e": 2346,
"s": 2316,
"text": "!pip install pyarrow==0.16.0\n"
},
{
"code": null,
"e": 3045,
"s": 2346,
"text": "Collecting pyarrow==0.16.0\n Downloading https://files.pythonhosted.org/packages/00/d2/695bab1e1e7a4554b6dbd287d55cca096214bd441037058a432afd724bb1/pyarrow-0.16.0-cp36-cp36m-manylinux2014_x86_64.whl (63.1MB)\n |████████████████████████████████| 63.2MB 63kB/s \nRequirement already satisfied: six>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from pyarrow==0.16.0) (1.15.0)\nRequirement already satisfied: numpy>=1.14 in /usr/local/lib/python3.6/dist-packages (from pyarrow==0.16.0) (1.18.5)\nInstalling collected packages: pyarrow\n Found existing installation: pyarrow 0.14.1\n Uninstalling pyarrow-0.14.1:\n Successfully uninstalled pyarrow-0.14.1\nSuccessfully installed pyarrow-0.16.0\n"
},
{
"code": null,
"e": 3070,
"s": 3045,
"text": "!pip install textattack\n"
},
{
"code": null,
"e": 30380,
"s": 3070,
"text": "Collecting textattack\n Downloading https://files.pythonhosted.org/packages/df/eb/bb9793f290f0ca40c725f15144171318c1b1e1952ee249cecb66ed5fe841/textattack-0.2.4-py3-none-any.whl (207kB)\n |████████████████████████████████| 215kB 2.7MB/s \nCollecting flair>=0.5.1\n Downloading https://files.pythonhosted.org/packages/60/8f/51d1f2eb5f9b09beb1e6858b4c174a087bc3b05893438e2cd3ffbf9c6e8b/flair-0.5.1-py3-none-any.whl (201kB)\n |████████████████████████████████| 204kB 8.0MB/s \nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from textattack) (0.22.2.post1)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from textattack) (4.41.1)\nRequirement already satisfied: pandas>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from textattack) (1.0.5)\nCollecting visdom\n Downloading https://files.pythonhosted.org/packages/c9/75/e078f5a2e1df7e0d3044749089fc2823e62d029cc027ed8ae5d71fafcbdc/visdom-0.1.8.9.tar.gz (676kB)\n |████████████████████████████████| 686kB 11.4MB/s \nCollecting wandb\n Downloading https://files.pythonhosted.org/packages/94/19/f8db9eff4b0173adf6dd2e8b0c3d8de0bfe10ec9ed63d247665980d82258/wandb-0.9.4-py2.py3-none-any.whl (1.4MB)\n |████████████████████████████████| 1.4MB 17.9MB/s \nCollecting tensorboardX\n Downloading https://files.pythonhosted.org/packages/af/0c/4f41bcd45db376e6fe5c619c01100e9b7531c55791b7244815bac6eac32c/tensorboardX-2.1-py2.py3-none-any.whl (308kB)\n |████████████████████████████████| 317kB 22.5MB/s \nCollecting lemminflect\n Downloading https://files.pythonhosted.org/packages/8d/c5/62e8dd0b6cbfea212cf55a2338838d85a819dbda9462ba53a415dcf19b86/lemminflect-0.2.1-py3-none-any.whl (769kB)\n |████████████████████████████████| 778kB 26.6MB/s \nCollecting tokenizers==0.8.1-rc1\n Downloading https://files.pythonhosted.org/packages/40/d0/30d5f8d221a0ed981a186c8eb986ce1c94e3a6e87f994eae9f4aa5250217/tokenizers-0.8.1rc1-cp36-cp36m-manylinux1_x86_64.whl (3.0MB)\n |████████████████████████████████| 3.0MB 37.0MB/s \nCollecting nlp\n Downloading https://files.pythonhosted.org/packages/09/e3/bcdc59f3434b224040c1047769c47b82705feca2b89ebbc28311e3764782/nlp-0.4.0-py3-none-any.whl (1.7MB)\n |████████████████████████████████| 1.7MB 33.8MB/s \nRequirement already satisfied: scipy==1.4.1 in /usr/local/lib/python3.6/dist-packages (from textattack) (1.4.1)\nRequirement already satisfied: pyarrow<1.0 in /usr/local/lib/python3.6/dist-packages (from textattack) (0.16.0)\nRequirement already satisfied: tensorflow>=2 in /usr/local/lib/python3.6/dist-packages (from textattack) (2.3.0)\nCollecting terminaltables\n Downloading https://files.pythonhosted.org/packages/9b/c4/4a21174f32f8a7e1104798c445dacdc1d4df86f2f26722767034e4de4bff/terminaltables-3.1.0.tar.gz\nCollecting language-tool-python\n Downloading https://files.pythonhosted.org/packages/d2/4a/95ee8562f40bb8e72f6da43f888e3577711cb49cf62ffedff2b6316d25b5/language_tool_python-2.3.1-py3-none-any.whl\nRequirement already satisfied: editdistance in /usr/local/lib/python3.6/dist-packages (from textattack) (0.5.3)\nRequirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from textattack) (1.6.0+cu101)\nCollecting transformers==3.0.2\n Downloading https://files.pythonhosted.org/packages/27/3c/91ed8f5c4e7ef3227b4119200fc0ed4b4fd965b1f0172021c25701087825/transformers-3.0.2-py3-none-any.whl (769kB)\n |████████████████████████████████| 778kB 37.4MB/s \nRequirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from textattack) (3.2.5)\nRequirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from textattack) (3.0.12)\nCollecting sentence-transformers>0.2.6\n Downloading https://files.pythonhosted.org/packages/ee/71/acfb3f1016f83d90590130dc2ee0d8cd36b005aa7afa45b465837b711070/sentence-transformers-0.3.3.tar.gz (65kB)\n |████████████████████████████████| 71kB 7.9MB/s \nCollecting lru-dict\n Downloading https://files.pythonhosted.org/packages/00/a5/32ed6e10246cd341ca8cc205acea5d208e4053f48a4dced2b1b31d45ba3f/lru-dict-1.1.6.tar.gz\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from textattack) (1.18.5)\nRequirement already satisfied: tensorflow-hub in /usr/local/lib/python3.6/dist-packages (from textattack) (0.8.0)\nCollecting bert-score\n Downloading https://files.pythonhosted.org/packages/50/8c/70244d0f351176c9984643e2037edc18b9124491b47ad19191039a18d2bd/bert_score-0.3.5-py3-none-any.whl (52kB)\n |████████████████████████████████| 61kB 6.9MB/s \nCollecting langdetect\n Downloading https://files.pythonhosted.org/packages/56/a3/8407c1e62d5980188b4acc45ef3d94b933d14a2ebc9ef3505f22cf772570/langdetect-1.0.8.tar.gz (981kB)\n |████████████████████████████████| 983kB 43.8MB/s \nCollecting pytest>=5.3.2\n Downloading https://files.pythonhosted.org/packages/98/db/712bee56f9ab20373508a5a1c662e1db49b407dacf03b5224c6171ed0a3d/pytest-6.0.1-py3-none-any.whl (270kB)\n |████████████████████████████████| 276kB 44.2MB/s \nCollecting segtok>=1.5.7\n Downloading https://files.pythonhosted.org/packages/41/08/582dab5f4b1d5ca23bc6927b4bb977c8ff7f3a87a3b98844ef833e2f5623/segtok-1.5.10.tar.gz\nCollecting sqlitedict>=1.6.0\n Downloading https://files.pythonhosted.org/packages/0f/1c/c757b93147a219cf1e25cef7e1ad9b595b7f802159493c45ce116521caff/sqlitedict-1.6.0.tar.gz\nRequirement already satisfied: matplotlib>=2.2.3 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (3.2.2)\nCollecting mpld3==0.3\n Downloading https://files.pythonhosted.org/packages/91/95/a52d3a83d0a29ba0d6898f6727e9858fe7a43f6c2ce81a5fe7e05f0f4912/mpld3-0.3.tar.gz (788kB)\n |████████████████████████████████| 798kB 40.0MB/s \nRequirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (2.8.1)\nRequirement already satisfied: gensim>=3.4.0 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (3.6.0)\nCollecting deprecated>=1.2.4\n Downloading https://files.pythonhosted.org/packages/76/a1/05d7f62f956d77b23a640efc650f80ce24483aa2f85a09c03fb64f49e879/Deprecated-1.2.10-py2.py3-none-any.whl\nRequirement already satisfied: hyperopt>=0.1.1 in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (0.1.2)\nCollecting bpemb>=0.2.9\n Downloading https://files.pythonhosted.org/packages/91/77/3f0f53856e86af32b1d3c86652815277f7b5f880002584eb30db115b6df5/bpemb-0.3.2-py3-none-any.whl\nRequirement already satisfied: regex in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (2019.12.20)\nCollecting sentencepiece!=0.1.92\n Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)\n |████████████████████████████████| 1.1MB 30.7MB/s \nRequirement already satisfied: tabulate in /usr/local/lib/python3.6/dist-packages (from flair>=0.5.1->textattack) (0.8.7)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->textattack) (0.16.0)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=1.0.1->textattack) (2018.9)\nRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (2.23.0)\nRequirement already satisfied: tornado in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (5.1.1)\nRequirement already satisfied: pyzmq in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (19.0.2)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (1.15.0)\nCollecting jsonpatch\n Downloading https://files.pythonhosted.org/packages/4f/d0/34b0f59ac08de9c1e07876cfecd80aec650600177b4bd445124c755499a7/jsonpatch-1.26-py2.py3-none-any.whl\nCollecting torchfile\n Downloading https://files.pythonhosted.org/packages/91/af/5b305f86f2d218091af657ddb53f984ecbd9518ca9fe8ef4103a007252c9/torchfile-0.1.0.tar.gz\nCollecting websocket-client\n Downloading https://files.pythonhosted.org/packages/4c/5f/f61b420143ed1c8dc69f9eaec5ff1ac36109d52c80de49d66e0c36c3dfdf/websocket_client-0.57.0-py2.py3-none-any.whl (200kB)\n |████████████████████████████████| 204kB 38.4MB/s \nRequirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from visdom->textattack) (7.0.0)\nCollecting subprocess32>=3.5.3\n Downloading https://files.pythonhosted.org/packages/32/c8/564be4d12629b912ea431f1a50eb8b3b9d00f1a0b1ceff17f266be190007/subprocess32-3.5.4.tar.gz (97kB)\n |████████████████████████████████| 102kB 11.4MB/s \nCollecting watchdog>=0.8.3\n Downloading https://files.pythonhosted.org/packages/0e/06/121302598a4fc01aca942d937f4a2c33430b7181137b35758913a8db10ad/watchdog-0.10.3.tar.gz (94kB)\n |████████████████████████████████| 102kB 10.0MB/s \nCollecting docker-pycreds>=0.4.0\n Downloading https://files.pythonhosted.org/packages/f5/e8/f6bd1eee09314e7e6dee49cbe2c5e22314ccdb38db16c9fc72d2fa80d054/docker_pycreds-0.4.0-py2.py3-none-any.whl\nCollecting GitPython>=1.0.0\n Downloading https://files.pythonhosted.org/packages/f9/1e/a45320cab182bf1c8656107b3d4c042e659742822fc6bff150d769a984dd/GitPython-3.1.7-py3-none-any.whl (158kB)\n |████████████████████████████████| 163kB 34.9MB/s \nRequirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (3.13)\nRequirement already satisfied: nvidia-ml-py3>=7.352.0 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (7.352.0)\nCollecting shortuuid>=0.5.0\n Downloading https://files.pythonhosted.org/packages/25/a6/2ecc1daa6a304e7f1b216f0896b26156b78e7c38e1211e9b798b4716c53d/shortuuid-1.0.1-py3-none-any.whl\nCollecting configparser>=3.8.1\n Downloading https://files.pythonhosted.org/packages/4b/6b/01baa293090240cf0562cc5eccb69c6f5006282127f2b846fad011305c79/configparser-5.0.0-py3-none-any.whl\nRequirement already satisfied: psutil>=5.0.0 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (5.4.8)\nCollecting gql==0.2.0\n Downloading https://files.pythonhosted.org/packages/c4/6f/cf9a3056045518f06184e804bae89390eb706168349daa9dff8ac609962a/gql-0.2.0.tar.gz\nCollecting sentry-sdk>=0.4.0\n Downloading https://files.pythonhosted.org/packages/4b/23/811fcdfc9d67fea7e47c91dd553081218d53dda744c28384f4d2f69206c9/sentry_sdk-0.16.3-py2.py3-none-any.whl (110kB)\n |████████████████████████████████| 112kB 40.6MB/s \nRequirement already satisfied: Click>=7.0 in /usr/local/lib/python3.6/dist-packages (from wandb->textattack) (7.1.2)\nRequirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorboardX->textattack) (3.12.4)\nRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from nlp->textattack) (0.7)\nRequirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from nlp->textattack) (0.3.2)\nCollecting xxhash\n Downloading https://files.pythonhosted.org/packages/f7/73/826b19f3594756cb1c6c23d2fbd8ca6a77a9cd3b650c9dec5acc85004c38/xxhash-2.0.0-cp36-cp36m-manylinux2010_x86_64.whl (242kB)\n |████████████████████████████████| 245kB 41.7MB/s \nRequirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.6.3)\nRequirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (3.3.0)\nRequirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (2.3.0)\nRequirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.3.3)\nRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.9.0)\nRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.34.2)\nRequirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (2.10.0)\nRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.1.0)\nRequirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.1.2)\nRequirement already satisfied: tensorflow-estimator<2.4.0,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (2.3.0)\nRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.30.0)\nRequirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (0.2.0)\nRequirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2->textattack) (1.12.1)\nRequirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch->textattack) (0.16.0)\nRequirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers==3.0.2->textattack) (20.4)\nCollecting sacremoses\n Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)\n |████████████████████████████████| 890kB 36.1MB/s \nRequirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (8.4.0)\nCollecting pluggy<1.0,>=0.12\n Downloading https://files.pythonhosted.org/packages/a0/28/85c7aa31b80d150b772fbe4a229487bc6644da9ccb7e427dd8cc60cb8a62/pluggy-0.13.1-py2.py3-none-any.whl\nRequirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (0.10.1)\nRequirement already satisfied: py>=1.8.2 in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (1.9.0)\nRequirement already satisfied: iniconfig in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (1.0.1)\nRequirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (19.3.0)\nRequirement already satisfied: importlib-metadata>=0.12; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from pytest>=5.3.2->flair>=0.5.1->textattack) (1.7.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2.3->flair>=0.5.1->textattack) (1.2.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2.3->flair>=0.5.1->textattack) (2.4.7)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2.3->flair>=0.5.1->textattack) (0.10.0)\nRequirement already satisfied: smart-open>=1.2.1 in /usr/local/lib/python3.6/dist-packages (from gensim>=3.4.0->flair>=0.5.1->textattack) (2.1.0)\nRequirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from hyperopt>=0.1.1->flair>=0.5.1->textattack) (2.4)\nRequirement already satisfied: pymongo in /usr/local/lib/python3.6/dist-packages (from hyperopt>=0.1.1->flair>=0.5.1->textattack) (3.11.0)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (1.24.3)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (2020.6.20)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->visdom->textattack) (2.10)\nCollecting jsonpointer>=1.9\n Downloading https://files.pythonhosted.org/packages/18/b0/a80d29577c08eea401659254dfaed87f1af45272899e1812d7e01b679bc5/jsonpointer-2.0-py2.py3-none-any.whl\nCollecting pathtools>=0.1.1\n Downloading https://files.pythonhosted.org/packages/e7/7f/470d6fcdf23f9f3518f6b0b76be9df16dcc8630ad409947f8be2eb0ed13a/pathtools-0.1.2.tar.gz\nCollecting gitdb<5,>=4.0.1\n Downloading https://files.pythonhosted.org/packages/48/11/d1800bca0a3bae820b84b7d813ad1eff15a48a64caea9c823fc8c1b119e8/gitdb-4.0.5-py3-none-any.whl (63kB)\n |████████████████████████████████| 71kB 7.6MB/s \nCollecting graphql-core<2,>=0.5.0\n Downloading https://files.pythonhosted.org/packages/b0/89/00ad5e07524d8c523b14d70c685e0299a8b0de6d0727e368c41b89b7ed0b/graphql-core-1.1.tar.gz (70kB)\n |████████████████████████████████| 71kB 6.5MB/s \nRequirement already satisfied: promise<3,>=2.0 in /usr/local/lib/python3.6/dist-packages (from gql==0.2.0->wandb->textattack) (2.3)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.8.0->tensorboardX->textattack) (49.2.0)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.7.0)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.0.1)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (3.2.2)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (0.4.1)\nRequirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.17.2)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.12; python_version < \"3.8\"->pytest>=5.3.2->flair>=0.5.1->textattack) (3.1.0)\nRequirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (1.14.33)\nRequirement already satisfied: boto in /usr/local/lib/python3.6/dist-packages (from smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (2.49.0)\nRequirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->hyperopt>=0.1.1->flair>=0.5.1->textattack) (4.4.2)\nCollecting smmap<4,>=3.0.1\n Downloading https://files.pythonhosted.org/packages/b0/9a/4d409a6234eb940e6a78dfdfc66156e7522262f5f2fecca07dc55915952d/smmap-3.0.4-py2.py3-none-any.whl\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (1.3.0)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (0.2.8)\nRequirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (4.6)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (4.1.1)\nRequirement already satisfied: botocore<1.18.0,>=1.17.33 in /usr/local/lib/python3.6/dist-packages (from boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (1.17.33)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (0.10.0)\nRequirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (0.3.3)\nRequirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (3.1.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow>=2->textattack) (0.4.8)\nRequirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.18.0,>=1.17.33->boto3->smart-open>=1.2.1->gensim>=3.4.0->flair>=0.5.1->textattack) (0.15.2)\nBuilding wheels for collected packages: visdom, terminaltables, sentence-transformers, lru-dict, langdetect, segtok, sqlitedict, mpld3, torchfile, subprocess32, watchdog, gql, sacremoses, pathtools, graphql-core\n Building wheel for visdom (setup.py) ... done\n Created wheel for visdom: filename=visdom-0.1.8.9-cp36-none-any.whl size=655250 sha256=021ecf255f934787d40fdc3808b5cb6f59e53c7bdd18f1aa58119bb494c8230b\n Stored in directory: /root/.cache/pip/wheels/70/19/a7/6d589ed967f4dfefd33bc166d081257bd4ed0cb618dccfd62a\n Building wheel for terminaltables (setup.py) ... done\n Created wheel for terminaltables: filename=terminaltables-3.1.0-cp36-none-any.whl size=15356 sha256=11bd424019d47ef03b9b055f4ae0c5de6f5b953e14a30ef54218857a638c2613\n Stored in directory: /root/.cache/pip/wheels/30/6b/50/6c75775b681fb36cdfac7f19799888ef9d8813aff9e379663e\n Building wheel for sentence-transformers (setup.py) ... done\n Created wheel for sentence-transformers: filename=sentence_transformers-0.3.3-cp36-none-any.whl size=97299 sha256=d1d4f8047c37c1616c94c6f24f0e2ee327c3768200f4f13256bd6d306ccbcddc\n Stored in directory: /root/.cache/pip/wheels/75/d6/0a/cab163b21d0597cc1580bc344487b11ad405e0d1d314725f2b\n Building wheel for lru-dict (setup.py) ... done\n Created wheel for lru-dict: filename=lru_dict-1.1.6-cp36-cp36m-linux_x86_64.whl size=25864 sha256=9f0c1af722bacbb05e34202cf6d062f406cf508e65b623a56ba51c9a3747462e\n Stored in directory: /root/.cache/pip/wheels/b7/ef/06/fbdd555907a7d438fb33e4c8675f771ff1cf41917284c51ebf\n Building wheel for langdetect (setup.py) ... done\n Created wheel for langdetect: filename=langdetect-1.0.8-cp36-none-any.whl size=993193 sha256=f6806cc32d2d54c50fd8cd5eb9c4ee3634002c089e479143004248b6213c4324\n Stored in directory: /root/.cache/pip/wheels/8d/b3/aa/6d99de9f3841d7d3d40a60ea06e6d669e8e5012e6c8b947a57\n Building wheel for segtok (setup.py) ... done\n Created wheel for segtok: filename=segtok-1.5.10-cp36-none-any.whl size=25020 sha256=f3bb5a27e2e5f9411305807610b17562f95896e7cb1de79520e393f17153e09f\n Stored in directory: /root/.cache/pip/wheels/b4/39/f6/9ca1c5cabde964d728023b5751c3a206a5c8cc40252321fb6b\n Building wheel for sqlitedict (setup.py) ... done\n Created wheel for sqlitedict: filename=sqlitedict-1.6.0-cp36-none-any.whl size=14689 sha256=dadddd2a944c7e9e4b9e25deb4a0661d03f882ed71f84c73c5938900f5a02397\n Stored in directory: /root/.cache/pip/wheels/bd/57/d3/907c3ee02d35e66f674ad0106e61f06eeeb98f6ee66a6cc3fe\n Building wheel for mpld3 (setup.py) ... done\n Created wheel for mpld3: filename=mpld3-0.3-cp36-none-any.whl size=116679 sha256=083b76dbbce87fafde4618a05fb9f26a3c88856b4e01b9158b82fa0db216ac1d\n Stored in directory: /root/.cache/pip/wheels/c0/47/fb/8a64f89aecfe0059830479308ad42d62e898a3e3cefdf6ba28\n Building wheel for torchfile (setup.py) ... done\n Created wheel for torchfile: filename=torchfile-0.1.0-cp36-none-any.whl size=5712 sha256=e181fea9479102f59cc0172804beea0549594ba49f2b0e6a2e4d20316e732089\n Stored in directory: /root/.cache/pip/wheels/b1/c3/d6/9a1cc8f3a99a0fc1124cae20153f36af59a6e683daca0a0814\n Building wheel for subprocess32 (setup.py) ... done\n Created wheel for subprocess32: filename=subprocess32-3.5.4-cp36-none-any.whl size=6489 sha256=cee805c7291b55f24d0b4e4fcfa06915bfbe93e6bf9a4eaa9cab87633fd34ff2\n Stored in directory: /root/.cache/pip/wheels/68/39/1a/5e402bdfdf004af1786c8b853fd92f8c4a04f22aad179654d1\n Building wheel for watchdog (setup.py) ... done\n Created wheel for watchdog: filename=watchdog-0.10.3-cp36-none-any.whl size=73870 sha256=1a2896b9c4d89700d00421232ec98119340bbbf2bfb98daba4d4c947c5f33624\n Stored in directory: /root/.cache/pip/wheels/a8/1d/38/2c19bb311f67cc7b4d07a2ec5ea36ab1a0a0ea50db994a5bc7\n Building wheel for gql (setup.py) ... done\n Created wheel for gql: filename=gql-0.2.0-cp36-none-any.whl size=7630 sha256=f90f7f403b9d2af02e220bd61968c7f7d4aeeb52a756f6527e8c751662a4c743\n Stored in directory: /root/.cache/pip/wheels/ce/0e/7b/58a8a5268655b3ad74feef5aa97946f0addafb3cbb6bd2da23\n Building wheel for sacremoses (setup.py) ... done\n Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893260 sha256=7a42b3f6968d9cd8a928f232911a1e4c188a1d737be201eb142410cba4c28641\n Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45\n Building wheel for pathtools (setup.py) ... done\n Created wheel for pathtools: filename=pathtools-0.1.2-cp36-none-any.whl size=8784 sha256=40e6d9de6b3e8584a9780536a67a3276ca90f8f63e13faa1e5cadcfaf2f336c5\n Stored in directory: /root/.cache/pip/wheels/0b/04/79/c3b0c3a0266a3cb4376da31e5bfe8bba0c489246968a68e843\n Building wheel for graphql-core (setup.py) ... done\n Created wheel for graphql-core: filename=graphql_core-1.1-cp36-none-any.whl size=104650 sha256=44a8e1a804ae3d4a17feb1b3ba836f04df2aa7d51acb2fe79ee72e8316ec2496\n Stored in directory: /root/.cache/pip/wheels/45/99/d7/c424029bb0fe910c63b68dbf2aa20d3283d023042521bcd7d5\nSuccessfully built visdom terminaltables sentence-transformers lru-dict langdetect segtok sqlitedict mpld3 torchfile subprocess32 watchdog gql sacremoses pathtools graphql-core\nERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.\nInstalling collected packages: langdetect, pluggy, pytest, segtok, sqlitedict, mpld3, deprecated, sentencepiece, bpemb, tokenizers, sacremoses, transformers, flair, jsonpointer, jsonpatch, torchfile, websocket-client, visdom, subprocess32, pathtools, watchdog, docker-pycreds, smmap, gitdb, GitPython, shortuuid, configparser, graphql-core, gql, sentry-sdk, wandb, tensorboardX, lemminflect, xxhash, nlp, terminaltables, language-tool-python, sentence-transformers, lru-dict, bert-score, textattack\n Found existing installation: pluggy 0.7.1\n Uninstalling pluggy-0.7.1:\n Successfully uninstalled pluggy-0.7.1\n Found existing installation: pytest 3.6.4\n Uninstalling pytest-3.6.4:\n Successfully uninstalled pytest-3.6.4\nSuccessfully installed GitPython-3.1.7 bert-score-0.3.5 bpemb-0.3.2 configparser-5.0.0 deprecated-1.2.10 docker-pycreds-0.4.0 flair-0.5.1 gitdb-4.0.5 gql-0.2.0 graphql-core-1.1 jsonpatch-1.26 jsonpointer-2.0 langdetect-1.0.8 language-tool-python-2.3.1 lemminflect-0.2.1 lru-dict-1.1.6 mpld3-0.3 nlp-0.4.0 pathtools-0.1.2 pluggy-0.13.1 pytest-6.0.1 sacremoses-0.0.43 segtok-1.5.10 sentence-transformers-0.3.3 sentencepiece-0.1.91 sentry-sdk-0.16.3 shortuuid-1.0.1 smmap-3.0.4 sqlitedict-1.6.0 subprocess32-3.5.4 tensorboardX-2.1 terminaltables-3.1.0 textattack-0.2.4 tokenizers-0.8.1rc1 torchfile-0.1.0 transformers-3.0.2 visdom-0.1.8.9 wandb-0.9.4 watchdog-0.10.3 websocket-client-0.57.0 xxhash-2.0.0\n"
},
{
"code": null,
"e": 30492,
"s": 30380,
"text": "from textattack.augmentation import WordNetAugmenter, EmbeddingAugmenter, EasyDataAugmenter, CharSwapAugmenter\n"
},
{
"code": null,
"e": 30625,
"s": 30492,
"text": "textattack: First time running textattack: downloading remaining required packages.\ntextattack: Downloading NLTK required packages.\n"
},
{
"code": null,
"e": 31130,
"s": 30625,
"text": "[nltk_data] Downloading package wordnet to /root/nltk_data...\n[nltk_data] Unzipping corpora/wordnet.zip.\n[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] /root/nltk_data...\n[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n[nltk_data] Downloading package universal_tagset to /root/nltk_data...\n[nltk_data] Unzipping taggers/universal_tagset.zip.\n[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Unzipping corpora/stopwords.zip.\n"
},
{
"code": null,
"e": 31237,
"s": 31130,
"text": "wandb: WARNING W&B installed but not logged in. Run `wandb login` or set the WANDB_API_KEY env variable.\n"
},
{
"code": null,
"e": 31248,
"s": 31237,
"text": "Example 1:"
},
{
"code": null,
"e": 31371,
"s": 31248,
"text": "text = \"Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it.\"\n"
},
{
"code": null,
"e": 31415,
"s": 31371,
"text": "aug = WordNetAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 31543,
"s": 31415,
"text": "['Leadership requires two things: a imaginativeness of the world that does not yet survive and the ability to communicate it.']"
},
{
"code": null,
"e": 31589,
"s": 31543,
"text": "aug = EmbeddingAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 31919,
"s": 31589,
"text": "textattack: Downloading https://textattack.s3.amazonaws.com/word_embeddings/paragramcf.\n100%|██████████| 481M/481M [00:09<00:00, 52.4MB/s]\ntextattack: Unzipping file /root/.cache/textattack/tmppu06z0jb.zip to /root/.cache/textattack/word_embeddings/paragramcf.\ntextattack: Successfully saved word_embeddings/paragramcf to cache.\n"
},
{
"code": null,
"e": 32040,
"s": 31919,
"text": "['Leadership requires deux things: a vision of the world that does not yet exist and the capacities to communicate it.']"
},
{
"code": null,
"e": 32085,
"s": 32040,
"text": "aug = EasyDataAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 32546,
"s": 32085,
"text": "['Leadership requires two things: a vision of the world that does not yet be and the power to communicate it.',\n 'Leadership requires two: a of the world that does not yet exist and the ability to communicate it.',\n 'Leadership requires two things: a vision of the world that it communicate yet exist and the ability to not does.',\n 'Leadership requires two live things: a vision of the world that withal does not yet exist and the ability to communicate it.']"
},
{
"code": null,
"e": 32591,
"s": 32546,
"text": "aug = CharSwapAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 32707,
"s": 32591,
"text": "['Leadership requires two things: a visoin of the worl that does not yet exist and the ability to communicate it.']"
},
{
"code": null,
"e": 32718,
"s": 32707,
"text": "Example 2:"
},
{
"code": null,
"e": 32875,
"s": 32718,
"text": "text = \"The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen.\"\n"
},
{
"code": null,
"e": 32919,
"s": 32875,
"text": "aug = WordNetAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 33070,
"s": 32919,
"text": "['The persona of a leader is not to come up with all the great theme. The role of a leader is to create an environment in which great ideas can hap.']"
},
{
"code": null,
"e": 33116,
"s": 33070,
"text": "aug = EmbeddingAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 33273,
"s": 33116,
"text": "['The role of a leader is not to come up with all the great ideas. The role of a leader is to creations an environment in which grand insights can happen.']"
},
{
"code": null,
"e": 33318,
"s": 33273,
"text": "aug = EasyDataAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 33932,
"s": 33318,
"text": "['The role of a leader is not to come up with all the great estimate. The function of a leader is to make an environment in which great ideas can happen.',\n 'The role environment great leader is not to come up with all the a ideas. The role of a leader is to create an of in which great ideas happen can.',\n 'The role of a leader is not to come up with all the great improving ideas. The role of make a leader is to be create an environment in which great ideas can happen.',\n 'role of a leader is not to come up with all the great ideas. The role of a leader is create an environment in which great can happen.']"
},
{
"code": null,
"e": 33977,
"s": 33932,
"text": "aug = CharSwapAugmenter()\naug.augment(text)\n"
},
{
"code": null,
"e": 34128,
"s": 33977,
"text": "['The role of a Sleader is not to come up with all the great ideas. The role of a lXader is to create an environment in which great ides can happen.']"
},
{
"code": null,
"e": 34423,
"s": 34128,
"text": "We can apply these methods to real-world data to increase the size of the data. The sample code is given below. Here the originaltrain dataframe is copied to the train_aug dataframe and then augmentation is applied on train_aug. And finally, train_aug is appended to the original train dataset."
},
{
"code": null,
"e": 34653,
"s": 34423,
"text": "train_aug = train.copy()from textattack.augmentation import EmbeddingAugmenteraug = EmbeddingAugmenter()train_aug['text'] = train_aug['text'].apply(lambda x: str(aug.augment(x)))train = train.append(train_copy, ignore_index=True)"
},
{
"code": null,
"e": 34782,
"s": 34653,
"text": "Googletrans is built on top of Google Translate API. This uses Google Translate Ajax API for language detection and translation."
},
{
"code": null,
"e": 34807,
"s": 34782,
"text": "!pip install googletrans"
},
{
"code": null,
"e": 34853,
"s": 34807,
"text": "The key parameters to translate() method are:"
},
{
"code": null,
"e": 34925,
"s": 34853,
"text": "src: source language. Optional parameter as googletrans will detect it."
},
{
"code": null,
"e": 34974,
"s": 34925,
"text": "dest: destination language. Mandatory parameter."
},
{
"code": null,
"e": 35077,
"s": 34974,
"text": "text: the text to be translated from source language to the destination language. Mandatory parameter."
},
{
"code": null,
"e": 35391,
"s": 35077,
"text": "As we can see, the given text is first translated from English to Italian and then translated to back to English. During this back translation, as we can see, there is a slight change in the sentence between the original text and the back-translated text but the overall meaning of the sentence is still retained."
},
{
"code": null,
"e": 35417,
"s": 35391,
"text": "!pip install googletrans\n"
},
{
"code": null,
"e": 39427,
"s": 35417,
"text": "Collecting googletrans\n Downloading https://files.pythonhosted.org/packages/71/3a/3b19effdd4c03958b90f40fe01c93de6d5280e03843cc5adf6956bfc9512/googletrans-3.0.0.tar.gz\nCollecting httpx==0.13.3\n Downloading https://files.pythonhosted.org/packages/54/b4/698b284c6aed4d7c2b4fe3ba5df1fcf6093612423797e76fbb24890dd22f/httpx-0.13.3-py3-none-any.whl (55kB)\n |████████████████████████████████| 61kB 2.9MB/s \nRequirement already satisfied: chardet==3.* in /usr/local/lib/python3.6/dist-packages (from httpx==0.13.3->googletrans) (3.0.4)\nCollecting rfc3986<2,>=1.3\n Downloading https://files.pythonhosted.org/packages/78/be/7b8b99fd74ff5684225f50dd0e865393d2265656ef3b4ba9eaaaffe622b8/rfc3986-1.4.0-py2.py3-none-any.whl\nCollecting hstspreload\n Downloading https://files.pythonhosted.org/packages/45/c1/732c4f4dd2f1340388e36d6fd9ae601013e93595890497d3854f533307c6/hstspreload-2020.8.8-py3-none-any.whl (930kB)\n |████████████████████████████████| 931kB 7.9MB/s \nCollecting httpcore==0.9.*\n Downloading https://files.pythonhosted.org/packages/dd/d5/e4ff9318693ac6101a2095e580908b591838c6f33df8d3ee8dd953ba96a8/httpcore-0.9.1-py3-none-any.whl (42kB)\n |████████████████████████████████| 51kB 7.4MB/s \nRequirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from httpx==0.13.3->googletrans) (2020.6.20)\nCollecting sniffio\n Downloading https://files.pythonhosted.org/packages/b3/82/4bd4b7d9c0d1dc0fbfbc2a1e00138e7f3ab85bc239358fe9b78aa2ab586d/sniffio-1.1.0-py3-none-any.whl\nRequirement already satisfied: idna==2.* in /usr/local/lib/python3.6/dist-packages (from httpx==0.13.3->googletrans) (2.10)\nCollecting h11<0.10,>=0.8\n Downloading https://files.pythonhosted.org/packages/5a/fd/3dad730b0f95e78aeeb742f96fa7bbecbdd56a58e405d3da440d5bfb90c6/h11-0.9.0-py2.py3-none-any.whl (53kB)\n |████████████████████████████████| 61kB 7.5MB/s \nCollecting h2==3.*\n Downloading https://files.pythonhosted.org/packages/25/de/da019bcc539eeab02f6d45836f23858ac467f584bfec7a526ef200242afe/h2-3.2.0-py2.py3-none-any.whl (65kB)\n |████████████████████████████████| 71kB 8.3MB/s \nCollecting contextvars>=2.1; python_version < \"3.7\"\n Downloading https://files.pythonhosted.org/packages/83/96/55b82d9f13763be9d672622e1b8106c85acb83edd7cc2fa5bc67cd9877e9/contextvars-2.4.tar.gz\nCollecting hpack<4,>=3.0\n Downloading https://files.pythonhosted.org/packages/8a/cc/e53517f4a1e13f74776ca93271caef378dadec14d71c61c949d759d3db69/hpack-3.0.0-py2.py3-none-any.whl\nCollecting hyperframe<6,>=5.2.0\n Downloading https://files.pythonhosted.org/packages/19/0c/bf88182bcb5dce3094e2f3e4fe20db28a9928cb7bd5b08024030e4b140db/hyperframe-5.2.0-py2.py3-none-any.whl\nCollecting immutables>=0.9\n Downloading https://files.pythonhosted.org/packages/99/e0/ea6fd4697120327d26773b5a84853f897a68e33d3f9376b00a8ff96e4f63/immutables-0.14-cp36-cp36m-manylinux1_x86_64.whl (98kB)\n |████████████████████████████████| 102kB 9.1MB/s \nBuilding wheels for collected packages: googletrans, contextvars\n Building wheel for googletrans (setup.py) ... done\n Created wheel for googletrans: filename=googletrans-3.0.0-cp36-none-any.whl size=15736 sha256=ff7b2a4e87aa0b1a99d73d7fc65f520eda57c43d965be132208c22d2ed63b9b8\n Stored in directory: /root/.cache/pip/wheels/28/1a/a7/eaf4d7a3417a0c65796c547cff4deb6d79c7d14c2abd29273e\n Building wheel for contextvars (setup.py) ... done\n Created wheel for contextvars: filename=contextvars-2.4-cp36-none-any.whl size=7666 sha256=20946ee05dbf98289686f0fd61c06e941485fac64829c40a417616d44bc2efae\n Stored in directory: /root/.cache/pip/wheels/a5/7d/68/1ebae2668bda2228686e3c1cf16f2c2384cea6e9334ad5f6de\nSuccessfully built googletrans contextvars\nInstalling collected packages: rfc3986, hstspreload, immutables, contextvars, sniffio, h11, hpack, hyperframe, h2, httpcore, httpx, googletrans\nSuccessfully installed contextvars-2.4 googletrans-3.0.0 h11-0.9.0 h2-3.2.0 hpack-3.0.0 hstspreload-2020.8.8 httpcore-0.9.1 httpx-0.13.3 hyperframe-5.2.0 immutables-0.14 rfc3986-1.4.0 sniffio-1.1.0\n"
},
{
"code": null,
"e": 39489,
"s": 39427,
"text": "from googletrans import Translator\ntranslator = Translator()\n"
},
{
"code": null,
"e": 39500,
"s": 39489,
"text": "Example 1:"
},
{
"code": null,
"e": 39649,
"s": 39500,
"text": "origin_text = \"Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it.\"\nprint(origin_text)\n"
},
{
"code": null,
"e": 39763,
"s": 39649,
"text": "Leadership requires two things: a vision of the world that does not yet exist and the ability to communicate it.\n"
},
{
"code": null,
"e": 39886,
"s": 39763,
"text": "# translate from English to Italian\ntext_trans = translator.translate(text=origin_text, dest='it').text\nprint(text_trans)\n"
},
{
"code": null,
"e": 39995,
"s": 39886,
"text": "La leadership richiede due cose: una visione del mondo che ancora non esiste e la capacità di comunicarlo.\n"
},
{
"code": null,
"e": 40092,
"s": 39995,
"text": "# translate back to Englisht from Italian\ntranslator.translate(text=text_trans, dest='en').text\n"
},
{
"code": null,
"e": 40205,
"s": 40092,
"text": "'Leadership requires two things: a view of the world that does not yet exist and the ability to communicate it.'"
},
{
"code": null,
"e": 40216,
"s": 40205,
"text": "Example 2:"
},
{
"code": null,
"e": 40398,
"s": 40216,
"text": "origin_text = \"The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen\"\nprint(origin_text)\n"
},
{
"code": null,
"e": 40545,
"s": 40398,
"text": "The role of a leader is not to come up with all the great ideas. The role of a leader is to create an environment in which great ideas can happen\n"
},
{
"code": null,
"e": 40668,
"s": 40545,
"text": "# translate from English to Italian\ntext_trans = translator.translate(text=origin_text, dest='it').text\nprint(text_trans)\n"
},
{
"code": null,
"e": 40817,
"s": 40668,
"text": "Il ruolo di un leader non è quello di trovare tutte le grandi idee. Il ruolo di un leader è creare un ambiente in cui possano nascere grandi idee\n"
},
{
"code": null,
"e": 40913,
"s": 40817,
"text": "# translate back to English from Italian\ntranslator.translate(text=text_trans, dest='en').text\n"
},
{
"code": null,
"e": 41049,
"s": 40913,
"text": "'The role of a leader is not to find all the great ideas. The role of a leader is to create an environment where great ideas can arise'"
},
{
"code": null,
"e": 41425,
"s": 41049,
"text": "We can apply this technique to real-world data. The sample code is given below. Here the original train dataframe is copied to tran_aug dataframe and then back-translation is applied on train_aug dataframe. And finally, train_aug is appended to the original train dataframe. Note that we are translating original text from English to Italian and then from Italian to English."
},
{
"code": null,
"e": 41691,
"s": 41425,
"text": "train_aug = train.copy()from googletrans import Translatortranslator = Translator()train_aug['text'] = train_aug['text'].apply(lambda x: translator.translate(translator.translate(x, dest='it').text, dest='en').text)train = train.append(train_aug, ignore_index=True)"
},
{
"code": null,
"e": 41819,
"s": 41691,
"text": "Now you know how to make use of TextAttack and Googletrans libraries for your data science projects for text data augmentation."
}
] |
Tryit Editor v3.7
|
HTML Form elements
Tryit: HTML datalist element
|
[
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML Form elements"
}
] |
HAS-A relationship in Java
|
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Let's look into an example −
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle {
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.
In an Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs."
},
{
"code": null,
"e": 1274,
"s": 1245,
"text": "Let's look into an example −"
},
{
"code": null,
"e": 1376,
"s": 1274,
"text": "public class Vehicle{}\npublic class Speed{}\npublic class Van extends Vehicle {\n private Speed sp;\n}"
},
{
"code": null,
"e": 1610,
"s": 1376,
"text": "This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications."
},
{
"code": null,
"e": 1996,
"s": 1610,
"text": "In an Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action."
}
] |
Python - Convert TSV to CSV file - GeeksforGeeks
|
05 Nov, 2021
In this article, we will see how to Convert TSV Files to CSV using Python.
TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\t”) with comma(“,”) as data in CSV file is comma-separated.
Example:
Input File:
Python3
# Python program to convert .tsv file to .csv file
# importing re library
import re
# reading given tsv file
with open("Olympic.tsv", 'r') as myfile:
with open("Olympic.csv", 'w') as csv_file:
for line in myfile:
# Replace every tab with comma
fileContent = re.sub("\t", ",", line)
# Writing into csv file
csv_file.write(fileContent)
# output
print("Successfully made csv file")
Output:
Successfully made csv file
The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False.
Example:
Input File:
Python3
# Python program to convert .tsv file to .csv file
# importing pandas library
import pandas as pd
tsv_file='GfG.tsv'
# readinag given tsv file
csv_table=pd.read_table(tsv_file,sep='\t')
# converting tsv file into csv
csv_table.to_csv('GfG.csv',index=False)
# output
print("Successfully made csv file")
Output:
Successfully made csv file
Output File:
Picked
Python-TSV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to 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 unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23973,
"s": 23942,
"text": " \n05 Nov, 2021\n"
},
{
"code": null,
"e": 24049,
"s": 23973,
"text": "In this article, we will see how to Convert TSV Files to CSV using Python. "
},
{
"code": null,
"e": 24434,
"s": 24049,
"text": "TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\\t”) with comma(“,”) as data in CSV file is comma-separated. "
},
{
"code": null,
"e": 24443,
"s": 24434,
"text": "Example:"
},
{
"code": null,
"e": 24455,
"s": 24443,
"text": "Input File:"
},
{
"code": null,
"e": 24463,
"s": 24455,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Python program to convert .tsv file to .csv file \n# importing re library \nimport re \n \n# reading given tsv file \nwith open(\"Olympic.tsv\", 'r') as myfile: \n with open(\"Olympic.csv\", 'w') as csv_file: \n for line in myfile: \n \n # Replace every tab with comma \n fileContent = re.sub(\"\\t\", \",\", line) \n \n # Writing into csv file \n csv_file.write(fileContent) \n \n# output \nprint(\"Successfully made csv file\")\n\n\n\n\n\n",
"e": 24933,
"s": 24473,
"text": null
},
{
"code": null,
"e": 24941,
"s": 24933,
"text": "Output:"
},
{
"code": null,
"e": 24968,
"s": 24941,
"text": "Successfully made csv file"
},
{
"code": null,
"e": 25440,
"s": 24968,
"text": "The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False."
},
{
"code": null,
"e": 25449,
"s": 25440,
"text": "Example:"
},
{
"code": null,
"e": 25461,
"s": 25449,
"text": "Input File:"
},
{
"code": null,
"e": 25469,
"s": 25461,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Python program to convert .tsv file to .csv file \n# importing pandas library \nimport pandas as pd \n \ntsv_file='GfG.tsv'\n \n# readinag given tsv file \ncsv_table=pd.read_table(tsv_file,sep='\\t') \n \n# converting tsv file into csv \ncsv_table.to_csv('GfG.csv',index=False) \n \n# output \nprint(\"Successfully made csv file\")\n\n\n\n\n\n",
"e": 25815,
"s": 25479,
"text": null
},
{
"code": null,
"e": 25823,
"s": 25815,
"text": "Output:"
},
{
"code": null,
"e": 25850,
"s": 25823,
"text": "Successfully made csv file"
},
{
"code": null,
"e": 25863,
"s": 25850,
"text": "Output File:"
},
{
"code": null,
"e": 25872,
"s": 25863,
"text": "\nPicked\n"
},
{
"code": null,
"e": 25885,
"s": 25872,
"text": "\nPython-TSV\n"
},
{
"code": null,
"e": 25894,
"s": 25885,
"text": "\nPython\n"
},
{
"code": null,
"e": 26099,
"s": 25894,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26131,
"s": 26099,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26187,
"s": 26131,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26229,
"s": 26187,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26271,
"s": 26229,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26307,
"s": 26271,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26329,
"s": 26307,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26368,
"s": 26329,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26395,
"s": 26368,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26426,
"s": 26395,
"text": "Python | os.path.join() method"
}
] |
Check if a large number is divisible by 2, 3 and 5 or not - GeeksforGeeks
|
21 May, 2021
Given a number, the task is to check if a number is divisible by 2, 3, and 5 or not. The input number may be large and it may not be possible to store even if we use long long int, so the number is taken as a string.Examples:
Input : str = "725"
Output : NO
Input : str = "263730746028908374890"
Output : YES
A number is divisible by 2 if it’s right most digit is even and also a number is divisible by 5 if it’s right most digit is zero or five.So, from above two observations, one can conclude that for the number to be divisible by both 2 and 5 the rightmost digit of the number must be zero.Now, a number is divisible by 3 if the sum of its digits is divisible by three.Therefore, a number will be divisible by all of 2, 3, and 5 if:
Its rightmost digit is zero.
Sum of all of its digits is divisible by 3.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to Check if a large number is// divisible by 2, 3 and 5 or not.#include <bits/stdc++.h>using namespace std; // function to return sum of digits of// a numberint SumOfDigits(string str, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (int)(str[i] - '0'); return sum;} // function to Check if a large number is// divisible by 2, 3 and 5 or notbool Divisible(string str, int n){ if (SumOfDigits(str, n) % 3 == 0 and str[n - 1] == '0') return true; return false;} // Driver codeint main(){ string str = "263730746028908374890"; int n = str.size(); if (Divisible(str, n)) cout << "YES"; else cout << "NO"; return 0;}
// Java program to Check if a large// number is divisible by 2, 3 and// 5 or not.class GFG{// function to return sum of// digits of a numberstatic int SumOfDigits(String str, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (int)(str.charAt(i) - '0'); return sum;} // function to Check if a large number// is divisible by 2, 3 and 5 or notstatic boolean Divisible(String str, int n){ if (SumOfDigits(str, n) % 3 == 0 && str.charAt(n - 1) == '0') return true; return false;} // Driver codepublic static void main(String []args){ String str = "263730746028908374890"; int n = str.length(); if (Divisible(str, n)) System.out.println("YES"); else System.out.println("NO");}} // This code is contributed by ihritik
# Python 3 program to Check if# a large number is# divisible by 2, 3 and 5 or not. # function to return sum of digits of# a numberdef SumOfDigits(str, n): sum = 0 for i in range(0,n): sum += int(ord(str[i] )- ord('0')) return sum # function to Check if a large number is# divisible by 2, 3 and 5 or notdef Divisible(str, n): if ((SumOfDigits(str, n) % 3 == 0 and str[n - 1] == '0')): return True return False # Driver codeif __name__ == "__main__": str = "263730746028908374890" n = len(str) if (Divisible(str, n)): print("YES") else: print("NO") # this code is contributed by# ChitraNayal
// C# program to Check if a large number// is divisible by 2, 3 and 5 or not.using System; class GFG{// function to return sum of digits// of a numberstatic int SumOfDigits(String str, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (int)(str[i] - '0'); return sum;} // function to Check if a large number// is divisible by 2, 3 and 5 or notstatic bool Divisible(String str, int n){ if (SumOfDigits(str, n) % 3 == 0 && str[n - 1] == '0') return true; return false;} // Driver codepublic static void Main(){ String str = "263730746028908374890"; int n = str.Length; if (Divisible(str, n)) Console.WriteLine("YES"); else Console.WriteLine("NO");}} // This code is contributed by ihritik
<?php// PHP program to Check if a large number// is divisible by 2, 3 and 5 or not. // function to return sum of digits// of a numberfunction SumOfDigits($str, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += (int)($str[$i] - '0'); return $sum;} // function to Check if a large number// is divisible by 2, 3 and 5 or notfunction Divisible($str, $n){ if (SumOfDigits($str, $n) % 3 == 0 and $str[$n - 1] == '0') return true; return false;} // Driver code$str = "263730746028908374890"; $n = strlen($str); if (Divisible($str, $n)) echo "YES";else echo "NO"; // This code is contributed// by Shivi_Aggarwal?>
<script> // JavaScript program to Check if a large// number is divisible by 2, 3 and// 5 or not. // Function to return sum of// digits of a numberfunction SumOfDigits(str, n){ var sum = 0; for(var i = 0; i < n; i++) sum += (str.charAt(i) - '0'); return sum;} // Function to Check if a large number// is divisible by 2, 3 and 5 or notfunction Divisible(str, n){ if (SumOfDigits(str, n) % 3 == 0 && str.charAt(n - 1) == '0') return true; return false;} // Driver codevar str = "263730746028908374890";var n = str.length; if (Divisible(str, n)) document.write("YES");else document.write("NO"); // This code is contributed by Ankita saini </script>
YES
ihritik
Shivi_Aggarwal
ukasp
ankita_saini
divisibility
large-numbers
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26709,
"s": 26681,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26937,
"s": 26709,
"text": "Given a number, the task is to check if a number is divisible by 2, 3, and 5 or not. The input number may be large and it may not be possible to store even if we use long long int, so the number is taken as a string.Examples: "
},
{
"code": null,
"e": 27022,
"s": 26937,
"text": "Input : str = \"725\" \nOutput : NO\n\nInput : str = \"263730746028908374890\"\nOutput : YES"
},
{
"code": null,
"e": 27455,
"s": 27024,
"text": "A number is divisible by 2 if it’s right most digit is even and also a number is divisible by 5 if it’s right most digit is zero or five.So, from above two observations, one can conclude that for the number to be divisible by both 2 and 5 the rightmost digit of the number must be zero.Now, a number is divisible by 3 if the sum of its digits is divisible by three.Therefore, a number will be divisible by all of 2, 3, and 5 if: "
},
{
"code": null,
"e": 27484,
"s": 27455,
"text": "Its rightmost digit is zero."
},
{
"code": null,
"e": 27528,
"s": 27484,
"text": "Sum of all of its digits is divisible by 3."
},
{
"code": null,
"e": 27581,
"s": 27528,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27585,
"s": 27581,
"text": "C++"
},
{
"code": null,
"e": 27590,
"s": 27585,
"text": "Java"
},
{
"code": null,
"e": 27599,
"s": 27590,
"text": "Python 3"
},
{
"code": null,
"e": 27602,
"s": 27599,
"text": "C#"
},
{
"code": null,
"e": 27606,
"s": 27602,
"text": "PHP"
},
{
"code": null,
"e": 27617,
"s": 27606,
"text": "Javascript"
},
{
"code": "// CPP program to Check if a large number is// divisible by 2, 3 and 5 or not.#include <bits/stdc++.h>using namespace std; // function to return sum of digits of// a numberint SumOfDigits(string str, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (int)(str[i] - '0'); return sum;} // function to Check if a large number is// divisible by 2, 3 and 5 or notbool Divisible(string str, int n){ if (SumOfDigits(str, n) % 3 == 0 and str[n - 1] == '0') return true; return false;} // Driver codeint main(){ string str = \"263730746028908374890\"; int n = str.size(); if (Divisible(str, n)) cout << \"YES\"; else cout << \"NO\"; return 0;}",
"e": 28316,
"s": 27617,
"text": null
},
{
"code": "// Java program to Check if a large// number is divisible by 2, 3 and// 5 or not.class GFG{// function to return sum of// digits of a numberstatic int SumOfDigits(String str, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (int)(str.charAt(i) - '0'); return sum;} // function to Check if a large number// is divisible by 2, 3 and 5 or notstatic boolean Divisible(String str, int n){ if (SumOfDigits(str, n) % 3 == 0 && str.charAt(n - 1) == '0') return true; return false;} // Driver codepublic static void main(String []args){ String str = \"263730746028908374890\"; int n = str.length(); if (Divisible(str, n)) System.out.println(\"YES\"); else System.out.println(\"NO\");}} // This code is contributed by ihritik",
"e": 29146,
"s": 28316,
"text": null
},
{
"code": "# Python 3 program to Check if# a large number is# divisible by 2, 3 and 5 or not. # function to return sum of digits of# a numberdef SumOfDigits(str, n): sum = 0 for i in range(0,n): sum += int(ord(str[i] )- ord('0')) return sum # function to Check if a large number is# divisible by 2, 3 and 5 or notdef Divisible(str, n): if ((SumOfDigits(str, n) % 3 == 0 and str[n - 1] == '0')): return True return False # Driver codeif __name__ == \"__main__\": str = \"263730746028908374890\" n = len(str) if (Divisible(str, n)): print(\"YES\") else: print(\"NO\") # this code is contributed by# ChitraNayal",
"e": 29815,
"s": 29146,
"text": null
},
{
"code": "// C# program to Check if a large number// is divisible by 2, 3 and 5 or not.using System; class GFG{// function to return sum of digits// of a numberstatic int SumOfDigits(String str, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (int)(str[i] - '0'); return sum;} // function to Check if a large number// is divisible by 2, 3 and 5 or notstatic bool Divisible(String str, int n){ if (SumOfDigits(str, n) % 3 == 0 && str[n - 1] == '0') return true; return false;} // Driver codepublic static void Main(){ String str = \"263730746028908374890\"; int n = str.Length; if (Divisible(str, n)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");}} // This code is contributed by ihritik",
"e": 30609,
"s": 29815,
"text": null
},
{
"code": "<?php// PHP program to Check if a large number// is divisible by 2, 3 and 5 or not. // function to return sum of digits// of a numberfunction SumOfDigits($str, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += (int)($str[$i] - '0'); return $sum;} // function to Check if a large number// is divisible by 2, 3 and 5 or notfunction Divisible($str, $n){ if (SumOfDigits($str, $n) % 3 == 0 and $str[$n - 1] == '0') return true; return false;} // Driver code$str = \"263730746028908374890\"; $n = strlen($str); if (Divisible($str, $n)) echo \"YES\";else echo \"NO\"; // This code is contributed// by Shivi_Aggarwal?>",
"e": 31273,
"s": 30609,
"text": null
},
{
"code": "<script> // JavaScript program to Check if a large// number is divisible by 2, 3 and// 5 or not. // Function to return sum of// digits of a numberfunction SumOfDigits(str, n){ var sum = 0; for(var i = 0; i < n; i++) sum += (str.charAt(i) - '0'); return sum;} // Function to Check if a large number// is divisible by 2, 3 and 5 or notfunction Divisible(str, n){ if (SumOfDigits(str, n) % 3 == 0 && str.charAt(n - 1) == '0') return true; return false;} // Driver codevar str = \"263730746028908374890\";var n = str.length; if (Divisible(str, n)) document.write(\"YES\");else document.write(\"NO\"); // This code is contributed by Ankita saini </script>",
"e": 31963,
"s": 31273,
"text": null
},
{
"code": null,
"e": 31967,
"s": 31963,
"text": "YES"
},
{
"code": null,
"e": 31977,
"s": 31969,
"text": "ihritik"
},
{
"code": null,
"e": 31992,
"s": 31977,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 31998,
"s": 31992,
"text": "ukasp"
},
{
"code": null,
"e": 32011,
"s": 31998,
"text": "ankita_saini"
},
{
"code": null,
"e": 32024,
"s": 32011,
"text": "divisibility"
},
{
"code": null,
"e": 32038,
"s": 32024,
"text": "large-numbers"
},
{
"code": null,
"e": 32062,
"s": 32038,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32075,
"s": 32062,
"text": "Mathematical"
},
{
"code": null,
"e": 32088,
"s": 32075,
"text": "Mathematical"
},
{
"code": null,
"e": 32186,
"s": 32088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32264,
"s": 32186,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 32293,
"s": 32264,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 32320,
"s": 32293,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 32358,
"s": 32320,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 32417,
"s": 32358,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 32447,
"s": 32417,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32507,
"s": 32447,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32522,
"s": 32507,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32565,
"s": 32522,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Introduction to Keyloggers - GeeksforGeeks
|
20 May, 2020
Key loggers also known as keystroke loggers, may be defined as the recording of the key pressed on a system and saved it to a file, and the that file is accessed by the person using this malware. Key logger can be software or can be hardware.
Working:Mainly key-loggers are used to steal password or confidential details such as bank information etc. First key-logger was invented in 1970’s and was a hardware key logger and first software key-logger was developed in 1983.
1. Software key-loggers :Software key-loggers are the computer programs which are developed to steal password from the victims computer. However key loggers are used in IT organizations to troubleshoot technical problems with computers and business networks. Also Microsoft windows 10 also has key-logger installed in it.
JavaScript based key logger –It is a malicious script which is installed into a web page, and listens for key to press such as oneKeyUp(). These scripts can be sent by various methods, like sharing through social media, sending as a mail file, or RAT file.Form Based Key loggers –These are key-loggers which activates when a person fills a form online and when click the button submit all the data or the words written is sent via file on a computer. Some key-loggers works as a API in running application it looks like a simple application and whenever a key is pressed it records it.
JavaScript based key logger –It is a malicious script which is installed into a web page, and listens for key to press such as oneKeyUp(). These scripts can be sent by various methods, like sharing through social media, sending as a mail file, or RAT file.
Form Based Key loggers –These are key-loggers which activates when a person fills a form online and when click the button submit all the data or the words written is sent via file on a computer. Some key-loggers works as a API in running application it looks like a simple application and whenever a key is pressed it records it.
2. Hardware Key-loggers :These are not dependent on any software as these are hardware key-loggers. keyboard hardware is a circuit which is attached in a keyboard itself that whenever the key of that keyboard pressed it gets recorded.
USB keylogger –There are USB connector key-loggers which has to be connected to a computer and steals the data. Also some circuits are built into a keyboard so no external wire i used or shows on the keyboard.Smartphone sensors –Some cool android tricks are also used as key loggers such as android accelerometer sensor which when placed near to the keyboard can sense the vibrations and the graph then used to convert it to sentences, this technique accuracy is about 80%.Now a days crackers are using keystroke logging Trojan, it is a malware which is sent to a victims computer to steal the data and login details.
USB keylogger –There are USB connector key-loggers which has to be connected to a computer and steals the data. Also some circuits are built into a keyboard so no external wire i used or shows on the keyboard.
Smartphone sensors –Some cool android tricks are also used as key loggers such as android accelerometer sensor which when placed near to the keyboard can sense the vibrations and the graph then used to convert it to sentences, this technique accuracy is about 80%.Now a days crackers are using keystroke logging Trojan, it is a malware which is sent to a victims computer to steal the data and login details.
Now a days crackers are using keystroke logging Trojan, it is a malware which is sent to a victims computer to steal the data and login details.
So key-loggers are the software malware or a hardware which is used to steal , or snatch our login details, credentials , bank information and many more.
Some keylogger application used in 2020 are:
1. Kidlogger
2. Best Free Keylogger
3. Windows Keylogger
4. Refog Personal Monitor
5. All In One Keylogger
Prevention from key-loggers :These are following below-
Anti-Key-logger –As the name suggest these are the software which are anti / against key loggers and main task is to detect key-logger from a computer system.Anti-Virus –Many anti-virus software also detect key loggers and delete them from the computer system. These are software anti-software so these can not get rid from the hardware key-loggers.Automatic form filler –This technique can be used by the user to not fill forms on regular bases instead use automatic form filler which will give a shield against key-loggers as keys will not be pressed .One-Time-Passwords –Using OTP’s as password may be safe as every time we login we have to use a new password.Patterns or mouse-recognition –On android devices used pattern as a password of applications and on PC use mouse recognition, mouse program uses mouse gestures instead of stylus.
Anti-Key-logger –As the name suggest these are the software which are anti / against key loggers and main task is to detect key-logger from a computer system.
Anti-Virus –Many anti-virus software also detect key loggers and delete them from the computer system. These are software anti-software so these can not get rid from the hardware key-loggers.
Automatic form filler –This technique can be used by the user to not fill forms on regular bases instead use automatic form filler which will give a shield against key-loggers as keys will not be pressed .
One-Time-Passwords –Using OTP’s as password may be safe as every time we login we have to use a new password.
Patterns or mouse-recognition –On android devices used pattern as a password of applications and on PC use mouse recognition, mouse program uses mouse gestures instead of stylus.
These techniques are less common but are very helpful against key-loggers.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Multiple Access Protocols in Computer Network
Congestion Control in Computer Networks
Routing Information Protocol (RIP)
Architecture of Internet of Things (IoT)
Wireless Sensor Network (WSN)
|
[
{
"code": null,
"e": 25780,
"s": 25752,
"text": "\n20 May, 2020"
},
{
"code": null,
"e": 26023,
"s": 25780,
"text": "Key loggers also known as keystroke loggers, may be defined as the recording of the key pressed on a system and saved it to a file, and the that file is accessed by the person using this malware. Key logger can be software or can be hardware."
},
{
"code": null,
"e": 26254,
"s": 26023,
"text": "Working:Mainly key-loggers are used to steal password or confidential details such as bank information etc. First key-logger was invented in 1970’s and was a hardware key logger and first software key-logger was developed in 1983."
},
{
"code": null,
"e": 26576,
"s": 26254,
"text": "1. Software key-loggers :Software key-loggers are the computer programs which are developed to steal password from the victims computer. However key loggers are used in IT organizations to troubleshoot technical problems with computers and business networks. Also Microsoft windows 10 also has key-logger installed in it."
},
{
"code": null,
"e": 27162,
"s": 26576,
"text": "JavaScript based key logger –It is a malicious script which is installed into a web page, and listens for key to press such as oneKeyUp(). These scripts can be sent by various methods, like sharing through social media, sending as a mail file, or RAT file.Form Based Key loggers –These are key-loggers which activates when a person fills a form online and when click the button submit all the data or the words written is sent via file on a computer. Some key-loggers works as a API in running application it looks like a simple application and whenever a key is pressed it records it."
},
{
"code": null,
"e": 27419,
"s": 27162,
"text": "JavaScript based key logger –It is a malicious script which is installed into a web page, and listens for key to press such as oneKeyUp(). These scripts can be sent by various methods, like sharing through social media, sending as a mail file, or RAT file."
},
{
"code": null,
"e": 27749,
"s": 27419,
"text": "Form Based Key loggers –These are key-loggers which activates when a person fills a form online and when click the button submit all the data or the words written is sent via file on a computer. Some key-loggers works as a API in running application it looks like a simple application and whenever a key is pressed it records it."
},
{
"code": null,
"e": 27984,
"s": 27749,
"text": "2. Hardware Key-loggers :These are not dependent on any software as these are hardware key-loggers. keyboard hardware is a circuit which is attached in a keyboard itself that whenever the key of that keyboard pressed it gets recorded."
},
{
"code": null,
"e": 28602,
"s": 27984,
"text": "USB keylogger –There are USB connector key-loggers which has to be connected to a computer and steals the data. Also some circuits are built into a keyboard so no external wire i used or shows on the keyboard.Smartphone sensors –Some cool android tricks are also used as key loggers such as android accelerometer sensor which when placed near to the keyboard can sense the vibrations and the graph then used to convert it to sentences, this technique accuracy is about 80%.Now a days crackers are using keystroke logging Trojan, it is a malware which is sent to a victims computer to steal the data and login details."
},
{
"code": null,
"e": 28812,
"s": 28602,
"text": "USB keylogger –There are USB connector key-loggers which has to be connected to a computer and steals the data. Also some circuits are built into a keyboard so no external wire i used or shows on the keyboard."
},
{
"code": null,
"e": 29221,
"s": 28812,
"text": "Smartphone sensors –Some cool android tricks are also used as key loggers such as android accelerometer sensor which when placed near to the keyboard can sense the vibrations and the graph then used to convert it to sentences, this technique accuracy is about 80%.Now a days crackers are using keystroke logging Trojan, it is a malware which is sent to a victims computer to steal the data and login details."
},
{
"code": null,
"e": 29366,
"s": 29221,
"text": "Now a days crackers are using keystroke logging Trojan, it is a malware which is sent to a victims computer to steal the data and login details."
},
{
"code": null,
"e": 29520,
"s": 29366,
"text": "So key-loggers are the software malware or a hardware which is used to steal , or snatch our login details, credentials , bank information and many more."
},
{
"code": null,
"e": 29565,
"s": 29520,
"text": "Some keylogger application used in 2020 are:"
},
{
"code": null,
"e": 29673,
"s": 29565,
"text": "1. Kidlogger\n2. Best Free Keylogger\n3. Windows Keylogger\n4. Refog Personal Monitor\n5. All In One Keylogger "
},
{
"code": null,
"e": 29729,
"s": 29673,
"text": "Prevention from key-loggers :These are following below-"
},
{
"code": null,
"e": 30571,
"s": 29729,
"text": "Anti-Key-logger –As the name suggest these are the software which are anti / against key loggers and main task is to detect key-logger from a computer system.Anti-Virus –Many anti-virus software also detect key loggers and delete them from the computer system. These are software anti-software so these can not get rid from the hardware key-loggers.Automatic form filler –This technique can be used by the user to not fill forms on regular bases instead use automatic form filler which will give a shield against key-loggers as keys will not be pressed .One-Time-Passwords –Using OTP’s as password may be safe as every time we login we have to use a new password.Patterns or mouse-recognition –On android devices used pattern as a password of applications and on PC use mouse recognition, mouse program uses mouse gestures instead of stylus."
},
{
"code": null,
"e": 30730,
"s": 30571,
"text": "Anti-Key-logger –As the name suggest these are the software which are anti / against key loggers and main task is to detect key-logger from a computer system."
},
{
"code": null,
"e": 30922,
"s": 30730,
"text": "Anti-Virus –Many anti-virus software also detect key loggers and delete them from the computer system. These are software anti-software so these can not get rid from the hardware key-loggers."
},
{
"code": null,
"e": 31128,
"s": 30922,
"text": "Automatic form filler –This technique can be used by the user to not fill forms on regular bases instead use automatic form filler which will give a shield against key-loggers as keys will not be pressed ."
},
{
"code": null,
"e": 31238,
"s": 31128,
"text": "One-Time-Passwords –Using OTP’s as password may be safe as every time we login we have to use a new password."
},
{
"code": null,
"e": 31417,
"s": 31238,
"text": "Patterns or mouse-recognition –On android devices used pattern as a password of applications and on PC use mouse recognition, mouse program uses mouse gestures instead of stylus."
},
{
"code": null,
"e": 31492,
"s": 31417,
"text": "These techniques are less common but are very helpful against key-loggers."
},
{
"code": null,
"e": 31510,
"s": 31492,
"text": "Computer Networks"
},
{
"code": null,
"e": 31528,
"s": 31510,
"text": "Computer Networks"
},
{
"code": null,
"e": 31626,
"s": 31528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31661,
"s": 31626,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 31694,
"s": 31661,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 31732,
"s": 31694,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 31758,
"s": 31732,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 31785,
"s": 31758,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 31831,
"s": 31785,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 31871,
"s": 31831,
"text": "Congestion Control in Computer Networks"
},
{
"code": null,
"e": 31906,
"s": 31871,
"text": "Routing Information Protocol (RIP)"
},
{
"code": null,
"e": 31947,
"s": 31906,
"text": "Architecture of Internet of Things (IoT)"
}
] |
Python | Mean Squared Error - GeeksforGeeks
|
30 Jun, 2019
The Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator measures the average of error squares i.e. the average squared difference between the estimated values and true value. It is a risk function, corresponding to the expected value of the squared error loss. It is always non – negative and values close to zero are better. The MSE is the second moment of the error (about the origin) and thus incorporates both the variance of the estimator and its bias.
Steps to find the MSE
Find the equation for the regression line.(1) Insert X values in the equation found in step 1 in order to get the respective Y values i.e.(2) Now subtract the new Y values (i.e. ) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.(3) Square the errors found in step 3.(4) Sum up all the squares.(5) Divide the value found in step 5 by the total number of observations.(6)
Find the equation for the regression line.(1)
(1)
Insert X values in the equation found in step 1 in order to get the respective Y values i.e.(2)
(2)
Now subtract the new Y values (i.e. ) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.(3)
(3)
Square the errors found in step 3.(4)
(4)
Sum up all the squares.(5)
(5)
Divide the value found in step 5 by the total number of observations.(6)
(6)
Example:Consider the given data points: (1,1), (2,1), (3,2), (4,2), (5,4)You can use this online calculator to find the regression equation / line.
Regression line equation: Y = 0.7X – 0.1
Now, using formula found for MSE in step 6 above, we can get MSE = 0.21606
MSE using scikit – learn:
from sklearn.metrics import mean_squared_error # Given valuesY_true = [1,1,2,2,4] # Y_true = Y (original values) # calculated valuesY_pred = [0.6,1.29,1.99,2.69,3.4] # Y_pred = Y' # Calculation of Mean Squared Error (MSE)mean_squared_error(Y_true,Y_pred)
Output: 0.21606
MSE using Numpy module:
import numpy as np # Given valuesY_true = [1,1,2,2,4] # Y_true = Y (original values) # Calculated valuesY_pred = [0.6,1.29,1.99,2.69,3.4] # Y_pred = Y' # Mean Squared ErrorMSE = np.square(np.subtract(Y_true,Y_pred)).mean()
Output: 0.21606
Advanced Computer Subject
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25815,
"s": 25787,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 26294,
"s": 25815,
"text": "The Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator measures the average of error squares i.e. the average squared difference between the estimated values and true value. It is a risk function, corresponding to the expected value of the squared error loss. It is always non – negative and values close to zero are better. The MSE is the second moment of the error (about the origin) and thus incorporates both the variance of the estimator and its bias."
},
{
"code": null,
"e": 26316,
"s": 26294,
"text": "Steps to find the MSE"
},
{
"code": null,
"e": 26805,
"s": 26316,
"text": "Find the equation for the regression line.(1) Insert X values in the equation found in step 1 in order to get the respective Y values i.e.(2) Now subtract the new Y values (i.e. ) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.(3) Square the errors found in step 3.(4) Sum up all the squares.(5) Divide the value found in step 5 by the total number of observations.(6) "
},
{
"code": null,
"e": 26854,
"s": 26805,
"text": "Find the equation for the regression line.(1) "
},
{
"code": null,
"e": 26861,
"s": 26854,
"text": "(1) "
},
{
"code": null,
"e": 26960,
"s": 26861,
"text": "Insert X values in the equation found in step 1 in order to get the respective Y values i.e.(2) "
},
{
"code": null,
"e": 26967,
"s": 26960,
"text": "(2) "
},
{
"code": null,
"e": 27166,
"s": 26967,
"text": "Now subtract the new Y values (i.e. ) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.(3) "
},
{
"code": null,
"e": 27173,
"s": 27166,
"text": "(3) "
},
{
"code": null,
"e": 27214,
"s": 27173,
"text": "Square the errors found in step 3.(4) "
},
{
"code": null,
"e": 27221,
"s": 27214,
"text": "(4) "
},
{
"code": null,
"e": 27251,
"s": 27221,
"text": "Sum up all the squares.(5) "
},
{
"code": null,
"e": 27258,
"s": 27251,
"text": "(5) "
},
{
"code": null,
"e": 27334,
"s": 27258,
"text": "Divide the value found in step 5 by the total number of observations.(6) "
},
{
"code": null,
"e": 27341,
"s": 27334,
"text": "(6) "
},
{
"code": null,
"e": 27489,
"s": 27341,
"text": "Example:Consider the given data points: (1,1), (2,1), (3,2), (4,2), (5,4)You can use this online calculator to find the regression equation / line."
},
{
"code": null,
"e": 27530,
"s": 27489,
"text": "Regression line equation: Y = 0.7X – 0.1"
},
{
"code": null,
"e": 27605,
"s": 27530,
"text": "Now, using formula found for MSE in step 6 above, we can get MSE = 0.21606"
},
{
"code": null,
"e": 27631,
"s": 27605,
"text": "MSE using scikit – learn:"
},
{
"code": "from sklearn.metrics import mean_squared_error # Given valuesY_true = [1,1,2,2,4] # Y_true = Y (original values) # calculated valuesY_pred = [0.6,1.29,1.99,2.69,3.4] # Y_pred = Y' # Calculation of Mean Squared Error (MSE)mean_squared_error(Y_true,Y_pred)",
"e": 27891,
"s": 27631,
"text": null
},
{
"code": null,
"e": 27907,
"s": 27891,
"text": "Output: 0.21606"
},
{
"code": null,
"e": 27931,
"s": 27907,
"text": "MSE using Numpy module:"
},
{
"code": "import numpy as np # Given valuesY_true = [1,1,2,2,4] # Y_true = Y (original values) # Calculated valuesY_pred = [0.6,1.29,1.99,2.69,3.4] # Y_pred = Y' # Mean Squared ErrorMSE = np.square(np.subtract(Y_true,Y_pred)).mean()",
"e": 28159,
"s": 27931,
"text": null
},
{
"code": null,
"e": 28175,
"s": 28159,
"text": "Output: 0.21606"
},
{
"code": null,
"e": 28201,
"s": 28175,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 28208,
"s": 28201,
"text": "Python"
},
{
"code": null,
"e": 28224,
"s": 28208,
"text": "Python Programs"
},
{
"code": null,
"e": 28322,
"s": 28224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28345,
"s": 28322,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 28383,
"s": 28345,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28427,
"s": 28383,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 28461,
"s": 28427,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 28492,
"s": 28461,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 28520,
"s": 28492,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28570,
"s": 28520,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28592,
"s": 28570,
"text": "Python map() function"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.