title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Difference between Iterator and Enumeration in Java
Iterator and Enumeration both are the cursors to traverse and access an element from the collection. They both belong to the collection framework. Enumeration was added in JDK1.0 and Iterator in the JDK.1.2 version in the collection framework. Enumeration can’t make structural changes in the collection because it has read-only access to the element in the collection. It has the following methods : *hasMoreElements() *nextElement() On the other hand, an iterator can read and remove the element in the collection. It has the following methods − *hasNext() *next() *remove() class EnumerationExample { public static void main(String args[]) { List list = new ArrayList(Arrays.asList( new String[] {"Apple", "Cat", "Dog", "Rat"})); Vector v = new Vector(list); delete(v, "Dog"); } private static void delete(Vector v, String name) { Enumeration e = v.elements(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equals(name)) { v.remove(name); } } // Display the names System.out.println("The names are:"); e = v.elements(); while (e.hasMoreElements()) { // Prints elements System.out.println(e.nextElement()); } } } class IteratorExample { public static void main(String args[]) { List list = new ArrayList(Arrays.asList( new String[] {"Apple", "Cat", "Dog", "Rat"})); Vector v = new Vector(list); delete(v, "Dog"); } private static void delete(Vector v, String name) { Iterator i = v.iterator(); while (i.hasNext()) { String s = (String) i.next(); if (s.equals(name)) { i.remove(); } } // Display the names System.out.println("The names are:"); i = v.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
[ { "code": null, "e": 1307, "s": 1062, "text": "Iterator and Enumeration both are the cursors to traverse and access an element from the collection. They both belong to the collection framework. Enumeration was added in JDK1.0 and Iterator in the JDK.1.2 version in the collection framework. " }, { "code": null, "e": 1464, "s": 1307, "text": "Enumeration can’t make structural changes in the collection because it has read-only access to the element in the collection. It has the following methods :" }, { "code": null, "e": 1483, "s": 1464, "text": "*hasMoreElements()" }, { "code": null, "e": 1498, "s": 1483, "text": "*nextElement()" }, { "code": null, "e": 1611, "s": 1498, "text": "On the other hand, an iterator can read and remove the element in the collection. It has the following methods −" }, { "code": null, "e": 1622, "s": 1611, "text": "*hasNext()" }, { "code": null, "e": 1630, "s": 1622, "text": "*next()" }, { "code": null, "e": 1640, "s": 1630, "text": "*remove()" }, { "code": null, "e": 2340, "s": 1640, "text": "class EnumerationExample {\n public static void main(String args[]) {\n List list = new ArrayList(Arrays.asList( new String[] {\"Apple\", \"Cat\", \"Dog\", \"Rat\"}));\n Vector v = new Vector(list);\n delete(v, \"Dog\");\n }\n private static void delete(Vector v, String name) {\n Enumeration e = v.elements();\n while (e.hasMoreElements()) {\n String s = (String) e.nextElement();\n if (s.equals(name)) {\n v.remove(name);\n }\n }\n // Display the names\n System.out.println(\"The names are:\");\n e = v.elements();\n while (e.hasMoreElements()) {\n // Prints elements\n System.out.println(e.nextElement());\n }\n }\n}" }, { "code": null, "e": 2972, "s": 2340, "text": "class IteratorExample {\n public static void main(String args[]) {\n List list = new ArrayList(Arrays.asList( new String[] {\"Apple\", \"Cat\", \"Dog\", \"Rat\"}));\n Vector v = new Vector(list);\n delete(v, \"Dog\");\n }\n private static void delete(Vector v, String name) {\n Iterator i = v.iterator();\n while (i.hasNext()) {\n String s = (String) i.next();\n if (s.equals(name)) {\n i.remove();\n }\n }\n // Display the names\n System.out.println(\"The names are:\");\n i = v.iterator();\n while (i.hasNext()) {\n System.out.println(i.next());\n }\n }\n}" } ]
Organizing Your First Text Analytics Project | by Sakshi Gupta | Towards Data Science
Using Natural Language tools to uncover conversational data. Text analytics or text mining is the analysis of “unstructured” data contained in natural language text using various methods, tools and techniques. The popularity of text mining today is driven by statistics and the availability of unstructured data. With the growing popularity of social media and with the internet as a central location for all sorts of important conversations, text mining offers a low-cost method to gauge public opinion. This was my inspiration to learn about text analytics and write this blog and share my learnings with my fellow data scientists! My key reference for this blog is DataCamp’s beautifully designed course Text Mining — Bag of Words. Below are the six main steps for a text mining project. In this blog, I will focus on Steps 3, 4, 5 and 6 and discuss the key packages and functions in R which can be used for these steps. Identifying the specific goals or objectives for any project is key to its success. One needs to have domain understanding to define the problem statement appropriately. For this article, I will be asking whether Amazon or Google has a better pay perception according to online reviews, and which has a better work-life balance according to current employee reviews. There can be multiple ways to collect employees reviews, from websites like Glassdoor and Indeed to articles published with workplace reviews, or even through focus group interviews of employees. This involves the multiple steps for cleaning and pre-processing your text. There are two main packages in R which can be used to perform this: qdap and tm. Points to Remember: the tm package works on the text corpus object the qdap package is applied directly to the text vector x -> vector with positive reviews for Amazon # qdap cleaning function> qdap_clean <- function(x) { x <- replace_abbreviations(x) x <- replace_contractions(x) x <- replace_number(x) x <- replace_ordinal(x) x <- replace_symbol(x) x <- tolower(x) return(x)} **You can also add more cleaning functions to the above, based on specific requirements. corpus -> VCorpus(VectorSource(x)) Then use the tm_map() function — provided by the tm package — to apply cleaning functions to a corpus. Mapping these functions to an entire corpus makes scaling of the cleaning steps very easy. # tm cleaning function> clean_corpus <- function(corpus){ corpus <- tm_map(corpus, stripWhitespace) corpus <- tm_map(corpus, removePunctuation) corpus <- tm_map(corpus, content_transformer(tolower)) corpus <- tm_map(corpus, removeWords, c(stopwords("en"), "Google", "Amazon", "company)) return(corpus)} Word stemming and stem completion on a sentence using tm package The tm package provides the stemDocument() function to get to a word’s root. This function either takes in a character vector and returns a character vector, or takes in a PlainTextDocument and returns a PlainTextDocument. # Remove punctuation> rm_punc <- removePunctuation(text_data)# Create character vector> n_char_vec <- unlist(strsplit(rm_punc, split = ' '))# Perform word stemming: stem_doc> stem_doc <- stemDocument(n_char_vec)# Re-complete stemmed document: complete_doc> complete_doc <- stemCompletion(stem_doc, comp_dict) Point to remember: Define your own comp_dict which is a custom dictionary containing words you want to use to re-complete the stemmed words. After completing the basic cleaning and pre-processing of text, the next step is to extract the key features which can be done in the form of sentiment scoring or extracting n-grams and plotting them. For this purpose, the TermDocumentMatrix (TDM) or DocumentTerm Matrix (DTM) functions come in very handy. # Generate TDM> coffee_tdm <- TermDocumentMatrix(clean_corp)# Generate DTM> coffee_dtm <- DocumentTermMatrix(clean_corp) Points to remember: You can use TDM when you have more words than documents to be reviewed, as it is easier to read a large number of rows than columns. You can then convert the results to matrices using the as.matrix() function, and then slice and dice and review parts of these matrices. Let’s see a simple example of creating a TDM for bigrams: To create a bigrams TDM, we use TermDocumentMatrix() along with a control argument which receives a list of control functions (please refer to TermDocumentMatrix for more details). Here, a built-in function called tokenizer is used, which helps in tokenizing words as bigrams. # Create bigram TDM> amzn_p_tdm <- TermDocumentMatrix(amzn_pros_corp,control = list(tokenize = tokenizer))# Create amzn_p_tdm_m> amzn_p_tdm_m <- as.matrix(amzn_p_tdm) # Create amzn_p_freq > amzn_p_freq <- rowSums(amzn_p_tdm_m) There are multiple ways to analyze the text features. A few of them are discussed below. # Sort term_frequency in descending order> amzn_p_freq <- sort(amzn_p_freq, decreasing = TRUE) > # Plot a barchart of the 10 most common words> barplot(amzn_p_freq[1:10], col = "tan", las = 2) # Plot a wordcloud using amzn_p_freq values> wordcloud(names(amzn_p_freq), amzn_p_freq, max.words = 25, color = "red") To further learn different ways to plot wordcloud, please refer to this article which I found quite useful. c. Cluster Dendograms This is a simple clustering technique to perform a hierarchical cluster and create a dendrogram to see how connected different phrases are. # Create amzn_p_tdm2 by removing sparse terms> amzn_p_tdm2 <- removeSparseTerms(amzn_p_tdm, sparse = .993) > # Create hc as a cluster of distance values> hc <- hclust(dist(amzn_p_tdm2, method = "euclidean"), method = "complete") > # Produce a plot of hc> plot(hc) You can see similar topics throughout the dendrogram like “great benefits,” “good pay,” “smart people,” etc. d. Word Association This is used to examine top phrases that appear in the word clouds and find associated terms using the findAssocs() function from the tm package. The code below is used to find the most associated words with the most frequent terms in the positive reviews for Amazon. # Find associations with Top 2 most frequent words> findAssocs(amzn_p_tdm, "great benefits", 0.2) $`great benefits` stock options options four four hundred vacation time 0.35 0.28 0.27 0.26 benefits stock competitive pay great management time vacation 0.22 0.22 0.22 0.22> findAssocs(amzn_p_tdm, "good pay", 0.2) $`good pay` pay benefits pay good good people work nice 0.31 0.23 0.22 0.22 e. Comparison Clouds This is used when you wish to examine two different corpuses of words in one go, rather then analyzing them separately (which can be more time consuming). The code below compares the positive and negative reviews for Google. # Create all_goog_corp> all_goog_corp <- tm_clean(all_goog_corpus) > # Create all_tdm> all_tdm <- TermDocumentMatrix(all_goog_corp)<>Non-/sparse entries: 2845/1713Sparsity : 38%Maximal term length: 27Weighting : term frequency (tf)> # Name the columns of all_tdm> colnames(all_tdm) <- c("Goog_Pros", "Goog_Cons") > # Create all_m> all_m <- as.matrix(all_tdm) > # Build a comparison cloud> comparison.cloud(all_m, colors = c("#F44336", "#2196f3"), max.words = 100) f. Pyramid Plots Pyramid plots are used to display a pyramid (as opposed to a horizontal bar) plot and help in easy comparison based on similar phrases. The code below compares the frequency of positive phrases for Amazon vs Google. # Create common_words> common_words <- subset(all_tdm_m, all_tdm_m[,1] > 0 & all_tdm_m[,2] > 0)> str(common_words) num [1:269, 1:2] 1 1 1 1 1 3 2 2 1 1 ... - attr(*, "dimnames")=List of 2 ..$ Terms: chr [1:269] "able work" "actual work" "area traffic" "atmosphere little" ... ..$ Docs : chr [1:2] "Amazon Pro" "Google Pro"# Create difference> difference <- abs(common_words[,1]- common_words[,2]) ># Add difference to common_words> common_words <- cbind(common_words, difference) > head(common_words) Amazon Pro Google Pro difference able work 1 1 0 actual work 1 1 0 area traffic 1 1 0 atmosphere little 1 1 0 back forth 1 1 0 bad work 3 1 2# Order the data frame from most differences to least> common_words <- common_words[order(common_words[,"difference"],decreasing = TRUE),]# Create top15_df> top15_df <- data.frame(x = common_words[1:15,1], y = common_words[1:15,2], labels = rownames(common_words[1:15,]))# Create the pyramid plot> pyramid.plot(top15_df$x, top15_df$y, labels = top15_df$labels, gap = 12, top.labels = c("Amzn", "Pro Words", "Google"), main = "Words in Common", unit = NULL) [1] 5.1 4.1 4.1 2.1 Based on the above visual (“Words in Common” pyramid plot), overall Amazon looks to have a better work environment and work-life balance than Google. Working hours seem to be higher at Amazon, but perhaps they provide other benefits to restore the work-life balance. We would need to collect more reviews to make a better conclusion. So, finally we come to the end of this blog. We learned how to organize our text analytics project, the different steps involved in cleaning and pre-processing and finally how to visualize the features and draw conclusions. I am on my way to completing my text analytics project based on this blog and learnings from DataCamp. I will soon post my GitHub repository for the project to help you further. Our next goal should be to perform sentiment analysis. Till then keep CODING!! Hope you liked this blog. Do share your comments on what you liked and what you would like me to improve in my next blog. Keep watching this space for more. Cheers! (First published @www.datacritics.com)
[ { "code": null, "e": 232, "s": 171, "text": "Using Natural Language tools to uncover conversational data." }, { "code": null, "e": 381, "s": 232, "text": "Text analytics or text mining is the analysis of “unstructured” data contained in natural language text using various methods, tools and techniques." }, { "code": null, "e": 676, "s": 381, "text": "The popularity of text mining today is driven by statistics and the availability of unstructured data. With the growing popularity of social media and with the internet as a central location for all sorts of important conversations, text mining offers a low-cost method to gauge public opinion." }, { "code": null, "e": 805, "s": 676, "text": "This was my inspiration to learn about text analytics and write this blog and share my learnings with my fellow data scientists!" }, { "code": null, "e": 906, "s": 805, "text": "My key reference for this blog is DataCamp’s beautifully designed course Text Mining — Bag of Words." }, { "code": null, "e": 1095, "s": 906, "text": "Below are the six main steps for a text mining project. In this blog, I will focus on Steps 3, 4, 5 and 6 and discuss the key packages and functions in R which can be used for these steps." }, { "code": null, "e": 1265, "s": 1095, "text": "Identifying the specific goals or objectives for any project is key to its success. One needs to have domain understanding to define the problem statement appropriately." }, { "code": null, "e": 1462, "s": 1265, "text": "For this article, I will be asking whether Amazon or Google has a better pay perception according to online reviews, and which has a better work-life balance according to current employee reviews." }, { "code": null, "e": 1658, "s": 1462, "text": "There can be multiple ways to collect employees reviews, from websites like Glassdoor and Indeed to articles published with workplace reviews, or even through focus group interviews of employees." }, { "code": null, "e": 1815, "s": 1658, "text": "This involves the multiple steps for cleaning and pre-processing your text. There are two main packages in R which can be used to perform this: qdap and tm." }, { "code": null, "e": 1835, "s": 1815, "text": "Points to Remember:" }, { "code": null, "e": 1882, "s": 1835, "text": "the tm package works on the text corpus object" }, { "code": null, "e": 1938, "s": 1882, "text": "the qdap package is applied directly to the text vector" }, { "code": null, "e": 1983, "s": 1938, "text": "x -> vector with positive reviews for Amazon" }, { "code": null, "e": 2204, "s": 1983, "text": "# qdap cleaning function> qdap_clean <- function(x) { x <- replace_abbreviations(x) x <- replace_contractions(x) x <- replace_number(x) x <- replace_ordinal(x) x <- replace_symbol(x) x <- tolower(x) return(x)}" }, { "code": null, "e": 2293, "s": 2204, "text": "**You can also add more cleaning functions to the above, based on specific requirements." }, { "code": null, "e": 2328, "s": 2293, "text": "corpus -> VCorpus(VectorSource(x))" }, { "code": null, "e": 2522, "s": 2328, "text": "Then use the tm_map() function — provided by the tm package — to apply cleaning functions to a corpus. Mapping these functions to an entire corpus makes scaling of the cleaning steps very easy." }, { "code": null, "e": 2825, "s": 2522, "text": "# tm cleaning function> clean_corpus <- function(corpus){ corpus <- tm_map(corpus, stripWhitespace) corpus <- tm_map(corpus, removePunctuation) corpus <- tm_map(corpus, content_transformer(tolower)) corpus <- tm_map(corpus, removeWords, c(stopwords(\"en\"), \"Google\", \"Amazon\", \"company)) return(corpus)}" }, { "code": null, "e": 2890, "s": 2825, "text": "Word stemming and stem completion on a sentence using tm package" }, { "code": null, "e": 3113, "s": 2890, "text": "The tm package provides the stemDocument() function to get to a word’s root. This function either takes in a character vector and returns a character vector, or takes in a PlainTextDocument and returns a PlainTextDocument." }, { "code": null, "e": 3422, "s": 3113, "text": "# Remove punctuation> rm_punc <- removePunctuation(text_data)# Create character vector> n_char_vec <- unlist(strsplit(rm_punc, split = ' '))# Perform word stemming: stem_doc> stem_doc <- stemDocument(n_char_vec)# Re-complete stemmed document: complete_doc> complete_doc <- stemCompletion(stem_doc, comp_dict)" }, { "code": null, "e": 3441, "s": 3422, "text": "Point to remember:" }, { "code": null, "e": 3563, "s": 3441, "text": "Define your own comp_dict which is a custom dictionary containing words you want to use to re-complete the stemmed words." }, { "code": null, "e": 3870, "s": 3563, "text": "After completing the basic cleaning and pre-processing of text, the next step is to extract the key features which can be done in the form of sentiment scoring or extracting n-grams and plotting them. For this purpose, the TermDocumentMatrix (TDM) or DocumentTerm Matrix (DTM) functions come in very handy." }, { "code": null, "e": 3991, "s": 3870, "text": "# Generate TDM> coffee_tdm <- TermDocumentMatrix(clean_corp)# Generate DTM> coffee_dtm <- DocumentTermMatrix(clean_corp)" }, { "code": null, "e": 4011, "s": 3991, "text": "Points to remember:" }, { "code": null, "e": 4144, "s": 4011, "text": "You can use TDM when you have more words than documents to be reviewed, as it is easier to read a large number of rows than columns." }, { "code": null, "e": 4281, "s": 4144, "text": "You can then convert the results to matrices using the as.matrix() function, and then slice and dice and review parts of these matrices." }, { "code": null, "e": 4339, "s": 4281, "text": "Let’s see a simple example of creating a TDM for bigrams:" }, { "code": null, "e": 4616, "s": 4339, "text": "To create a bigrams TDM, we use TermDocumentMatrix() along with a control argument which receives a list of control functions (please refer to TermDocumentMatrix for more details). Here, a built-in function called tokenizer is used, which helps in tokenizing words as bigrams." }, { "code": null, "e": 4843, "s": 4616, "text": "# Create bigram TDM> amzn_p_tdm <- TermDocumentMatrix(amzn_pros_corp,control = list(tokenize = tokenizer))# Create amzn_p_tdm_m> amzn_p_tdm_m <- as.matrix(amzn_p_tdm) # Create amzn_p_freq > amzn_p_freq <- rowSums(amzn_p_tdm_m)" }, { "code": null, "e": 4932, "s": 4843, "text": "There are multiple ways to analyze the text features. A few of them are discussed below." }, { "code": null, "e": 5125, "s": 4932, "text": "# Sort term_frequency in descending order> amzn_p_freq <- sort(amzn_p_freq, decreasing = TRUE) > # Plot a barchart of the 10 most common words> barplot(amzn_p_freq[1:10], col = \"tan\", las = 2)" }, { "code": null, "e": 5244, "s": 5125, "text": "# Plot a wordcloud using amzn_p_freq values> wordcloud(names(amzn_p_freq), amzn_p_freq, max.words = 25, color = \"red\")" }, { "code": null, "e": 5352, "s": 5244, "text": "To further learn different ways to plot wordcloud, please refer to this article which I found quite useful." }, { "code": null, "e": 5374, "s": 5352, "text": "c. Cluster Dendograms" }, { "code": null, "e": 5514, "s": 5374, "text": "This is a simple clustering technique to perform a hierarchical cluster and create a dendrogram to see how connected different phrases are." }, { "code": null, "e": 5778, "s": 5514, "text": "# Create amzn_p_tdm2 by removing sparse terms> amzn_p_tdm2 <- removeSparseTerms(amzn_p_tdm, sparse = .993) > # Create hc as a cluster of distance values> hc <- hclust(dist(amzn_p_tdm2, method = \"euclidean\"), method = \"complete\") > # Produce a plot of hc> plot(hc)" }, { "code": null, "e": 5887, "s": 5778, "text": "You can see similar topics throughout the dendrogram like “great benefits,” “good pay,” “smart people,” etc." }, { "code": null, "e": 5907, "s": 5887, "text": "d. Word Association" }, { "code": null, "e": 6053, "s": 5907, "text": "This is used to examine top phrases that appear in the word clouds and find associated terms using the findAssocs() function from the tm package." }, { "code": null, "e": 6175, "s": 6053, "text": "The code below is used to find the most associated words with the most frequent terms in the positive reviews for Amazon." }, { "code": null, "e": 6669, "s": 6175, "text": "# Find associations with Top 2 most frequent words> findAssocs(amzn_p_tdm, \"great benefits\", 0.2) $`great benefits` stock options options four four hundred vacation time 0.35 0.28 0.27 0.26 benefits stock competitive pay great management time vacation 0.22 0.22 0.22 0.22> findAssocs(amzn_p_tdm, \"good pay\", 0.2) $`good pay` pay benefits pay good good people work nice 0.31 0.23 0.22 0.22" }, { "code": null, "e": 6690, "s": 6669, "text": "e. Comparison Clouds" }, { "code": null, "e": 6845, "s": 6690, "text": "This is used when you wish to examine two different corpuses of words in one go, rather then analyzing them separately (which can be more time consuming)." }, { "code": null, "e": 6915, "s": 6845, "text": "The code below compares the positive and negative reviews for Google." }, { "code": null, "e": 7379, "s": 6915, "text": "# Create all_goog_corp> all_goog_corp <- tm_clean(all_goog_corpus) > # Create all_tdm> all_tdm <- TermDocumentMatrix(all_goog_corp)<>Non-/sparse entries: 2845/1713Sparsity : 38%Maximal term length: 27Weighting : term frequency (tf)> # Name the columns of all_tdm> colnames(all_tdm) <- c(\"Goog_Pros\", \"Goog_Cons\") > # Create all_m> all_m <- as.matrix(all_tdm) > # Build a comparison cloud> comparison.cloud(all_m, colors = c(\"#F44336\", \"#2196f3\"), max.words = 100)" }, { "code": null, "e": 7396, "s": 7379, "text": "f. Pyramid Plots" }, { "code": null, "e": 7532, "s": 7396, "text": "Pyramid plots are used to display a pyramid (as opposed to a horizontal bar) plot and help in easy comparison based on similar phrases." }, { "code": null, "e": 7612, "s": 7532, "text": "The code below compares the frequency of positive phrases for Amazon vs Google." }, { "code": null, "e": 8731, "s": 7612, "text": "# Create common_words> common_words <- subset(all_tdm_m, all_tdm_m[,1] > 0 & all_tdm_m[,2] > 0)> str(common_words) num [1:269, 1:2] 1 1 1 1 1 3 2 2 1 1 ... - attr(*, \"dimnames\")=List of 2 ..$ Terms: chr [1:269] \"able work\" \"actual work\" \"area traffic\" \"atmosphere little\" ... ..$ Docs : chr [1:2] \"Amazon Pro\" \"Google Pro\"# Create difference> difference <- abs(common_words[,1]- common_words[,2]) ># Add difference to common_words> common_words <- cbind(common_words, difference) > head(common_words) Amazon Pro Google Pro difference able work 1 1 0 actual work 1 1 0 area traffic 1 1 0 atmosphere little 1 1 0 back forth 1 1 0 bad work 3 1 2# Order the data frame from most differences to least> common_words <- common_words[order(common_words[,\"difference\"],decreasing = TRUE),]# Create top15_df> top15_df <- data.frame(x = common_words[1:15,1], y = common_words[1:15,2], labels = rownames(common_words[1:15,]))# Create the pyramid plot> pyramid.plot(top15_df$x, top15_df$y, labels = top15_df$labels, gap = 12, top.labels = c(\"Amzn\", \"Pro Words\", \"Google\"), main = \"Words in Common\", unit = NULL) [1] 5.1 4.1 4.1 2.1" }, { "code": null, "e": 9065, "s": 8731, "text": "Based on the above visual (“Words in Common” pyramid plot), overall Amazon looks to have a better work environment and work-life balance than Google. Working hours seem to be higher at Amazon, but perhaps they provide other benefits to restore the work-life balance. We would need to collect more reviews to make a better conclusion." }, { "code": null, "e": 9546, "s": 9065, "text": "So, finally we come to the end of this blog. We learned how to organize our text analytics project, the different steps involved in cleaning and pre-processing and finally how to visualize the features and draw conclusions. I am on my way to completing my text analytics project based on this blog and learnings from DataCamp. I will soon post my GitHub repository for the project to help you further. Our next goal should be to perform sentiment analysis. Till then keep CODING!!" }, { "code": null, "e": 9668, "s": 9546, "text": "Hope you liked this blog. Do share your comments on what you liked and what you would like me to improve in my next blog." }, { "code": null, "e": 9711, "s": 9668, "text": "Keep watching this space for more. Cheers!" } ]
Deep Learning Side By Side: Julia v.s. Python | by DJ Passey | Towards Data Science
Julia could possibly be the biggest threat to Python. For a variety of applications, Julia is hands-down faster than Python and is almost as fast as C. Julia also offers features like multiple dispatch and metaprogramming that give it an edge over Python. At the same time, Python is established, widely used, and has a variety of time tested packages. The question of switching to Julia is a hard question to address. Often the answer is a frustrating, “It depends”. To help showcase Julia and to address the question of whether to use it, I’ve taken samples of deep learning code from both languages and placed them in series for easy comparison. I will walk through training VGG19 model on the CIFAR10 dataset. Deep learning models can be huge and often take a lot of work to define, especially when they contain specialized layers like ResNet [1]. We will use a medium sized model (no pun intended) , VGG19, for this comparison [2]. VGG19 in Python I’ve chosen Keras for our Python implementation because its lightweight and flexible design is competitive with Julia. from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, MaxPool2D , Flattenvgg19 = Sequential()vgg19.add(Conv2D(input_shape=(224,224,3),filters=64,kernel_size=(3,3),padding="same", activation="relu"))vgg19.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Flatten())model.add(Dense(units=4096,activation="relu"))vgg19.add(Dense(units=4096,activation="relu"))vgg19.add(Dense(units=10, activation="softmax"))# Code from Rohit Thakur on GitHub The task here is to concatenate 21 layers of deep learning machinery. Python handles this well. The syntax is simple and easy to understand. While the .add() function might be a little ugly, it is obvious what it is doing. Furthermore, it is clear in the code what each model layer does. (Convolves, pools, flattens, etc..) VGG19 In Julia using Fluxvgg16() = Chain( Conv((3, 3), 3 => 64, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 64 => 64, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 64 => 128, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 128 => 128, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 128 => 256, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 256 => 256, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 256 => 256, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 256 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), BatchNorm(512), MaxPool((2,2)), flatten, Dense(512, 4096, relu), Dropout(0.5), Dense(4096, 4096, relu), Dropout(0.5), Dense(4096, 10), softmax)# Code from Flux Model Zoo on Github Discussion At a glance, Julia looks slightly less cluttered than Python. The import statements are a little cleaner and the code is a little easier to read. Like Python, it is clear what each layer does. The Chain type is a little ambiguous, but it is pretty clear that it concatenates the layers together. Something to notice is that there is no model class. In fact, Julia is not object oriented, so each layer is a type instead of a class. This is worth noting because it emphasizes how the Julia model is very lightweight. Each of these layers was defined independently and then chained together without any class structure to control how they interact. However, avoiding a little clutter doesn’t really matter when training giant models. The advantage for Python here is that Python has a huge amount of support for troubleshooting and working through bugs. The documentation is excellent and there are hundreds of VGG19 examples online. Contrast this with Julia where there are five unique VGG19 examples online (maybe). For data processing we will look at the dataset CIFAR10 that is commonly associated with VGG19. Data Processing In Python from keras.datasets import cifar10from keras.utils import to_categorical(X, Y), (tsX, tsY) = cifar10.load_data() # Use a one-hot-encodingY = to_categorical(Y)tsY = to_categorical(tsY)# Change datatype to floatX = X.astype('float32')tsX = tsX.astype('float32') # Scale X and tsX so each entry is between 0 and 1X = X / 255.0tsX = tsX / 255.0 In order to train the model on image data, images must be put into the correct format. It only takes a few lines of code to do this. Images are loaded into variables along with image labels. To make classification easier, the labels are translated into a one hot encoding format. This is relatively straightforward in Python. Data Processing In Julia using MLDatasets: CIFAR10using Flux: onehotbatch# Data comes pre-normalized in JuliatrainX, trainY = CIFAR10.traindata(Float64)testX, testY = CIFAR10.testdata(Float64)# One hot encode labelstrainY = onehotbatch(trainY, 0:9)testY = onehotbatch(testY, 0:9) Julia requires the same kind of image processing as Python to prepare images for the training process. The code looks extremely similar and does not appear to favor either language. Next we will look at the model training loop. Training in Python optimizer = SGD(lr=0.001, momentum=0.9)vgg19.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])history = model.fit(X, Y, epochs=100, batch_size=64, validation_data=(tsX, tsY), verbose=0) Training In Julia using Flux: crossentropy, @epochsusing Flux.Data: DataLoadermodel = vgg19()opt = Momentum(.001, .9)loss(x, y) = crossentropy(model(x), y)data = DataLoader(trainX, trainY, batchsize=64)@epochs 100 Flux.train!(loss, params(model), data, opt) The code here is about equally verbose, but the differences in the languages show. In Python, model.fit returns a dictionary containing accuracy and loss evaluations. It also has keyword arguments to automate the optimization process for you. Julia is much more bare-bones. The training algorithm requires the user to provide their own loss function, optimizer and iterable containing batches of data along with the model. The Python implementation is much more user friendly. The training process is easy and produces useful output. Julia requires a little more from the user. At the same time, Julia is more abstract, and allows any optimizer and loss function. The user can define a loss function any way that they want without needing to consult a list of built in loss functions. This kind of abstraction is typical of Julia developers, who work to make code as abstract and generic as possible. For this reason, Keras is more practical for implementing known techniques and standard model training, but makes Flux better suited for developing new techniques. Unfortunately, there is no available benchmark comparing Flux and Keras on the internet. There are a few resources that give us an idea and we can use TensorFlow speed as a reference. One benchmark found that on the GPU and on the CPU, Flux is barely slower than TensorFlow. It’s been shown that Keras is slightly slower than TensorFlow on the GPU as well. Unfortunately this doesn’t give us a clear winner but suggests that the speed of the two packages are similar. The Flux benchmark above was done before a major rework of Flux’s automatic differentiation package. The new package, Zygote.jl, sped up computations considerably. A more recent benchmark of Flux on the CPU found that the improved Flux is faster than TensorFlow on the CPU. This suggests that Flux could be faster on the on the GPU as well, but winning on the CPU doesn’t necessarily imply a victory on the GPU. At the same time, this is still good evidence that Flux would beat Keras on the CPU. Both languages preform well in every category. Differences between the two are largely matters of taste. However there are two places that each language has an edge. Python has a huge support community and offers time tested libraries. It is reliable and standard. Deep learning in Python is much more common. Developers who use Python for deep learning will fit in well in the deep learning community. Julia is cleaner and more abstract. The deep learning code could definitely be faster and improvements are in the works. Julia has an edge on potential. Deep Learning libraries in Python are much more complete, and don’t have as much potential to grow and develop. Julia, with its richer base language has potential for many new ideas and much faster code in the future. Developers who adopt Julia will be closer to the frontier of programming, but will have to deal with forging their own path. Deep learning is difficult and requires a lot of troubleshooting. It can be very difficult to reach state of the art accuracy. For this reason, Python wins this comparison. Deep learning in Julia does not have a strong level of online support for deep learning troubleshooting. This can make writing complicated deep learning scripts very difficult. Julia is excellent for many applications, but for deep learning, I would recommend Python. medium.com towardsdatascience.com [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun, Deep Residual Learning for Image Recognition, CVPR 2016. [2] Karen Simonyan, Andrew Zisserman, Very Deep Convolutional Networks for Large-Scale Image Recognition, International Conference on Learning Representations, 2015
[ { "code": null, "e": 428, "s": 172, "text": "Julia could possibly be the biggest threat to Python. For a variety of applications, Julia is hands-down faster than Python and is almost as fast as C. Julia also offers features like multiple dispatch and metaprogramming that give it an edge over Python." }, { "code": null, "e": 640, "s": 428, "text": "At the same time, Python is established, widely used, and has a variety of time tested packages. The question of switching to Julia is a hard question to address. Often the answer is a frustrating, “It depends”." }, { "code": null, "e": 886, "s": 640, "text": "To help showcase Julia and to address the question of whether to use it, I’ve taken samples of deep learning code from both languages and placed them in series for easy comparison. I will walk through training VGG19 model on the CIFAR10 dataset." }, { "code": null, "e": 1109, "s": 886, "text": "Deep learning models can be huge and often take a lot of work to define, especially when they contain specialized layers like ResNet [1]. We will use a medium sized model (no pun intended) , VGG19, for this comparison [2]." }, { "code": null, "e": 1125, "s": 1109, "text": "VGG19 in Python" }, { "code": null, "e": 1244, "s": 1125, "text": "I’ve chosen Keras for our Python implementation because its lightweight and flexible design is competitive with Julia." }, { "code": null, "e": 2918, "s": 1244, "text": "from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, MaxPool2D , Flattenvgg19 = Sequential()vgg19.add(Conv2D(input_shape=(224,224,3),filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))vgg19.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))vgg19.add(Flatten())model.add(Dense(units=4096,activation=\"relu\"))vgg19.add(Dense(units=4096,activation=\"relu\"))vgg19.add(Dense(units=10, activation=\"softmax\"))# Code from Rohit Thakur on GitHub" }, { "code": null, "e": 3242, "s": 2918, "text": "The task here is to concatenate 21 layers of deep learning machinery. Python handles this well. The syntax is simple and easy to understand. While the .add() function might be a little ugly, it is obvious what it is doing. Furthermore, it is clear in the code what each model layer does. (Convolves, pools, flattens, etc..)" }, { "code": null, "e": 3257, "s": 3242, "text": "VGG19 In Julia" }, { "code": null, "e": 4379, "s": 3257, "text": "using Fluxvgg16() = Chain( Conv((3, 3), 3 => 64, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 64 => 64, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 64 => 128, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 128 => 128, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 128 => 256, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 256 => 256, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 256 => 256, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 256 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), MaxPool((2,2)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), Conv((3, 3), 512 => 512, relu, pad=(1, 1), stride=(1, 1)), BatchNorm(512), MaxPool((2,2)), flatten, Dense(512, 4096, relu), Dropout(0.5), Dense(4096, 4096, relu), Dropout(0.5), Dense(4096, 10), softmax)# Code from Flux Model Zoo on Github" }, { "code": null, "e": 4390, "s": 4379, "text": "Discussion" }, { "code": null, "e": 4686, "s": 4390, "text": "At a glance, Julia looks slightly less cluttered than Python. The import statements are a little cleaner and the code is a little easier to read. Like Python, it is clear what each layer does. The Chain type is a little ambiguous, but it is pretty clear that it concatenates the layers together." }, { "code": null, "e": 5037, "s": 4686, "text": "Something to notice is that there is no model class. In fact, Julia is not object oriented, so each layer is a type instead of a class. This is worth noting because it emphasizes how the Julia model is very lightweight. Each of these layers was defined independently and then chained together without any class structure to control how they interact." }, { "code": null, "e": 5406, "s": 5037, "text": "However, avoiding a little clutter doesn’t really matter when training giant models. The advantage for Python here is that Python has a huge amount of support for troubleshooting and working through bugs. The documentation is excellent and there are hundreds of VGG19 examples online. Contrast this with Julia where there are five unique VGG19 examples online (maybe)." }, { "code": null, "e": 5502, "s": 5406, "text": "For data processing we will look at the dataset CIFAR10 that is commonly associated with VGG19." }, { "code": null, "e": 5528, "s": 5502, "text": "Data Processing In Python" }, { "code": null, "e": 5869, "s": 5528, "text": "from keras.datasets import cifar10from keras.utils import to_categorical(X, Y), (tsX, tsY) = cifar10.load_data() # Use a one-hot-encodingY = to_categorical(Y)tsY = to_categorical(tsY)# Change datatype to floatX = X.astype('float32')tsX = tsX.astype('float32') # Scale X and tsX so each entry is between 0 and 1X = X / 255.0tsX = tsX / 255.0" }, { "code": null, "e": 6195, "s": 5869, "text": "In order to train the model on image data, images must be put into the correct format. It only takes a few lines of code to do this. Images are loaded into variables along with image labels. To make classification easier, the labels are translated into a one hot encoding format. This is relatively straightforward in Python." }, { "code": null, "e": 6220, "s": 6195, "text": "Data Processing In Julia" }, { "code": null, "e": 6475, "s": 6220, "text": "using MLDatasets: CIFAR10using Flux: onehotbatch# Data comes pre-normalized in JuliatrainX, trainY = CIFAR10.traindata(Float64)testX, testY = CIFAR10.testdata(Float64)# One hot encode labelstrainY = onehotbatch(trainY, 0:9)testY = onehotbatch(testY, 0:9)" }, { "code": null, "e": 6657, "s": 6475, "text": "Julia requires the same kind of image processing as Python to prepare images for the training process. The code looks extremely similar and does not appear to favor either language." }, { "code": null, "e": 6703, "s": 6657, "text": "Next we will look at the model training loop." }, { "code": null, "e": 6722, "s": 6703, "text": "Training in Python" }, { "code": null, "e": 6942, "s": 6722, "text": "optimizer = SGD(lr=0.001, momentum=0.9)vgg19.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])history = model.fit(X, Y, epochs=100, batch_size=64, validation_data=(tsX, tsY), verbose=0)" }, { "code": null, "e": 6960, "s": 6942, "text": "Training In Julia" }, { "code": null, "e": 7200, "s": 6960, "text": "using Flux: crossentropy, @epochsusing Flux.Data: DataLoadermodel = vgg19()opt = Momentum(.001, .9)loss(x, y) = crossentropy(model(x), y)data = DataLoader(trainX, trainY, batchsize=64)@epochs 100 Flux.train!(loss, params(model), data, opt)" }, { "code": null, "e": 7623, "s": 7200, "text": "The code here is about equally verbose, but the differences in the languages show. In Python, model.fit returns a dictionary containing accuracy and loss evaluations. It also has keyword arguments to automate the optimization process for you. Julia is much more bare-bones. The training algorithm requires the user to provide their own loss function, optimizer and iterable containing batches of data along with the model." }, { "code": null, "e": 8101, "s": 7623, "text": "The Python implementation is much more user friendly. The training process is easy and produces useful output. Julia requires a little more from the user. At the same time, Julia is more abstract, and allows any optimizer and loss function. The user can define a loss function any way that they want without needing to consult a list of built in loss functions. This kind of abstraction is typical of Julia developers, who work to make code as abstract and generic as possible." }, { "code": null, "e": 8265, "s": 8101, "text": "For this reason, Keras is more practical for implementing known techniques and standard model training, but makes Flux better suited for developing new techniques." }, { "code": null, "e": 8449, "s": 8265, "text": "Unfortunately, there is no available benchmark comparing Flux and Keras on the internet. There are a few resources that give us an idea and we can use TensorFlow speed as a reference." }, { "code": null, "e": 8733, "s": 8449, "text": "One benchmark found that on the GPU and on the CPU, Flux is barely slower than TensorFlow. It’s been shown that Keras is slightly slower than TensorFlow on the GPU as well. Unfortunately this doesn’t give us a clear winner but suggests that the speed of the two packages are similar." }, { "code": null, "e": 9230, "s": 8733, "text": "The Flux benchmark above was done before a major rework of Flux’s automatic differentiation package. The new package, Zygote.jl, sped up computations considerably. A more recent benchmark of Flux on the CPU found that the improved Flux is faster than TensorFlow on the CPU. This suggests that Flux could be faster on the on the GPU as well, but winning on the CPU doesn’t necessarily imply a victory on the GPU. At the same time, this is still good evidence that Flux would beat Keras on the CPU." }, { "code": null, "e": 9396, "s": 9230, "text": "Both languages preform well in every category. Differences between the two are largely matters of taste. However there are two places that each language has an edge." }, { "code": null, "e": 9633, "s": 9396, "text": "Python has a huge support community and offers time tested libraries. It is reliable and standard. Deep learning in Python is much more common. Developers who use Python for deep learning will fit in well in the deep learning community." }, { "code": null, "e": 10129, "s": 9633, "text": "Julia is cleaner and more abstract. The deep learning code could definitely be faster and improvements are in the works. Julia has an edge on potential. Deep Learning libraries in Python are much more complete, and don’t have as much potential to grow and develop. Julia, with its richer base language has potential for many new ideas and much faster code in the future. Developers who adopt Julia will be closer to the frontier of programming, but will have to deal with forging their own path." }, { "code": null, "e": 10570, "s": 10129, "text": "Deep learning is difficult and requires a lot of troubleshooting. It can be very difficult to reach state of the art accuracy. For this reason, Python wins this comparison. Deep learning in Julia does not have a strong level of online support for deep learning troubleshooting. This can make writing complicated deep learning scripts very difficult. Julia is excellent for many applications, but for deep learning, I would recommend Python." }, { "code": null, "e": 10581, "s": 10570, "text": "medium.com" }, { "code": null, "e": 10604, "s": 10581, "text": "towardsdatascience.com" }, { "code": null, "e": 10716, "s": 10604, "text": "[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun, Deep Residual Learning for Image Recognition, CVPR 2016." } ]
Objective-C Arrays
Objective-C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. To declare an array in Objective-C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Objective-C data type. For example, to declare a 10-element array called balance of type double, use this statement − double balance[10]; Now, balance is a variable array, which is sufficient to hold up to 10 double numbers. You can initialize an array in Objective-C either one by one or using a single statement as follows − double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array − If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; You will create exactly the same array as you did in the previous example. balance[4] = 50.0; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above − An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays − #import <Foundation/Foundation.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) { NSLog(@"Element[%d] = %d\n", j, n[j] ); } return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 01:24:06.669 demo[16508] Element[0] = 100 2013-09-14 01:24:06.669 demo[16508] Element[1] = 101 2013-09-14 01:24:06.669 demo[16508] Element[2] = 102 2013-09-14 01:24:06.669 demo[16508] Element[3] = 103 2013-09-14 01:24:06.669 demo[16508] Element[4] = 104 2013-09-14 01:24:06.669 demo[16508] Element[5] = 105 2013-09-14 01:24:06.669 demo[16508] Element[6] = 106 2013-09-14 01:24:06.669 demo[16508] Element[7] = 107 2013-09-14 01:24:06.669 demo[16508] Element[8] = 108 2013-09-14 01:24:06.669 demo[16508] Element[9] = 109 Arrays are important to Objective-C and need lots of more details. There are following few important concepts related to array which should be clear to a Objective-C programmer − Objective-C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. You can pass to the function a pointer to an array by specifying the array's name without an index. Objective-C allows a function to return an array. You can generate a pointer to the first element of an array by simply specifying the array name, without any index. 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2862, "s": 2560, "text": "Objective-C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." }, { "code": null, "e": 3141, "s": 2862, "text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index." }, { "code": null, "e": 3289, "s": 3141, "text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element." }, { "code": null, "e": 3434, "s": 3289, "text": "To declare an array in Objective-C, a programmer specifies the type of the elements and the number of elements required by an array as follows −" }, { "code": null, "e": 3465, "s": 3434, "text": "type arrayName [ arraySize ];\n" }, { "code": null, "e": 3712, "s": 3465, "text": "This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Objective-C data type. For example, to declare a 10-element array called balance of type double, use this statement −" }, { "code": null, "e": 3733, "s": 3712, "text": "double balance[10];\n" }, { "code": null, "e": 3820, "s": 3733, "text": "Now, balance is a variable array, which is sufficient to hold up to 10 double numbers." }, { "code": null, "e": 3922, "s": 3820, "text": "You can initialize an array in Objective-C either one by one or using a single statement as follows −" }, { "code": null, "e": 3974, "s": 3922, "text": "double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};" }, { "code": null, "e": 4185, "s": 3974, "text": "The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −" }, { "code": null, "e": 4311, "s": 4185, "text": "If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −" }, { "code": null, "e": 4362, "s": 4311, "text": "double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};" }, { "code": null, "e": 4437, "s": 4362, "text": "You will create exactly the same array as you did in the previous example." }, { "code": null, "e": 4457, "s": 4437, "text": "balance[4] = 50.0;\n" }, { "code": null, "e": 4764, "s": 4457, "text": "The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above −" }, { "code": null, "e": 4930, "s": 4764, "text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −" }, { "code": null, "e": 4958, "s": 4930, "text": "double salary = balance[9];" }, { "code": null, "e": 5188, "s": 4958, "text": "The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays −" }, { "code": null, "e": 5612, "s": 5188, "text": "#import <Foundation/Foundation.h>\n \nint main () {\n int n[ 10 ]; /* n is an array of 10 integers */\n int i,j;\n \n /* initialize elements of array n to 0 */ \n for ( i = 0; i < 10; i++ ) {\n n[ i ] = i + 100; /* set element at location i to i + 100 */\n }\n \n /* output each array element's value */\n for (j = 0; j < 10; j++ ) {\n NSLog(@\"Element[%d] = %d\\n\", j, n[j] );\n }\n \n return 0;\n}" }, { "code": null, "e": 5693, "s": 5612, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6224, "s": 5693, "text": "2013-09-14 01:24:06.669 demo[16508] Element[0] = 100\n2013-09-14 01:24:06.669 demo[16508] Element[1] = 101\n2013-09-14 01:24:06.669 demo[16508] Element[2] = 102\n2013-09-14 01:24:06.669 demo[16508] Element[3] = 103\n2013-09-14 01:24:06.669 demo[16508] Element[4] = 104\n2013-09-14 01:24:06.669 demo[16508] Element[5] = 105\n2013-09-14 01:24:06.669 demo[16508] Element[6] = 106\n2013-09-14 01:24:06.669 demo[16508] Element[7] = 107\n2013-09-14 01:24:06.669 demo[16508] Element[8] = 108\n2013-09-14 01:24:06.669 demo[16508] Element[9] = 109\n" }, { "code": null, "e": 6403, "s": 6224, "text": "Arrays are important to Objective-C and need lots of more details. There are following few important concepts related to array which should be clear to a Objective-C programmer −" }, { "code": null, "e": 6527, "s": 6403, "text": "Objective-C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array." }, { "code": null, "e": 6627, "s": 6527, "text": "You can pass to the function a pointer to an array by specifying the array's name without an index." }, { "code": null, "e": 6677, "s": 6627, "text": "Objective-C allows a function to return an array." }, { "code": null, "e": 6793, "s": 6677, "text": "You can generate a pointer to the first element of an array by simply specifying the array name, without any index." }, { "code": null, "e": 6826, "s": 6793, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 6843, "s": 6826, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 6874, "s": 6843, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 6885, "s": 6874, "text": " Ken Burke" }, { "code": null, "e": 6892, "s": 6885, "text": " Print" }, { "code": null, "e": 6903, "s": 6892, "text": " Add Notes" } ]
Common Subexpression Elimination - Code optimization Technique in Compiler Design - GeeksforGeeks
03 Dec, 2021 Code Optimization Technique is an approach to enhance the performance of the code by either eliminating or rearranging the code lines. Code Optimization techniques are as follows: Compile-time evaluation Common Sub-expression elimination Dead code elimination Code movement Strength reduction Compile-time evaluation Common Sub-expression elimination Dead code elimination Code movement Strength reduction The expression or sub-expression that has been appeared and computed before and appears again during the computation of the code is the common sub-expression. Elimination of that sub-expression is known as Common sub-expression elimination. The advantage of this elimination method is to make the computation faster and better by avoiding the re-computation of the expression. In addition, it utilizes memory efficiently. The two types of elimination methods in common sub-expression elimination are: 1. Local Common Sub-expression elimination– It is used within a single basic block. Where a basic block is a simple code sequence that has no branches. 2. Global Common Sub-expression elimination– It is used for an entire procedure of common sub-expression elimination. Example 1: Before elimination – a = 10; b = a + 1 * 2; c = a + 1 * 2; //’c’ has common expression as ‘b’ d = c + a; After elimination – a = 10; b = a + 1 * 2; d = b + a; Let’s understand Example 1 with a diagram: fig.: Example 1 As shown in the figure (fig.: Example 1), the result of ‘d’ would be similar with both expressions. So, we will eliminate one of the common subexpressions, as it helps in faster execution and efficient memory utilization. Example 2: Before elimination – x = 11; y = 11 * 24; z = x * 24; //'z' has common expression as 'y' as 'x' can be evaluated directly as done in 'y'. After elimination – y = 11 * 24; Picked Computer Subject GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Transmission Control Protocol (TCP)? Backpatching in Compiler Design 6 Best Books to Learn Computer Networking Difference Between User Mode and Kernel Mode Token, Patterns, and Lexems Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems
[ { "code": null, "e": 24642, "s": 24614, "text": "\n03 Dec, 2021" }, { "code": null, "e": 24822, "s": 24642, "text": "Code Optimization Technique is an approach to enhance the performance of the code by either eliminating or rearranging the code lines. Code Optimization techniques are as follows:" }, { "code": null, "e": 24936, "s": 24822, "text": " Compile-time evaluation Common Sub-expression elimination Dead code elimination Code movement Strength reduction" }, { "code": null, "e": 24961, "s": 24936, "text": " Compile-time evaluation" }, { "code": null, "e": 24996, "s": 24961, "text": " Common Sub-expression elimination" }, { "code": null, "e": 25019, "s": 24996, "text": " Dead code elimination" }, { "code": null, "e": 25034, "s": 25019, "text": " Code movement" }, { "code": null, "e": 25054, "s": 25034, "text": " Strength reduction" }, { "code": null, "e": 25295, "s": 25054, "text": "The expression or sub-expression that has been appeared and computed before and appears again during the computation of the code is the common sub-expression. Elimination of that sub-expression is known as Common sub-expression elimination." }, { "code": null, "e": 25476, "s": 25295, "text": "The advantage of this elimination method is to make the computation faster and better by avoiding the re-computation of the expression. In addition, it utilizes memory efficiently." }, { "code": null, "e": 25555, "s": 25476, "text": "The two types of elimination methods in common sub-expression elimination are:" }, { "code": null, "e": 25707, "s": 25555, "text": "1. Local Common Sub-expression elimination– It is used within a single basic block. Where a basic block is a simple code sequence that has no branches." }, { "code": null, "e": 25825, "s": 25707, "text": "2. Global Common Sub-expression elimination– It is used for an entire procedure of common sub-expression elimination." }, { "code": null, "e": 25836, "s": 25825, "text": "Example 1:" }, { "code": null, "e": 25857, "s": 25836, "text": "Before elimination –" }, { "code": null, "e": 25865, "s": 25857, "text": "a = 10;" }, { "code": null, "e": 25880, "s": 25865, "text": "b = a + 1 * 2;" }, { "code": null, "e": 25897, "s": 25880, "text": "c = a + 1 * 2; " }, { "code": null, "e": 25932, "s": 25897, "text": "//’c’ has common expression as ‘b’" }, { "code": null, "e": 25943, "s": 25932, "text": "d = c + a;" }, { "code": null, "e": 25963, "s": 25943, "text": "After elimination –" }, { "code": null, "e": 25971, "s": 25963, "text": "a = 10;" }, { "code": null, "e": 25986, "s": 25971, "text": "b = a + 1 * 2;" }, { "code": null, "e": 25997, "s": 25986, "text": "d = b + a;" }, { "code": null, "e": 26040, "s": 25997, "text": "Let’s understand Example 1 with a diagram:" }, { "code": null, "e": 26056, "s": 26040, "text": "fig.: Example 1" }, { "code": null, "e": 26278, "s": 26056, "text": "As shown in the figure (fig.: Example 1), the result of ‘d’ would be similar with both expressions. So, we will eliminate one of the common subexpressions, as it helps in faster execution and efficient memory utilization." }, { "code": null, "e": 26289, "s": 26278, "text": "Example 2:" }, { "code": null, "e": 26310, "s": 26289, "text": "Before elimination –" }, { "code": null, "e": 26429, "s": 26310, "text": "x = 11;\ny = 11 * 24; \nz = x * 24;\n//'z' has common expression as 'y' as 'x' can be evaluated directly as done in 'y'." }, { "code": null, "e": 26449, "s": 26429, "text": "After elimination –" }, { "code": null, "e": 26462, "s": 26449, "text": "y = 11 * 24;" }, { "code": null, "e": 26469, "s": 26462, "text": "Picked" }, { "code": null, "e": 26486, "s": 26469, "text": "Computer Subject" }, { "code": null, "e": 26494, "s": 26486, "text": "GATE CS" }, { "code": null, "e": 26592, "s": 26494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26637, "s": 26592, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 26669, "s": 26637, "text": "Backpatching in Compiler Design" }, { "code": null, "e": 26711, "s": 26669, "text": "6 Best Books to Learn Computer Networking" }, { "code": null, "e": 26756, "s": 26711, "text": "Difference Between User Mode and Kernel Mode" }, { "code": null, "e": 26784, "s": 26756, "text": "Token, Patterns, and Lexems" }, { "code": null, "e": 26804, "s": 26784, "text": "Layers of OSI Model" }, { "code": null, "e": 26828, "s": 26804, "text": "ACID Properties in DBMS" }, { "code": null, "e": 26841, "s": 26828, "text": "TCP/IP Model" }, { "code": null, "e": 26890, "s": 26841, "text": "Page Replacement Algorithms in Operating Systems" } ]
Replace part of a string with another string in C++
Here we will see how to replace a part of a string by another string in C++. In C++ the replacing is very easy. There is a function called string.replace(). This replace function replaces only the first occurrence of the match. To do it for all we have used loop. This replace function takes the index from where it will replace, it takes the length of the string, and the string which will be placed in the place of matched string. Input: A string "Hello...Here all Hello will be replaced", and another string to replace "ABCDE" Output: "ABCDE...Here all ABCDE will be replaced" Step 1: Get the main string, and the string which will be replaced. And the match string Step 2: While the match string is present in the main string: Step 2.1: Replace it with the given string. Step 3: Return the modified string Live Demo #include<iostream> using namespace std; main() { int index; string my_str = "Hello...Here all Hello will be replaced"; string sub_str = "ABCDE"; cout << "Initial String :" << my_str << endl; //replace all Hello with welcome while((index = my_str.find("Hello")) != string::npos) { //for each location where Hello is found my_str.replace(index, sub_str.length(), sub_str); //remove and replace from that position } cout << "Final String :" << my_str; } Initial String :Hello...Here all Hello will be replaced Final String :ABCDE...Here all ABCDE will be replaced
[ { "code": null, "e": 1495, "s": 1062, "text": "Here we will see how to replace a part of a string by another string in C++. In C++ the replacing is very easy. There is a function called string.replace(). This replace function replaces only the first occurrence of the match. To do it for all we have used loop. This replace function takes the index from where it will replace, it takes the length of the string, and the string which will be placed in the place of matched string." }, { "code": null, "e": 1642, "s": 1495, "text": "Input: A string \"Hello...Here all Hello will be replaced\", and another string to replace \"ABCDE\"\nOutput: \"ABCDE...Here all ABCDE will be replaced\"" }, { "code": null, "e": 1872, "s": 1642, "text": "Step 1: Get the main string, and the string which will be replaced. And the match string\nStep 2: While the match string is present in the main string:\nStep 2.1: Replace it with the given string.\nStep 3: Return the modified string" }, { "code": null, "e": 1883, "s": 1872, "text": " Live Demo" }, { "code": null, "e": 2367, "s": 1883, "text": "#include<iostream>\nusing namespace std;\nmain() {\n int index;\n string my_str = \"Hello...Here all Hello will be replaced\";\n string sub_str = \"ABCDE\";\n cout << \"Initial String :\" << my_str << endl;\n //replace all Hello with welcome\n while((index = my_str.find(\"Hello\")) != string::npos) { //for each location where Hello is found\n my_str.replace(index, sub_str.length(), sub_str); //remove and replace from that position\n }\n cout << \"Final String :\" << my_str;\n}" }, { "code": null, "e": 2477, "s": 2367, "text": "Initial String :Hello...Here all Hello will be replaced\nFinal String :ABCDE...Here all ABCDE will be replaced" } ]
Data Structures and Algorithms | Set 17 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE CS 2006 exam. 1. An implementation of a queue Q, using two stacks S1 and S2, is given below: void insert(Q, x) { push (S1, x);} void delete(Q){ if(stack-empty(S2)) then if(stack-empty(S1)) then { print(“Q is empty”); return; } else while (!(stack-empty(S1))){ x=pop(S1); push(S2,x); } x=pop(S2);} Let n insert and m (<=n) delete operations be performed in an arbitrary order on an empty queue Q. Let x and y be the number of push and pop operations performed respectively in the process. Which one of the following is true for all m and n?(A) n+m <= x < 2n and 2m <= y <= n+m (B) n+m <= x < 2n and 2m<= y <= 2n (C) 2m <= x < 2n and 2m <= y <= n+m (D) 2m <= x <2n and 2m <= y <= 2n Answer(A) The order in which insert and delete operations are performed matters here. The best case: Insert and delete operations are performed alternatively. In every delete operation, 2 pop and 1 push operations are performed. So, total m+ n push (n push for insert() and m push for delete()) operations and 2m pop operations are performed.The worst case: First n elements are inserted and then m elements are deleted. In first delete operation, n + 1 pop operations and n push operation are performed. Other than first, in all delete operations, 1 pop operation is performed. So, total m + n pop operations and 2n push operations are performed (n push for insert() and m push for delete()) 2. Consider the following graph:Which one of the following cannot be the sequence of edges added, in that order, to a minimum spanning tree using Kruskal’s algorithm?(A) (a—b),(d—f),(b—f),(d—c),(d—e)(B) (a—b),(d—f),(d—c),(b—f),(d—e)(C) (d—f),(a—b),(d—c),(b—f),(d—e)(D) (d—f),(a—b),(b—f),(d—e),(d—c) Answer (D)The edge (d-e) cannot be considered before (d-c) in Kruskal’s minimum spanning tree algorithm because Kruskal’s algorithm picks the edge with minimum weight from the current set of edges at each step. 3. The median of n elements can be found in O(n)time. Which one of the following is correct about the complexity of quick sort, in which median is selected as pivot?(A) Θ(n)(B) Θ(nlogn)(C) Θ(n^2)(D) Θ(n^3) Answer (B)If median is always used as pivot, then recursion remains T(n) = 2T(n/2) + cn for all the cases where cn is combined time for median finding and partition. So, worst case time complexity of this quick sort becomes Θ(nlogn). In practical implementations, however, this variant is considerably slower on average (see http://en.wikipedia.org/wiki/Quicksort#Selection-based_pivoting) Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2006 GATE-CS-DS-&-Algo GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Normal Forms in DBMS Differences between TCP and UDP Semaphores in Process Synchronization Caesar Cipher in Cryptography Practice questions on Height balanced/AVL Tree Operating Systems | Set 1 C Language | Set 1 Computer Networks | Set 1 Computer Networks | Set 2
[ { "code": null, "e": 24382, "s": 24354, "text": "\n27 Mar, 2017" }, { "code": null, "e": 24440, "s": 24382, "text": "Following questions have been asked in GATE CS 2006 exam." }, { "code": null, "e": 24519, "s": 24440, "text": "1. An implementation of a queue Q, using two stacks S1 and S2, is given below:" }, { "code": "void insert(Q, x) { push (S1, x);} void delete(Q){ if(stack-empty(S2)) then if(stack-empty(S1)) then { print(“Q is empty”); return; } else while (!(stack-empty(S1))){ x=pop(S1); push(S2,x); } x=pop(S2);}", "e": 24787, "s": 24519, "text": null }, { "code": null, "e": 25864, "s": 24787, "text": "Let n insert and m (<=n) delete operations be performed in an arbitrary order on an empty queue Q. Let x and y be the number of push and pop operations performed respectively in the process. Which one of the following is true for all m and n?(A) n+m <= x < 2n and 2m <= y <= n+m\n(B) n+m <= x < 2n and 2m<= y <= 2n\n(C) 2m <= x < 2n and 2m <= y <= n+m\n(D) 2m <= x <2n and 2m <= y <= 2n\nAnswer(A)\nThe order in which insert and delete operations are performed matters here.\nThe best case: Insert and delete operations are performed alternatively. In every delete operation, 2 pop and 1 push operations are performed. So, total m+ n push (n push for insert() and m push for delete()) operations and 2m pop operations are performed.The worst case: First n elements are inserted and then m elements are deleted. In first delete operation, n + 1 pop operations and n push operation are performed. Other than first, in all delete operations, 1 pop operation is performed. So, total m + n pop operations and 2n push operations are performed (n push for insert() and m push for delete())" }, { "code": null, "e": 26163, "s": 25864, "text": "2. Consider the following graph:Which one of the following cannot be the sequence of edges added, in that order, to a minimum spanning tree using Kruskal’s algorithm?(A) (a—b),(d—f),(b—f),(d—c),(d—e)(B) (a—b),(d—f),(d—c),(b—f),(d—e)(C) (d—f),(a—b),(d—c),(b—f),(d—e)(D) (d—f),(a—b),(b—f),(d—e),(d—c)" }, { "code": null, "e": 26374, "s": 26163, "text": "Answer (D)The edge (d-e) cannot be considered before (d-c) in Kruskal’s minimum spanning tree algorithm because Kruskal’s algorithm picks the edge with minimum weight from the current set of edges at each step." }, { "code": null, "e": 26580, "s": 26374, "text": "3. The median of n elements can be found in O(n)time. Which one of the following is correct about the complexity of quick sort, in which median is selected as pivot?(A) Θ(n)(B) Θ(nlogn)(C) Θ(n^2)(D) Θ(n^3)" }, { "code": null, "e": 26970, "s": 26580, "text": "Answer (B)If median is always used as pivot, then recursion remains T(n) = 2T(n/2) + cn for all the cases where cn is combined time for median finding and partition. So, worst case time complexity of this quick sort becomes Θ(nlogn). In practical implementations, however, this variant is considerably slower on average (see http://en.wikipedia.org/wiki/Quicksort#Selection-based_pivoting)" }, { "code": null, "e": 27119, "s": 26970, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 27132, "s": 27119, "text": "GATE-CS-2006" }, { "code": null, "e": 27150, "s": 27132, "text": "GATE-CS-DS-&-Algo" }, { "code": null, "e": 27158, "s": 27150, "text": "GATE CS" }, { "code": null, "e": 27162, "s": 27158, "text": "MCQ" }, { "code": null, "e": 27260, "s": 27162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27309, "s": 27260, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 27330, "s": 27309, "text": "Normal Forms in DBMS" }, { "code": null, "e": 27362, "s": 27330, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27400, "s": 27362, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 27430, "s": 27400, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 27477, "s": 27430, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 27503, "s": 27477, "text": "Operating Systems | Set 1" }, { "code": null, "e": 27522, "s": 27503, "text": "C Language | Set 1" }, { "code": null, "e": 27548, "s": 27522, "text": "Computer Networks | Set 1" } ]
GraphQL - Introduction
GraphQL is an open source server-side technology which was developed by Facebook to optimize RESTful API calls. It is an execution engine and a data query language. In this chapter, we discuss about the advantages of using GraphQL. RESTful APIs follow clear and well-structured resource-oriented approach. However, when the data gets more complex, the routes get longer. Sometimes it is not possible to fetch data with a single request. This is where GraphQL comes handy. GraphQL structures data in the form of a graph with its powerful query syntax for traversing, retrieving, and modifying data. The following are advantages of using GraphQL query Language − Send a GraphQL query to your API and get exactly what you need. GraphQL queries always return predictable results. Applications using GraphQL are fast and stable. Unlike Restful services, these applications can restrict data that should be fetched from the server. The following example will help you understand this better − Let us consider a business object Student with the attributes id, firstName, lastName and collegeName. Suppose a mobile application needs to fetch only the firstName and id. If we design a REST endpoint like /api/v1/students, it will end up fetching data for all the fields for a student object. This means, data is over fetched by the RESTful service. This problem can be solved by using GraphQL. Consider the GraphQL query given below − { students { id firstName } } This will return values only for the id and firstname fields. The query will not fetch values for other attributes of the student object. The response of the query illustrated above is as shown below − { "data": { "students": [ { "id": "S1001", "firstName": "Mohtashim" }, { "id": "S1002", "firstName": "Kannan" } ] } } GraphQL queries help to smoothly retrieve associated business objects, while typical REST APIs require loading from multiple URLs. GraphQL APIs fetch all the data your application need in a single request. Applications using GraphQL can be quick even on slow mobile network connections. Let us consider one more business object, College which has the attributes: name and location. The Student business object has an association relationship with the College object. If we were to use a REST API in order to fetch the details of students and their college, we will end up making two requests to the server like /api/v1/students and /api/v1/colleges. This will lead to under fetching of data with each request. So mobile applications are forced to make multiple calls to the server to get the desired data. However, the mobile application can fetch details for both Student and College objects in a single request by using GraphQL. The following is a GraphQL query to fetch data − { students{ id firstName lastName college{ name location } } } The output of the above query contains exactly those fields we have requested for as shown below − { "data": { "students": [ { "id": "S1001", "firstName": "Mohtashim", "lastName": "Mohammad", "college": { "name": "CUSAT", "location": "Kerala" } }, { "id": "S1002", "firstName": "Kannan", "lastName": "Sudhakaran", "college": { "name": "AMU", "location": "Uttar Pradesh" } }, { "id": "S1003", "firstName": "Kiran", "lastName": "Panigrahi", "college": { "name": "AMU", "location": "Uttar Pradesh" } } ] } } GraphQL is strongly typed and the queries are based on fields and their associated data types. If there is type mismatch in a GraphQL query, server applications return clear and helpful error messages. This helps in smooth debugging and easy detection of bugs by client applications. GraphQL also provides client side libraries that can help in reducing explicit data conversion and parsing. An example of the Student and College data types is given below − type Query { students:[Student] } type Student { id:ID! firstName:String lastName:String fullName:String college:College } type College { id:ID! name:String location:String rating:Float students:[Student] } GraphQL provides rich developer tools for documentation and testing queries. GraphiQL is an excellent tool which generates documentation of the query and its schema. It also gives a query editor to test GraphQL APIs and intelligent code completion capability while building queries. 43 Lectures 3 hours Nilay Mehta 53 Lectures 3 hours Asfend Yar 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2183, "s": 1951, "text": "GraphQL is an open source server-side technology which was developed by Facebook to optimize RESTful API calls. It is an execution engine and a data query language. In this chapter, we discuss about the advantages of using GraphQL." }, { "code": null, "e": 2549, "s": 2183, "text": "RESTful APIs follow clear and well-structured resource-oriented approach. However, when the data gets more complex, the routes get longer. Sometimes it is not possible to fetch data with a single request. This is where GraphQL comes handy. GraphQL structures data in the form of a graph with its powerful query syntax for traversing, retrieving, and modifying data." }, { "code": null, "e": 2612, "s": 2549, "text": "The following are advantages of using GraphQL query Language −" }, { "code": null, "e": 2877, "s": 2612, "text": "Send a GraphQL query to your API and get exactly what you need. GraphQL queries always return predictable results. Applications using GraphQL are fast and stable. Unlike Restful services, these applications can restrict data that should be fetched from the server." }, { "code": null, "e": 2938, "s": 2877, "text": "The following example will help you understand this better −" }, { "code": null, "e": 3336, "s": 2938, "text": "Let us consider a business object Student with the attributes id, firstName, lastName and collegeName. Suppose a mobile application needs to fetch only the firstName and id. If we design a REST endpoint like /api/v1/students, it will end up fetching data for all the fields for a student object. This means, data is over fetched by the RESTful service. This problem can be solved by using GraphQL." }, { "code": null, "e": 3377, "s": 3336, "text": "Consider the GraphQL query given below −" }, { "code": null, "e": 3426, "s": 3377, "text": "{\n students {\n id\n firstName\n }\n}\n" }, { "code": null, "e": 3628, "s": 3426, "text": "This will return values only for the id and firstname fields. The query will not fetch values for other attributes of the student object. The response of the query illustrated above is as shown below −" }, { "code": null, "e": 3848, "s": 3628, "text": "{\n \"data\": {\n \"students\": [\n {\n \"id\": \"S1001\",\n \"firstName\": \"Mohtashim\"\n },\n {\n \"id\": \"S1002\",\n \"firstName\": \"Kannan\"\n }\n ]\n }\n}" }, { "code": null, "e": 4135, "s": 3848, "text": "GraphQL queries help to smoothly retrieve associated business objects, while typical REST APIs require loading from multiple URLs. GraphQL APIs fetch all the data your application need in a single request. Applications using GraphQL can be quick even on slow mobile network connections." }, { "code": null, "e": 4654, "s": 4135, "text": "Let us consider one more business object, College which has the attributes: name and location. The Student business object has an association relationship with the College object. If we were to use a REST API in order to fetch the details of students and their college, we will end up making two requests to the server like /api/v1/students and /api/v1/colleges. This will lead to under fetching of data with each request. So mobile applications are forced to make multiple calls to the server to get the desired data." }, { "code": null, "e": 4779, "s": 4654, "text": "However, the mobile application can fetch details for both Student and College objects in a single request by using GraphQL." }, { "code": null, "e": 4828, "s": 4779, "text": "The following is a GraphQL query to fetch data −" }, { "code": null, "e": 4945, "s": 4828, "text": "{\n students{\n id\n firstName\n lastName\n college{\n name\n location\n }\n }\n}" }, { "code": null, "e": 5044, "s": 4945, "text": "The output of the above query contains exactly those fields we have requested for as shown below −" }, { "code": null, "e": 5812, "s": 5044, "text": "{\n \"data\": {\n \"students\": [\n {\n \"id\": \"S1001\",\n \"firstName\": \"Mohtashim\",\n \"lastName\": \"Mohammad\",\n \"college\": {\n \"name\": \"CUSAT\",\n \"location\": \"Kerala\"\n }\n },\n \n {\n \"id\": \"S1002\",\n \"firstName\": \"Kannan\",\n \"lastName\": \"Sudhakaran\",\n \"college\": {\n \"name\": \"AMU\",\n \"location\": \"Uttar Pradesh\"\n }\n },\n \n {\n \"id\": \"S1003\",\n \"firstName\": \"Kiran\",\n \"lastName\": \"Panigrahi\",\n \"college\": {\n \"name\": \"AMU\",\n \"location\": \"Uttar Pradesh\"\n }\n }\n ]\n }\n}" }, { "code": null, "e": 6204, "s": 5812, "text": "GraphQL is strongly typed and the queries are based on fields and their associated data types. If there is type mismatch in a GraphQL query, server applications return clear and helpful error messages. This helps in smooth debugging and easy detection of bugs by client applications. GraphQL also provides client side libraries that can help in reducing explicit data conversion and parsing." }, { "code": null, "e": 6270, "s": 6204, "text": "An example of the Student and College data types is given below −" }, { "code": null, "e": 6512, "s": 6270, "text": "type Query {\n students:[Student]\n}\n\ntype Student {\n id:ID!\n firstName:String\n lastName:String\n fullName:String\n college:College\n}\n\ntype College {\n id:ID!\n name:String\n location:String\n rating:Float\n students:[Student]\n}" }, { "code": null, "e": 6795, "s": 6512, "text": "GraphQL provides rich developer tools for documentation and testing queries. GraphiQL is an excellent tool which generates documentation of the query and its schema. It also gives a query editor to test GraphQL APIs and intelligent code completion capability while building queries." }, { "code": null, "e": 6828, "s": 6795, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 6841, "s": 6828, "text": " Nilay Mehta" }, { "code": null, "e": 6874, "s": 6841, "text": "\n 53 Lectures \n 3 hours \n" }, { "code": null, "e": 6886, "s": 6874, "text": " Asfend Yar" }, { "code": null, "e": 6919, "s": 6886, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6937, "s": 6919, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 6944, "s": 6937, "text": " Print" }, { "code": null, "e": 6955, "s": 6944, "text": " Add Notes" } ]
cp command in Linux with examples - GeeksforGeeks
19 Feb, 2021 cp stands for copy. This command is used to copy files or group of files or directory. It creates an exact image of a file on a disk with different file name. cp command require at least two filenames in its arguments. Syntax: cp [OPTION] Source Destination cp [OPTION] Source Directory cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory First and second syntax is used to copy Source file to Destination file or Directory. Third syntax is used to copy multiple Sources(files) to Directory. cp command works on three principal modes of operation and these operations depend upon number and type of arguments passed in cp command : Two file names : If the command contains two file names, then it copy the contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it creates one and content is copied to it. But if it existed then it is simply overwritten without any warning. So be careful when you choose destination file name.cp Src_file Dest_file Suppose there is a directory named geeksforgeeks having a text file a.txt.Example:$ ls a.txt $ cp a.txt b.txt $ ls a.txt b.txt One or more arguments : If the command has one or more arguments, specifying file names and following those arguments, an argument specifying directory name then this command copies each source file to the destination directory with the same name, created if not existed but if already existed then it will be overwritten, so be careful !!.cp Src_file1 Src_file2 Src_file3 Dest_directory Suppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory name new in which we are going to copy all files.Example:$ ls a.txt b.txt new Initially new is empty $ ls new $ cp a.txt b.txt new $ ls new a.txt b.txt Note: For this case last argument must be a directory name. For the above command to work, Dest_directory must exist because cp command won’t create it.Two directory names : If the command contains two directory names, cp copies all files of the source directory to the destination directory, creating any files or directories needed. This mode of operation requires an additional option, typically R, to indicate the recursive copying of directories.cp -R Src_directory Dest_directory In the above command, cp behavior depend upon whether Dest_directory is exist or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory. Two file names : If the command contains two file names, then it copy the contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it creates one and content is copied to it. But if it existed then it is simply overwritten without any warning. So be careful when you choose destination file name.cp Src_file Dest_file Suppose there is a directory named geeksforgeeks having a text file a.txt.Example:$ ls a.txt $ cp a.txt b.txt $ ls a.txt b.txt cp Src_file Dest_file Suppose there is a directory named geeksforgeeks having a text file a.txt.Example: $ ls a.txt $ cp a.txt b.txt $ ls a.txt b.txt One or more arguments : If the command has one or more arguments, specifying file names and following those arguments, an argument specifying directory name then this command copies each source file to the destination directory with the same name, created if not existed but if already existed then it will be overwritten, so be careful !!.cp Src_file1 Src_file2 Src_file3 Dest_directory Suppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory name new in which we are going to copy all files.Example:$ ls a.txt b.txt new Initially new is empty $ ls new $ cp a.txt b.txt new $ ls new a.txt b.txt Note: For this case last argument must be a directory name. For the above command to work, Dest_directory must exist because cp command won’t create it. cp Src_file1 Src_file2 Src_file3 Dest_directory Suppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory name new in which we are going to copy all files.Example: $ ls a.txt b.txt new Initially new is empty $ ls new $ cp a.txt b.txt new $ ls new a.txt b.txt Note: For this case last argument must be a directory name. For the above command to work, Dest_directory must exist because cp command won’t create it. Two directory names : If the command contains two directory names, cp copies all files of the source directory to the destination directory, creating any files or directories needed. This mode of operation requires an additional option, typically R, to indicate the recursive copying of directories.cp -R Src_directory Dest_directory In the above command, cp behavior depend upon whether Dest_directory is exist or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory. cp -R Src_directory Dest_directory In the above command, cp behavior depend upon whether Dest_directory is exist or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory. Options: There are many options of cp command, here we will discuss some of the useful options:Suppose a directory named geeksforgeeks contains two files having some content named as a.txt and b.txt. This scenario is useful in understanding the following options. $ ls geeksforgeeks a.txt b.txt $ cat a.txt GFG $ cat b.txt GeeksforGeeks 1. -i(interactive): i stands for Interactive copying. With this option system first warns the user before overwriting the destination file. cp prompts for a response, if you press y then it overwrites the file and with any other option leave it uncopied. $ cp -i a.txt b.txt cp: overwrite 'b.txt'? y $ cat b.txt GFG 2. -b(backup): With this option cp command creates the backup of the destination file in the same folder with the different name and in different format. $ ls a.txt b.txt $ cp -b a.txt b.txt $ ls a.txt b.txt b.txt~ 3. -f(force): If the system is unable to open destination file for writing operation because the user doesn’t have writing permission for this file then by using -f option with cp command, destination file is deleted first and then copying of content is done from source to destination file. $ ls -l b.txt -r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt User, group and others doesn't have writing permission. Without -f option, command not executed $ cp a.txt b.txt cp: cannot create regular file 'b.txt': Permission denied With -f option, command executed successfully $ cp -f a.txt b.txt 4. -r or -R: Copying directory structure. With this option cp command shows its recursive behavior by copying the entire directory structure recursively.Suppose we want to copy geeksforgeeks directory containing many files, directories into gfg directory(not exist). $ ls geeksforgeeks/ a.txt b.txt b.txt~ Folder1 Folder2 Without -r option, error $ cp geeksforgeeks gfg cp: -r not specified; omitting directory 'geeksforgeeks' With -r, execute successfully $ cp -r geeksforgeeks gfg $ ls gfg/ a.txt b.txt b.txt~ Folder1 Folder2 5. -p(preserve): With -p option cp preserves the following characteristics of each source file in the corresponding destination file: the time of the last data modification and the time of the last access, the ownership (only if it has permissions to do this), and the file permission-bits.Note: For the preservation of characteristics you must be the root user of the system, otherwise characteristics changes. $ ls -l a.txt -rwxr-xr-x+ 1 User User 3 Nov 24 08:13 a.txt $ cp -p a.txt c.txt $ ls -l c.txt -rwxr-xr-x+ 1 User User 3 Nov 24 08:13 c.txt As we can see above both a.txt and c.txt(created by copying) have same characteristics. Examples: Copying using * wildcard: The star wildcard represents anything i.e. all files and directories. Suppose we have many text document in a directory and wants to copy it another directory, it takes lots of time if we copy files 1 by 1 or command becomes too long if specify all these file names as the argument, but by using * wildcard it becomes simple. Initially Folder1 is empty $ ls a.txt b.txt c.txt d.txt e.txt Folder1 $ cp *.txt Folder1 $ ls Folder1 a.txt b.txt c.txt d.txt e.txt YouTubeGeeksforGeeks501K subscribersLinux Tutorials | cp - Copying a File | GeeksforGeeksWatch laterShareCopy link15/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ngx4G10XY2s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>References:Wikipedia linux-command Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Mutex lock for Linux Thread Synchronization Tail command in Linux with examples tee command in Linux with examples Compiling with g++
[ { "code": null, "e": 23957, "s": 23929, "text": "\n19 Feb, 2021" }, { "code": null, "e": 24176, "s": 23957, "text": "cp stands for copy. This command is used to copy files or group of files or directory. It creates an exact image of a file on a disk with different file name. cp command require at least two filenames in its arguments." }, { "code": null, "e": 24184, "s": 24176, "text": "Syntax:" }, { "code": null, "e": 24457, "s": 24184, "text": "cp [OPTION] Source Destination\ncp [OPTION] Source Directory\ncp [OPTION] Source-1 Source-2 Source-3 Source-n Directory\n\nFirst and second syntax is used to copy Source file to Destination file or Directory.\nThird syntax is used to copy multiple Sources(files) to Directory.\n" }, { "code": null, "e": 24597, "s": 24457, "text": "cp command works on three principal modes of operation and these operations depend upon number and type of arguments passed in cp command :" }, { "code": null, "e": 26492, "s": 24597, "text": "Two file names : If the command contains two file names, then it copy the contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it creates one and content is copied to it. But if it existed then it is simply overwritten without any warning. So be careful when you choose destination file name.cp Src_file Dest_file\nSuppose there is a directory named geeksforgeeks having a text file a.txt.Example:$ ls\na.txt\n\n$ cp a.txt b.txt\n\n$ ls\na.txt b.txt\nOne or more arguments : If the command has one or more arguments, specifying file names and following those arguments, an argument specifying directory name then this command copies each source file to the destination directory with the same name, created if not existed but if already existed then it will be overwritten, so be careful !!.cp Src_file1 Src_file2 Src_file3 Dest_directory\nSuppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory name new in which we are going to copy all files.Example:$ ls\na.txt b.txt new\n\nInitially new is empty\n$ ls new\n\n$ cp a.txt b.txt new\n\n$ ls new\na.txt b.txt\nNote: For this case last argument must be a directory name. For the above command to work, Dest_directory must exist because cp command won’t create it.Two directory names : If the command contains two directory names, cp copies all files of the source directory to the destination directory, creating any files or directories needed. This mode of operation requires an additional option, typically R, to indicate the recursive copying of directories.cp -R Src_directory Dest_directory\nIn the above command, cp behavior depend upon whether Dest_directory is exist or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory." }, { "code": null, "e": 26964, "s": 26492, "text": "Two file names : If the command contains two file names, then it copy the contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it creates one and content is copied to it. But if it existed then it is simply overwritten without any warning. So be careful when you choose destination file name.cp Src_file Dest_file\nSuppose there is a directory named geeksforgeeks having a text file a.txt.Example:$ ls\na.txt\n\n$ cp a.txt b.txt\n\n$ ls\na.txt b.txt\n" }, { "code": null, "e": 26987, "s": 26964, "text": "cp Src_file Dest_file\n" }, { "code": null, "e": 27070, "s": 26987, "text": "Suppose there is a directory named geeksforgeeks having a text file a.txt.Example:" }, { "code": null, "e": 27119, "s": 27070, "text": "$ ls\na.txt\n\n$ cp a.txt b.txt\n\n$ ls\na.txt b.txt\n" }, { "code": null, "e": 27915, "s": 27119, "text": "One or more arguments : If the command has one or more arguments, specifying file names and following those arguments, an argument specifying directory name then this command copies each source file to the destination directory with the same name, created if not existed but if already existed then it will be overwritten, so be careful !!.cp Src_file1 Src_file2 Src_file3 Dest_directory\nSuppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory name new in which we are going to copy all files.Example:$ ls\na.txt b.txt new\n\nInitially new is empty\n$ ls new\n\n$ cp a.txt b.txt new\n\n$ ls new\na.txt b.txt\nNote: For this case last argument must be a directory name. For the above command to work, Dest_directory must exist because cp command won’t create it." }, { "code": null, "e": 27964, "s": 27915, "text": "cp Src_file1 Src_file2 Src_file3 Dest_directory\n" }, { "code": null, "e": 28119, "s": 27964, "text": "Suppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory name new in which we are going to copy all files.Example:" }, { "code": null, "e": 28221, "s": 28119, "text": "$ ls\na.txt b.txt new\n\nInitially new is empty\n$ ls new\n\n$ cp a.txt b.txt new\n\n$ ls new\na.txt b.txt\n" }, { "code": null, "e": 28374, "s": 28221, "text": "Note: For this case last argument must be a directory name. For the above command to work, Dest_directory must exist because cp command won’t create it." }, { "code": null, "e": 29003, "s": 28374, "text": "Two directory names : If the command contains two directory names, cp copies all files of the source directory to the destination directory, creating any files or directories needed. This mode of operation requires an additional option, typically R, to indicate the recursive copying of directories.cp -R Src_directory Dest_directory\nIn the above command, cp behavior depend upon whether Dest_directory is exist or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory." }, { "code": null, "e": 29039, "s": 29003, "text": "cp -R Src_directory Dest_directory\n" }, { "code": null, "e": 29334, "s": 29039, "text": "In the above command, cp behavior depend upon whether Dest_directory is exist or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory." }, { "code": null, "e": 29343, "s": 29334, "text": "Options:" }, { "code": null, "e": 29598, "s": 29343, "text": "There are many options of cp command, here we will discuss some of the useful options:Suppose a directory named geeksforgeeks contains two files having some content named as a.txt and b.txt. This scenario is useful in understanding the following options." }, { "code": null, "e": 29675, "s": 29598, "text": "$ ls geeksforgeeks\na.txt b.txt\n\n$ cat a.txt\nGFG\n\n$ cat b.txt\nGeeksforGeeks\n" }, { "code": null, "e": 29930, "s": 29675, "text": "1. -i(interactive): i stands for Interactive copying. With this option system first warns the user before overwriting the destination file. cp prompts for a response, if you press y then it overwrites the file and with any other option leave it uncopied." }, { "code": null, "e": 29993, "s": 29930, "text": "$ cp -i a.txt b.txt\ncp: overwrite 'b.txt'? y\n\n$ cat b.txt\nGFG\n" }, { "code": null, "e": 30147, "s": 29993, "text": "2. -b(backup): With this option cp command creates the backup of the destination file in the same folder with the different name and in different format." }, { "code": null, "e": 30214, "s": 30147, "text": "$ ls\na.txt b.txt\n\n$ cp -b a.txt b.txt\n\n$ ls\na.txt b.txt b.txt~\n" }, { "code": null, "e": 30506, "s": 30214, "text": "3. -f(force): If the system is unable to open destination file for writing operation because the user doesn’t have writing permission for this file then by using -f option with cp command, destination file is deleted first and then copying of content is done from source to destination file." }, { "code": null, "e": 30806, "s": 30506, "text": "$ ls -l b.txt\n-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt\n\nUser, group and others doesn't have writing permission.\n\nWithout -f option, command not executed\n$ cp a.txt b.txt\ncp: cannot create regular file 'b.txt': Permission denied\n\nWith -f option, command executed successfully\n$ cp -f a.txt b.txt\n" }, { "code": null, "e": 31073, "s": 30806, "text": "4. -r or -R: Copying directory structure. With this option cp command shows its recursive behavior by copying the entire directory structure recursively.Suppose we want to copy geeksforgeeks directory containing many files, directories into gfg directory(not exist)." }, { "code": null, "e": 31347, "s": 31073, "text": "$ ls geeksforgeeks/\na.txt b.txt b.txt~ Folder1 Folder2\n\nWithout -r option, error\n$ cp geeksforgeeks gfg\ncp: -r not specified; omitting directory 'geeksforgeeks'\n\nWith -r, execute successfully\n$ cp -r geeksforgeeks gfg\n\n$ ls gfg/\na.txt b.txt b.txt~ Folder1 Folder2\n\n" }, { "code": null, "e": 31759, "s": 31347, "text": "5. -p(preserve): With -p option cp preserves the following characteristics of each source file in the corresponding destination file: the time of the last data modification and the time of the last access, the ownership (only if it has permissions to do this), and the file permission-bits.Note: For the preservation of characteristics you must be the root user of the system, otherwise characteristics changes." }, { "code": null, "e": 31900, "s": 31759, "text": "$ ls -l a.txt\n-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 a.txt\n\n$ cp -p a.txt c.txt\n\n$ ls -l c.txt\n-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 c.txt\n" }, { "code": null, "e": 31988, "s": 31900, "text": "As we can see above both a.txt and c.txt(created by copying) have same characteristics." }, { "code": null, "e": 31998, "s": 31988, "text": "Examples:" }, { "code": null, "e": 32350, "s": 31998, "text": "Copying using * wildcard: The star wildcard represents anything i.e. all files and directories. Suppose we have many text document in a directory and wants to copy it another directory, it takes lots of time if we copy files 1 by 1 or command becomes too long if specify all these file names as the argument, but by using * wildcard it becomes simple." }, { "code": null, "e": 32495, "s": 32350, "text": "Initially Folder1 is empty\n$ ls\na.txt b.txt c.txt d.txt e.txt Folder1\n\n$ cp *.txt Folder1\n\n$ ls Folder1\na.txt b.txt c.txt d.txt e.txt\n\n" }, { "code": null, "e": 33356, "s": 32495, "text": "YouTubeGeeksforGeeks501K subscribersLinux Tutorials | cp - Copying a File | GeeksforGeeksWatch laterShareCopy link15/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ngx4G10XY2s\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>References:Wikipedia" }, { "code": null, "e": 33370, "s": 33356, "text": "linux-command" }, { "code": null, "e": 33390, "s": 33370, "text": "Linux-file-commands" }, { "code": null, "e": 33401, "s": 33390, "text": "Linux-Unix" }, { "code": null, "e": 33499, "s": 33401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33508, "s": 33499, "text": "Comments" }, { "code": null, "e": 33521, "s": 33508, "text": "Old Comments" }, { "code": null, "e": 33556, "s": 33521, "text": "tar command in Linux with examples" }, { "code": null, "e": 33594, "s": 33556, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33632, "s": 33594, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 33667, "s": 33632, "text": "Cat command in Linux with examples" }, { "code": null, "e": 33704, "s": 33667, "text": "touch command in Linux with Examples" }, { "code": null, "e": 33740, "s": 33704, "text": "echo command in Linux with Examples" }, { "code": null, "e": 33784, "s": 33740, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 33820, "s": 33784, "text": "Tail command in Linux with examples" }, { "code": null, "e": 33855, "s": 33820, "text": "tee command in Linux with examples" } ]
Design and Analysis Fractional Knapsack
The Greedy algorithm could be understood very well with a well-known problem referred to as Knapsack problem. Although the same problem could be solved by employing other algorithmic approaches, Greedy approach solves Fractional Knapsack problem reasonably in a good time. Let us discuss the Knapsack problem in detail. Given a set of items, each with a weight and a value, determine a subset of items to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. The knapsack problem is in combinatorial optimization problem. It appears as a subproblem in many, more complex mathematical models of real-world problems. One general approach to difficult problems is to identify the most restrictive constraint, ignore the others, solve a knapsack problem, and somehow adjust the solution to satisfy the ignored constraints. In many cases of resource allocation along with some constraint, the problem can be derived in a similar way of Knapsack problem. Following is a set of example. Finding the least wasteful way to cut raw materials portfolio optimization Cutting stock problems A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n items available in the store and weight of ith item is wi and its profit is pi. What items should the thief take? In this context, the items should be selected in such a way that the thief will carry those items for which he will gain maximum profit. Hence, the objective of the thief is to maximize the profit. Based on the nature of the items, Knapsack problems are categorized as Fractional Knapsack Knapsack In this case, items can be broken into smaller pieces, hence the thief can select fractions of items. According to the problem statement, There are n items in the store There are n items in the store Weight of ith item wi>0 Weight of ith item wi>0 Profit for ith item pi>0 and Profit for ith item pi>0 and Capacity of the Knapsack is W Capacity of the Knapsack is W In this version of Knapsack problem, items can be broken into smaller pieces. So, the thief may take only a fraction xi of ith item. 0⩽xi⩽1 The ith item contributes the weight xi.wi to the total weight in the knapsack and profit xi.pi to the total profit. Hence, the objective of this algorithm is to maximize∑n=1n(xi.pi) subject to constraint, ∑n=1n(xi.wi)⩽W It is clear that an optimal solution must fill the knapsack exactly, otherwise we could add a fraction of one of the remaining items and increase the overall profit. Thus, an optimal solution can be obtained by ∑n=1n(xi.wi)=W In this context, first we need to sort those items according to the value of piwi, so that pi+1wi+1 ≤ piwi . Here, x is an array to store the fraction of items. Algorithm: Greedy-Fractional-Knapsack (w[1..n], p[1..n], W) for i = 1 to n do x[i] = 0 weight = 0 for i = 1 to n if weight + w[i] ≤ W then x[i] = 1 weight = weight + w[i] else x[i] = (W - weight) / w[i] weight = W break return x If the provided items are already sorted into a decreasing order of piwi, then the whileloop takes a time in O(n); Therefore, the total time including the sort is in O(n logn). Let us consider that the capacity of the knapsack W = 60 and the list of provided items are shown in the following table − As the provided items are not sorted based on piwi. After sorting, the items are as shown in the following table. After sorting all the items according to piwi. First all of B is chosen as weight of B is less than the capacity of the knapsack. Next, item A is chosen, as the available capacity of the knapsack is greater than the weight of A. Now, C is chosen as the next item. However, the whole item cannot be chosen as the remaining capacity of the knapsack is less than the weight of C. Hence, fraction of C (i.e. (60 − 50)/20) is chosen. Now, the capacity of the Knapsack is equal to the selected items. Hence, no more item can be selected. The total weight of the selected items is 10 + 40 + 20 * (10/20) = 60 And the total profit is 100 + 280 + 120 * (10/20) = 380 + 60 = 440 This is the optimal solution. We cannot gain more profit selecting any different combination of items. 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2919, "s": 2599, "text": "The Greedy algorithm could be understood very well with a well-known problem referred to as Knapsack problem. Although the same problem could be solved by employing other algorithmic approaches, Greedy approach solves Fractional Knapsack problem reasonably in a good time. Let us discuss the Knapsack problem in detail." }, { "code": null, "e": 3137, "s": 2919, "text": "Given a set of items, each with a weight and a value, determine a subset of items to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible." }, { "code": null, "e": 3497, "s": 3137, "text": "The knapsack problem is in combinatorial optimization problem. It appears as a subproblem in many, more complex mathematical models of real-world problems. One general approach to difficult problems is to identify the most restrictive constraint, ignore the others, solve a knapsack problem, and somehow adjust the solution to satisfy the ignored constraints." }, { "code": null, "e": 3658, "s": 3497, "text": "In many cases of resource allocation along with some constraint, the problem can be derived in a similar way of Knapsack problem. Following is a set of example." }, { "code": null, "e": 3710, "s": 3658, "text": "Finding the least wasteful way to cut raw materials" }, { "code": null, "e": 3733, "s": 3710, "text": "portfolio optimization" }, { "code": null, "e": 3756, "s": 3733, "text": "Cutting stock problems" }, { "code": null, "e": 3964, "s": 3756, "text": "A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n items available in the store and weight of ith item is wi and its profit is pi. What items should the thief take?" }, { "code": null, "e": 4162, "s": 3964, "text": "In this context, the items should be selected in such a way that the thief will carry those items for which he will gain maximum profit. Hence, the objective of the thief is to maximize the profit." }, { "code": null, "e": 4233, "s": 4162, "text": "Based on the nature of the items, Knapsack problems are categorized as" }, { "code": null, "e": 4253, "s": 4233, "text": "Fractional Knapsack" }, { "code": null, "e": 4262, "s": 4253, "text": "Knapsack" }, { "code": null, "e": 4364, "s": 4262, "text": "In this case, items can be broken into smaller pieces, hence the thief can select fractions of items." }, { "code": null, "e": 4400, "s": 4364, "text": "According to the problem statement," }, { "code": null, "e": 4431, "s": 4400, "text": "There are n items in the store" }, { "code": null, "e": 4462, "s": 4431, "text": "There are n items in the store" }, { "code": null, "e": 4486, "s": 4462, "text": "Weight of ith item wi>0" }, { "code": null, "e": 4510, "s": 4486, "text": "Weight of ith item wi>0" }, { "code": null, "e": 4539, "s": 4510, "text": "Profit for ith item pi>0 and" }, { "code": null, "e": 4568, "s": 4539, "text": "Profit for ith item pi>0 and" }, { "code": null, "e": 4598, "s": 4568, "text": "Capacity of the Knapsack is W" }, { "code": null, "e": 4628, "s": 4598, "text": "Capacity of the Knapsack is W" }, { "code": null, "e": 4761, "s": 4628, "text": "In this version of Knapsack problem, items can be broken into smaller pieces. So, the thief may take only a fraction xi of ith item." }, { "code": null, "e": 4768, "s": 4761, "text": "0⩽xi⩽1" }, { "code": null, "e": 4884, "s": 4768, "text": "The ith item contributes the weight xi.wi to the total weight in the knapsack and profit xi.pi to the total profit." }, { "code": null, "e": 4929, "s": 4884, "text": "Hence, the objective of this algorithm is to" }, { "code": null, "e": 4950, "s": 4929, "text": "maximize∑n=1n(xi.pi)" }, { "code": null, "e": 4973, "s": 4950, "text": "subject to constraint," }, { "code": null, "e": 4988, "s": 4973, "text": "∑n=1n(xi.wi)⩽W" }, { "code": null, "e": 5154, "s": 4988, "text": "It is clear that an optimal solution must fill the knapsack exactly, otherwise we could add a fraction of one of the remaining items and increase the overall profit." }, { "code": null, "e": 5199, "s": 5154, "text": "Thus, an optimal solution can be obtained by" }, { "code": null, "e": 5214, "s": 5199, "text": "∑n=1n(xi.wi)=W" }, { "code": null, "e": 5375, "s": 5214, "text": "In this context, first we need to sort those items according to the value of piwi, so that pi+1wi+1 ≤ piwi . Here, x is an array to store the fraction of items." }, { "code": null, "e": 5657, "s": 5375, "text": "Algorithm: Greedy-Fractional-Knapsack (w[1..n], p[1..n], W) \nfor i = 1 to n \n do x[i] = 0 \nweight = 0 \nfor i = 1 to n \n if weight + w[i] ≤ W then \n x[i] = 1 \n weight = weight + w[i] \n else \n x[i] = (W - weight) / w[i] \n weight = W \n break \nreturn x\n" }, { "code": null, "e": 5834, "s": 5657, "text": "If the provided items are already sorted into a decreasing order of piwi, then the whileloop takes a time in O(n); Therefore, the total time including the sort is in O(n logn)." }, { "code": null, "e": 5957, "s": 5834, "text": "Let us consider that the capacity of the knapsack W = 60 and the list of provided items are shown in the following table −" }, { "code": null, "e": 6071, "s": 5957, "text": "As the provided items are not sorted based on piwi. After sorting, the items are as shown in the following table." }, { "code": null, "e": 6448, "s": 6071, "text": "After sorting all the items according to piwi. First all of B is chosen as weight of B is less than the capacity of the knapsack. Next, item A is chosen, as the available capacity of the knapsack is greater than the weight of A. Now, C is chosen as the next item. However, the whole item cannot be chosen as the remaining capacity of the knapsack is less than the weight of C." }, { "code": null, "e": 6500, "s": 6448, "text": "Hence, fraction of C (i.e. (60 − 50)/20) is chosen." }, { "code": null, "e": 6603, "s": 6500, "text": "Now, the capacity of the Knapsack is equal to the selected items. Hence, no more item can be selected." }, { "code": null, "e": 6674, "s": 6603, "text": "The total weight of the selected items is 10 + 40 + 20 * (10/20) = 60" }, { "code": null, "e": 6741, "s": 6674, "text": "And the total profit is 100 + 280 + 120 * (10/20) = 380 + 60 = 440" }, { "code": null, "e": 6845, "s": 6741, "text": "This is the optimal solution. We cannot gain more profit selecting any different combination of items. " }, { "code": null, "e": 6880, "s": 6845, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 6899, "s": 6880, "text": " Arnab Chakraborty" }, { "code": null, "e": 6932, "s": 6899, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 6951, "s": 6932, "text": " Arnab Chakraborty" }, { "code": null, "e": 6984, "s": 6951, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 7003, "s": 6984, "text": " Arnab Chakraborty" }, { "code": null, "e": 7038, "s": 7003, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7051, "s": 7038, "text": " Manoj Kumar" }, { "code": null, "e": 7083, "s": 7051, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 7096, "s": 7083, "text": " Zach Miller" }, { "code": null, "e": 7129, "s": 7096, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 7143, "s": 7129, "text": " Sasha Miller" }, { "code": null, "e": 7150, "s": 7143, "text": " Print" }, { "code": null, "e": 7161, "s": 7150, "text": " Add Notes" } ]
VueJS - Render Function
We have seen components and the usage of it. For example, we have a content that needs to be reused across the project. We can convert the same as a component and use it. Let’s take a look at an example of a simple component and see what the render function has to do within it. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "component_test"> <testcomponent></testcomponent> </div> <script type = "text/javascript"> Vue.component('testcomponent',{ template : '<h1>Hello World</h1>', data: function() { }, methods:{ } }); var vm = new Vue({ el: '#component_test' }); </script> </body> </html> Consider the above example of a simple component that prints Hello World as shown in the following screenshot. Now, if we want to reuse the component, we can do so by just printing it again. For example, <div id = "component_test"> <testcomponent></testcomponent> <testcomponent></testcomponent> <testcomponent></testcomponent> <testcomponent></testcomponent> </div> And the output will be the following. However, now we need some changes to the component. We don’t want the same text to be printed. How can we change it? In case, we type something inside the component, will it be take into consideration? Let us consider the following example and see what happens. <div id = "component_test"> <testcomponent>Hello Jai</testcomponent> <testcomponent>Hello Roy</testcomponent> <testcomponent>Hello Ria</testcomponent> <testcomponent>Hello Ben</testcomponent> </div> The output remains the same as we had seen earlier. It does not change the text as we want. Component does provide something called as slots. Let’s make use of it and see if we get the desired results. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "component_test"> <testcomponent>Hello Jai</testcomponent> <testcomponent>Hello Roy</testcomponent> <testcomponent>Hello Ria</testcomponent> <testcomponent>Hello Ben</testcomponent> </div> <script type = "text/javascript"> Vue.component('testcomponent',{ template : '<h1><slot></slot></h1>', data: function() { }, methods:{ } }); var vm = new Vue({ el: '#component_test' }); </script> </body> </html> As seen in the above code, in the template we have added slot, hence now it takes the value to send inside the component as shown in the following screenshot. Now, let us consider we want to change the color and size. For example, currently we are using h1 tag and we want to change the HTML tag to p tag or div tag for the same component. How can we have the flexibility to carry out so many changes? We can do so with the help of the render function. Render function helps make the component dynamic and use the way it is required by keeping it common and helping pass arguments using the same component. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "component_test"> <testcomponent :elementtype = "'div,red,25,div1'">Hello Jai</testcomponent> <testcomponent :elementtype = "'h3,green,25,h3tag'">Hello Roy</testcomponent> <testcomponent :elementtype = "'p,blue,25,ptag'">Hello Ria</testcomponent> <testcomponent :elementtype = "'div,green,25,divtag'">Hello Ben</testcomponent> </div> <script type = "text/javascript"> Vue.component('testcomponent',{ render :function(createElement){ var a = this.elementtype.split(","); return createElement(a[0],{ attrs:{ id:a[3], style:"color:"+a[1]+";font-size:"+a[2]+";" } }, this.$slots.default ) }, props:{ elementtype:{ attributes:String, required:true } } }); var vm = new Vue({ el: '#component_test' }); </script> </body> </html> In the above code, we have changed the component and added the render function with props property using the following piece of code. Vue.component('testcomponent',{ render :function(createElement){ var a = this.elementtype.split(","); return createElement(a[0],{ attrs:{ id:a[3], style:"color:"+a[1]+";font-size:"+a[2]+";" } }, this.$slots.default ) }, props:{ elementtype:{ attributes:String, required:true } } }); The props look like the following. props:{ elementtype:{ attributes:String, required:true } } We have defined a property called elementtype, which takes attributes field of type string. Another required field, which mentions that the field is mandatory. In the render function, we have used the elementtype property as seen in the following piece of code. render :function(createElement){ var a = this.elementtype.split(","); return createElement(a[0],{ attrs:{ id:a[3], style:"color:"+a[1]+";font-size:"+a[2]+";" } }, this.$slots.default ) } Render function takes createElement as the argument and returns the same. CreateElement creates the DOM element the same way as in JavaScript. We have also split the elementtype on comma, using the values in the attrs field. CreateElement is taking the first param as the elementtag to be created. It is passed to the component using the following piece of code. <testcomponent :elementtype = "'div,red,25,div1'">Hello Jai</testcomponent> The component needs to take the props field as shown above. It starts with : and the name of the props. Here, we are passing the element tag, color, fontsize, and the id of the element. In render function, in createElement, we are splitting on comma, so the first element is the elementtag, which is given to the createElemet as shown in the following piece of code. return createElement( a[0],{ attrs:{ id:a[3], style:"color:"+a[1]+";font-size:"+a[2]+";" } }, this.$slots.default ) a[0] is the html element tag. The next parameter is the attributes for the element tag. They are defined in the attr field in the following piece of code. attrs:{ id:a[3], style:"color:"+a[1]+";font-size:"+a[2]+";" } We have defined two attributes for the element tag - id and style. To id, we are passing a[3], which is the value we have after splitting on comma. Using style, we have defined color and fontsize. Last is the slot, that is the message we have given in the componentin the following piece of code. <testcomponent :elementtype = "'div,red,25,div1'">Hello Jai</testcomponent> We have defined the text to be printed in the createElement using the following piece of code. this.$slots.default It takes the default assigned in the component field. Following is the output we get in the browser. The elements also show the structure. These are the components we have defined − <div id = "component_test"> <testcomponent :elementtype = "'div,red,25,div1'">Hello Jai</testcomponent> <testcomponent :elementtype = "'h3,green,25,h3tag'">Hello Roy</testcomponent> <testcomponent :elementtype = "'p,blue,25,ptag'">Hello Ria</testcomponent> <testcomponent :elementtype = "'div,green,25,divtag'">Hello Ben</testcomponent> </div> Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 1936, "text": "We have seen components and the usage of it. For example, we have a content that needs to be reused across the project. We can convert the same as a component and use it." }, { "code": null, "e": 2215, "s": 2107, "text": "Let’s take a look at an example of a simple component and see what the render function has to do within it." }, { "code": null, "e": 2777, "s": 2215, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"component_test\">\n <testcomponent></testcomponent>\n </div>\n <script type = \"text/javascript\">\n Vue.component('testcomponent',{\n template : '<h1>Hello World</h1>',\n data: function() {\n },\n methods:{\n }\n });\n var vm = new Vue({\n el: '#component_test'\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 2888, "s": 2777, "text": "Consider the above example of a simple component that prints Hello World as shown in the following screenshot." }, { "code": null, "e": 2981, "s": 2888, "text": "Now, if we want to reuse the component, we can do so by just printing it again. For example," }, { "code": null, "e": 3156, "s": 2981, "text": "<div id = \"component_test\">\n <testcomponent></testcomponent>\n <testcomponent></testcomponent>\n <testcomponent></testcomponent>\n <testcomponent></testcomponent>\n</div>" }, { "code": null, "e": 3194, "s": 3156, "text": "And the output will be the following." }, { "code": null, "e": 3396, "s": 3194, "text": "However, now we need some changes to the component. We don’t want the same text to be printed. How can we change it? In case, we type something inside the component, will it be take into consideration?" }, { "code": null, "e": 3456, "s": 3396, "text": "Let us consider the following example and see what happens." }, { "code": null, "e": 3667, "s": 3456, "text": "<div id = \"component_test\">\n <testcomponent>Hello Jai</testcomponent>\n <testcomponent>Hello Roy</testcomponent>\n <testcomponent>Hello Ria</testcomponent>\n <testcomponent>Hello Ben</testcomponent>\n</div>" }, { "code": null, "e": 3759, "s": 3667, "text": "The output remains the same as we had seen earlier. It does not change the text as we want." }, { "code": null, "e": 3869, "s": 3759, "text": "Component does provide something called as slots. Let’s make use of it and see if we get the desired results." }, { "code": null, "e": 4592, "s": 3869, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"component_test\">\n <testcomponent>Hello Jai</testcomponent>\n <testcomponent>Hello Roy</testcomponent>\n <testcomponent>Hello Ria</testcomponent>\n <testcomponent>Hello Ben</testcomponent>\n </div>\n <script type = \"text/javascript\">\n Vue.component('testcomponent',{\n template : '<h1><slot></slot></h1>',\n data: function() {\n },\n methods:{\n }\n });\n var vm = new Vue({\n el: '#component_test'\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 4751, "s": 4592, "text": "As seen in the above code, in the template we have added slot, hence now it takes the value to send inside the component as shown in the following screenshot." }, { "code": null, "e": 4994, "s": 4751, "text": "Now, let us consider we want to change the color and size. For example, currently we are using h1 tag and we want to change the HTML tag to p tag or div tag for the same component. How can we have the flexibility to carry out so many changes?" }, { "code": null, "e": 5199, "s": 4994, "text": "We can do so with the help of the render function. Render function helps make the component dynamic and use the way it is required by keeping it common and helping pass arguments using the same component." }, { "code": null, "e": 6450, "s": 5199, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"component_test\">\n <testcomponent :elementtype = \"'div,red,25,div1'\">Hello Jai</testcomponent>\n <testcomponent :elementtype = \"'h3,green,25,h3tag'\">Hello Roy</testcomponent>\n <testcomponent :elementtype = \"'p,blue,25,ptag'\">Hello Ria</testcomponent>\n <testcomponent :elementtype = \"'div,green,25,divtag'\">Hello Ben</testcomponent>\n </div>\n <script type = \"text/javascript\">\n Vue.component('testcomponent',{\n render :function(createElement){\n var a = this.elementtype.split(\",\");\n return createElement(a[0],{\n attrs:{\n id:a[3],\n style:\"color:\"+a[1]+\";font-size:\"+a[2]+\";\"\n }\n },\n this.$slots.default\n )\n },\n props:{\n elementtype:{\n attributes:String,\n required:true\n }\n }\n });\n var vm = new Vue({\n el: '#component_test'\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 6584, "s": 6450, "text": "In the above code, we have changed the component and added the render function with props property using the following piece of code." }, { "code": null, "e": 6981, "s": 6584, "text": "Vue.component('testcomponent',{\n render :function(createElement){\n var a = this.elementtype.split(\",\");\n return createElement(a[0],{\n attrs:{\n id:a[3],\n style:\"color:\"+a[1]+\";font-size:\"+a[2]+\";\"\n }\n },\n this.$slots.default\n )\n },\n props:{\n elementtype:{\n attributes:String,\n required:true\n }\n }\n});" }, { "code": null, "e": 7016, "s": 6981, "text": "The props look like the following." }, { "code": null, "e": 7093, "s": 7016, "text": "props:{\n elementtype:{\n attributes:String,\n required:true\n }\n}" }, { "code": null, "e": 7253, "s": 7093, "text": "We have defined a property called elementtype, which takes attributes field of type string. Another required field, which mentions that the field is mandatory." }, { "code": null, "e": 7355, "s": 7253, "text": "In the render function, we have used the elementtype property as seen in the following piece of code." }, { "code": null, "e": 7587, "s": 7355, "text": "render :function(createElement){\n var a = this.elementtype.split(\",\");\n return createElement(a[0],{\n attrs:{\n id:a[3],\n style:\"color:\"+a[1]+\";font-size:\"+a[2]+\";\"\n }\n },\n this.$slots.default\n )\n}" }, { "code": null, "e": 7813, "s": 7587, "text": "Render function takes createElement as the argument and returns the same. CreateElement creates the DOM element the same way as in JavaScript. We have also split the elementtype on comma, using the values in the attrs field." }, { "code": null, "e": 7951, "s": 7813, "text": "CreateElement is taking the first param as the elementtag to be created. It is passed to the component using the following piece of code." }, { "code": null, "e": 8028, "s": 7951, "text": "<testcomponent :elementtype = \"'div,red,25,div1'\">Hello Jai</testcomponent>" }, { "code": null, "e": 8214, "s": 8028, "text": "The component needs to take the props field as shown above. It starts with : and the name of the props. Here, we are passing the element tag, color, fontsize, and the id of the element." }, { "code": null, "e": 8395, "s": 8214, "text": "In render function, in createElement, we are splitting on comma, so the first element is the elementtag, which is given to the createElemet as shown in the following piece of code." }, { "code": null, "e": 8550, "s": 8395, "text": "return createElement(\n a[0],{\n attrs:{\n id:a[3],\n style:\"color:\"+a[1]+\";font-size:\"+a[2]+\";\"\n }\n },\n this.$slots.default\n)" }, { "code": null, "e": 8705, "s": 8550, "text": "a[0] is the html element tag. The next parameter is the attributes for the element tag. They are defined in the attr field in the following piece of code." }, { "code": null, "e": 8773, "s": 8705, "text": "attrs:{\n id:a[3],\n style:\"color:\"+a[1]+\";font-size:\"+a[2]+\";\"\n}" }, { "code": null, "e": 8970, "s": 8773, "text": "We have defined two attributes for the element tag - id and style. To id, we are passing a[3], which is the value we have after splitting on comma. Using style, we have defined color and fontsize." }, { "code": null, "e": 9070, "s": 8970, "text": "Last is the slot, that is the message we have given in the componentin the following piece of code." }, { "code": null, "e": 9146, "s": 9070, "text": "<testcomponent :elementtype = \"'div,red,25,div1'\">Hello Jai</testcomponent>" }, { "code": null, "e": 9241, "s": 9146, "text": "We have defined the text to be printed in the createElement using the following piece of code." }, { "code": null, "e": 9261, "s": 9241, "text": "this.$slots.default" }, { "code": null, "e": 9315, "s": 9261, "text": "It takes the default assigned in the component field." }, { "code": null, "e": 9362, "s": 9315, "text": "Following is the output we get in the browser." }, { "code": null, "e": 9443, "s": 9362, "text": "The elements also show the structure. These are the components we have defined −" }, { "code": null, "e": 9799, "s": 9443, "text": "<div id = \"component_test\">\n <testcomponent :elementtype = \"'div,red,25,div1'\">Hello Jai</testcomponent>\n <testcomponent :elementtype = \"'h3,green,25,h3tag'\">Hello Roy</testcomponent>\n <testcomponent :elementtype = \"'p,blue,25,ptag'\">Hello Ria</testcomponent>\n <testcomponent :elementtype = \"'div,green,25,divtag'\">Hello Ben</testcomponent>\n</div>" }, { "code": null, "e": 9806, "s": 9799, "text": " Print" }, { "code": null, "e": 9817, "s": 9806, "text": " Add Notes" } ]
Find Sum, Mean and Product of a Vector in R - GeeksforGeeks
26 Mar, 2021 sum(), mean(), and prod() methods are available in R which are used to compute the specified operation over the arguments specified in the method. In case, a single vector is specified, then the operation is performed over individual elements, which is equivalent to the application of for loop. mean() function is used to calculate mean Syntax: mean(x, na.rm) Parameters: x: Numeric Vector na.rm: Boolean value to ignore NA value sum() is used to calculate sum Syntax: sum(x) Parameters: x: Numeric Vector prod() is used to calculate product Syntax: prod(x) Parameters: x: Numeric Vector Given below are examples to help you understand better. Example 1: R vec = c(1, 2, 3 , 4) print("Sum of the vector:") # inbuilt sum method print(sum(vec)) # using inbuilt mean method print("Mean of the vector:") print(mean(vec)) # using inbuilt product method print("Product of the vector:") print(prod(vec)) Output [1] “Sum of the vector:” [1] 10 [1] “Mean of the vector:” [1] 2.5 [1] “Product of the vector:” [1] 24 Example 2: R vec = c(1.1, 2, 3.0 ) print("Sum of the vector:") # inbuilt sum method print(sum(vec)) # using inbuilt mean method print("Mean of the vector:") print(mean(vec)) # using inbuilt product method print("Product of the vector:") print(prod(vec)) Output [1] “Sum of the vector:” [1] 6.1 [1] “Mean of the vector:” [1] 2.033333 [1] “Product of the vector:” [1] 6.6 Example 3 : Vector with NaN values R # declaring a vector vec = c(1.1,NA, 2, 3.0,NA ) print("Sum of the vector:") # inbuilt sum method print(sum(vec)) # using inbuilt mean method print("Mean of the vector with NaN values:") # not ignoring NaN values print(mean(vec)) # ignoring missing values print("Mean of the vector without NaN values:") print(mean(vec,na.rm = TRUE)) # using inbuilt product method print("Product of the vector:") print(prod(vec)) Output [1] “Sum of the vector:” [1] NA [1] “Mean of the vector with NaN values:” [1] NA [1] “Mean of the vector without NaN values:” [1] 2.033333 [1] “Product of the vector:” [1] NA Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? How to change Row Names of DataFrame in R ? How to Split Column Into Multiple Columns in R DataFrame? Remove rows with NA in one column of R DataFrame Replace Specific Characters in String in R How to filter R DataFrame by values in a column?
[ { "code": null, "e": 24634, "s": 24603, "text": " \n26 Mar, 2021\n" }, { "code": null, "e": 24931, "s": 24634, "text": "sum(), mean(), and prod() methods are available in R which are used to compute the specified operation over the arguments specified in the method. In case, a single vector is specified, then the operation is performed over individual elements, which is equivalent to the application of for loop. " }, { "code": null, "e": 24973, "s": 24931, "text": "mean() function is used to calculate mean" }, { "code": null, "e": 24996, "s": 24973, "text": "Syntax: mean(x, na.rm)" }, { "code": null, "e": 25008, "s": 24996, "text": "Parameters:" }, { "code": null, "e": 25026, "s": 25008, "text": "x: Numeric Vector" }, { "code": null, "e": 25066, "s": 25026, "text": "na.rm: Boolean value to ignore NA value" }, { "code": null, "e": 25097, "s": 25066, "text": "sum() is used to calculate sum" }, { "code": null, "e": 25112, "s": 25097, "text": "Syntax: sum(x)" }, { "code": null, "e": 25124, "s": 25112, "text": "Parameters:" }, { "code": null, "e": 25142, "s": 25124, "text": "x: Numeric Vector" }, { "code": null, "e": 25178, "s": 25142, "text": "prod() is used to calculate product" }, { "code": null, "e": 25194, "s": 25178, "text": "Syntax: prod(x)" }, { "code": null, "e": 25206, "s": 25194, "text": "Parameters:" }, { "code": null, "e": 25224, "s": 25206, "text": "x: Numeric Vector" }, { "code": null, "e": 25280, "s": 25224, "text": "Given below are examples to help you understand better." }, { "code": null, "e": 25291, "s": 25280, "text": "Example 1:" }, { "code": null, "e": 25293, "s": 25291, "text": "R" }, { "code": "\n\n\n\n\n\n\nvec = c(1, 2, 3 , 4) \nprint(\"Sum of the vector:\") \n \n# inbuilt sum method \nprint(sum(vec)) \n \n# using inbuilt mean method \nprint(\"Mean of the vector:\") \nprint(mean(vec)) \n \n# using inbuilt product method \nprint(\"Product of the vector:\") \nprint(prod(vec))\n\n\n\n\n\n", "e": 25577, "s": 25303, "text": null }, { "code": null, "e": 25584, "s": 25577, "text": "Output" }, { "code": null, "e": 25609, "s": 25584, "text": "[1] “Sum of the vector:”" }, { "code": null, "e": 25616, "s": 25609, "text": "[1] 10" }, { "code": null, "e": 25642, "s": 25616, "text": "[1] “Mean of the vector:”" }, { "code": null, "e": 25650, "s": 25642, "text": "[1] 2.5" }, { "code": null, "e": 25679, "s": 25650, "text": "[1] “Product of the vector:”" }, { "code": null, "e": 25686, "s": 25679, "text": "[1] 24" }, { "code": null, "e": 25697, "s": 25686, "text": "Example 2:" }, { "code": null, "e": 25699, "s": 25697, "text": "R" }, { "code": "\n\n\n\n\n\n\nvec = c(1.1, 2, 3.0 ) \nprint(\"Sum of the vector:\") \n \n# inbuilt sum method \nprint(sum(vec)) \n \n# using inbuilt mean method \nprint(\"Mean of the vector:\") \nprint(mean(vec)) \n \n# using inbuilt product method \nprint(\"Product of the vector:\") \nprint(prod(vec))\n\n\n\n\n\n", "e": 25984, "s": 25709, "text": null }, { "code": null, "e": 25991, "s": 25984, "text": "Output" }, { "code": null, "e": 26016, "s": 25991, "text": "[1] “Sum of the vector:”" }, { "code": null, "e": 26024, "s": 26016, "text": "[1] 6.1" }, { "code": null, "e": 26050, "s": 26024, "text": "[1] “Mean of the vector:”" }, { "code": null, "e": 26063, "s": 26050, "text": "[1] 2.033333" }, { "code": null, "e": 26092, "s": 26063, "text": "[1] “Product of the vector:”" }, { "code": null, "e": 26100, "s": 26092, "text": "[1] 6.6" }, { "code": null, "e": 26136, "s": 26100, "text": "Example 3 : Vector with NaN values " }, { "code": null, "e": 26138, "s": 26136, "text": "R" }, { "code": "\n\n\n\n\n\n\n# declaring a vector \nvec = c(1.1,NA, 2, 3.0,NA ) \nprint(\"Sum of the vector:\") \n \n# inbuilt sum method \nprint(sum(vec)) \n \n# using inbuilt mean method \nprint(\"Mean of the vector with NaN values:\") \n \n# not ignoring NaN values \nprint(mean(vec)) \n \n# ignoring missing values \nprint(\"Mean of the vector without NaN values:\") \nprint(mean(vec,na.rm = TRUE)) \n \n# using inbuilt product method \nprint(\"Product of the vector:\") \nprint(prod(vec))\n\n\n\n\n\n", "e": 26609, "s": 26148, "text": null }, { "code": null, "e": 26616, "s": 26609, "text": "Output" }, { "code": null, "e": 26641, "s": 26616, "text": "[1] “Sum of the vector:”" }, { "code": null, "e": 26648, "s": 26641, "text": "[1] NA" }, { "code": null, "e": 26690, "s": 26648, "text": "[1] “Mean of the vector with NaN values:”" }, { "code": null, "e": 26697, "s": 26690, "text": "[1] NA" }, { "code": null, "e": 26742, "s": 26697, "text": "[1] “Mean of the vector without NaN values:”" }, { "code": null, "e": 26755, "s": 26742, "text": "[1] 2.033333" }, { "code": null, "e": 26784, "s": 26755, "text": "[1] “Product of the vector:”" }, { "code": null, "e": 26791, "s": 26784, "text": "[1] NA" }, { "code": null, "e": 26800, "s": 26791, "text": "\nPicked\n" }, { "code": null, "e": 26820, "s": 26800, "text": "\nR Vector-Programs\n" }, { "code": null, "e": 26832, "s": 26820, "text": "\nR-Vectors\n" }, { "code": null, "e": 26845, "s": 26832, "text": "\nR Language\n" }, { "code": null, "e": 26858, "s": 26845, "text": "\nR Programs\n" }, { "code": null, "e": 27063, "s": 26858, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27107, "s": 27063, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27159, "s": 27107, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27191, "s": 27159, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27243, "s": 27191, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27281, "s": 27243, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27325, "s": 27281, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27383, "s": 27325, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27432, "s": 27383, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 27475, "s": 27432, "text": "Replace Specific Characters in String in R" } ]
How to Enable or Install Byobu for Terminal Management on Ubuntu 16.04
In this article, we will learn about Byobu on the Ubuntu 16.04, Byobu which is a terminal multiplexer and easy to use, Byobu is used to have multiple windows, consoles and split panes within the windows and will also show the status badges and notifications on the terminal. To complete this tutorial we needed an Ubuntu 16.04 installed and a Linux user with sudo permissions. As a default feature of Ubuntu 16.04, Byobu is installed. However, as a practice, we will check the installation and version and if not we will install the Byobu. To check the Byobu is installed and also to find out the version we will use the below command $ byobu --version byobu version 5.106 tmux 2.1 If we are unable to see the current version or the command not found error displayed – $ byobu –version -bash: /usr/bin/byobu: No such file or directory As we don’t have the Byobu installed on our machine, to install the Byobu we needed to run the below command – $ sudo apt-get install byobu. Reading package lists... Done Building dependency tree Reading state information... Done Note, selecting 'byobu-extras' for regex 'byobu.' Note, selecting 'byobu' instead of 'byobu-extras' Suggested packages: ccze gnome-terminal po-debconf ttf-ubuntu-font-family wireless-tools The following NEW packages will be installed: byobu 0 upgraded, 1 newly installed, 0 to remove and 81 not upgraded. Need to get 105 kB of archives. After this operation, 654 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 byobu all 5.106-0ubuntu1 [105 kB] Fetched 105 kB in 1s (83.6 kB/s) Preconfiguring packages ... Selecting previously unselected package byobu. (Reading database ... 89994 files and directories currently installed.) Preparing to unpack .../byobu_5.106-0ubuntu1_all.deb ... Unpacking byobu (5.106-0ubuntu1) ... Setting up byobu (5.106-0ubuntu1) ... Now the Byobu is installed on the Ubuntu Byobu is disabled by default after the installation, we needed to enable the Byobu, and we have two ways to enable the Byobu. One is we can start the Byobu every time we needed or we can start the Byobu at the time of login or boot. To Start the Bybou, we can just use the below command automatically and the environment will be changed. $ byobu If we want to start the byobu to our login profile, we needed to enable by using the below command $ byobu–enable The Byobu window manager will be launched automatically at each text login. To disable this behavior later, just run: $ byobu-disable And if we want to stop using the byobu, just we can use the byobu-disable command to stop using the Byobu. By default, the Byobu will use the tmux as the backend multiplexer, if we want to change the multiplexer to screen we can use the below command – $ byobu-select-backend Select the byobu backend: tmux screen By default the tmux is enabled and if we want to change the multiplexer we can choose the screen Byobu has a good feature included with colorful prompt, which also includes the return code of the last executed command. We can use the below command to enable this feature – $ byobu-enable-prompt . ~/.bashrc root@ubuntu-16:~# . ~/.bashrc See the below image for the changes in the shell As we have configured the Byobu to get ready for use. As Byobu uses the default keybindis from F1 through F12 the default keyboard function keys. Byobu has many features like sessions, panes and windows. We start the sessions so that we can have our own window size with connections to the multiple devices with different screen sizes. We can start a new session using Ctrl+Shift+F2 and we can use Alt+UP ad Alt+Down to move forward and backward of the opened sessions. Ctrl+ D -> to exit from Byobu and close all the session we connected. F6 - > Will logout the current session and log you out of the SSH connection. Shift+F6 - > This will be used to detach the session, but the SSH connection will remain connected. Byobu has the ability of switching between the windows within in a single session, which will allow us to do the multi-tasks easily with a single connection. F2 → Will be used to open a new window with a new command prompt and can be used to do the multiple tasks. F3 & F4 is used to scroll the windows up and down respectively. F8 → To add names to the current windows. Ctrl+Shift+ F3 or F4 → To move the current windows left or right through the list for respectively. F7 → Scrollback the history. Byobu also provides the ability to split the windows into a multiple panes in both directions vertical and horizontal splits. Shift+F2 -> To split the current windows into horizontal splits. Ctrl+F2 - > To split the panes into vertical. Shift+F11 - > To Zoom the windows and back again. Alt+F11 -> To split a pane in a new window. We have to press the F9 key to enable the status notifications. When we press F9 key, then the Byobu configuration menu will be displayed and we needed to select the Toggle status notification press Enter key, we can see a list of available options on the screen we can enable them by selecting the options. After we select the options which are available, then select the Apply and exit from the menu, press F5 to refresh the status bar as the notifications are useful to see the information about the system. Here are the some of the options available with the status notification in the Byobu arch -> shows notification in the system architecture. battery -> shows notification for the current battery level for laptops. date -> shows notification of the current system date. disk -> shows the notification for current disk space usage. hostname -> shows the notification for a current system hostname. ip_address -> notification for shows the current system IP address. load_average -> shows the notification for current system load average. memory -> shows the notification for current memory usage. network -> shows the notification for current network usage, sending and receiving. reboot_required -> shows notification for an indicator when a system reboot is required. release -> shows the notification for current distribution version (e.g. 14.04). time -> shows the notification for current system time. updates_available -> shows notification for an indicator when there are updates available. uptime -> shows the notification for current system uptime. whoami -> shows the notification for currently logged in user. In the above article we can see a wide range of functions and we have covered some of the functions available with the Byobu, we can use these functions which fit into your environment and get the things done easily and quickly.
[ { "code": null, "e": 1337, "s": 1062, "text": "In this article, we will learn about Byobu on the Ubuntu 16.04, Byobu which is a terminal multiplexer and easy to use, Byobu is used to have multiple windows, consoles and split panes within the windows and will also show the status badges and notifications on the terminal." }, { "code": null, "e": 1439, "s": 1337, "text": "To complete this tutorial we needed an Ubuntu 16.04 installed and a Linux user with sudo permissions." }, { "code": null, "e": 1602, "s": 1439, "text": "As a default feature of Ubuntu 16.04, Byobu is installed. However, as a practice, we will check the installation and version and if not we will install the Byobu." }, { "code": null, "e": 1697, "s": 1602, "text": "To check the Byobu is installed and also to find out the version we will use the below command" }, { "code": null, "e": 1744, "s": 1697, "text": "$ byobu --version\nbyobu version 5.106\ntmux 2.1" }, { "code": null, "e": 1831, "s": 1744, "text": "If we are unable to see the current version or the command not found error displayed –" }, { "code": null, "e": 1897, "s": 1831, "text": "$ byobu –version\n-bash: /usr/bin/byobu: No such file or directory" }, { "code": null, "e": 2008, "s": 1897, "text": "As we don’t have the Byobu installed on our machine, to install the Byobu we needed to run the below command –" }, { "code": null, "e": 2979, "s": 2008, "text": "$ sudo apt-get install byobu.\nReading package lists... Done\nBuilding dependency tree\nReading state information... Done\nNote, selecting 'byobu-extras' for regex 'byobu.'\nNote, selecting 'byobu' instead of 'byobu-extras'\nSuggested packages:\nccze gnome-terminal po-debconf ttf-ubuntu-font-family wireless-tools\nThe following NEW packages will be installed:\nbyobu\n0 upgraded, 1 newly installed, 0 to remove and 81 not upgraded.\nNeed to get 105 kB of archives.\nAfter this operation, 654 kB of additional disk space will be used.\nGet:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 byobu all 5.106-0ubuntu1 [105 kB]\nFetched 105 kB in 1s (83.6 kB/s)\nPreconfiguring packages ...\nSelecting previously unselected package byobu.\n(Reading database ... 89994 files and directories currently installed.)\nPreparing to unpack .../byobu_5.106-0ubuntu1_all.deb ...\nUnpacking byobu (5.106-0ubuntu1) ...\nSetting up byobu (5.106-0ubuntu1) ...\nNow the Byobu is installed on the Ubuntu" }, { "code": null, "e": 3212, "s": 2979, "text": "Byobu is disabled by default after the installation, we needed to enable the Byobu, and we have two ways to enable the Byobu. One is we can start the Byobu every time we needed or we can start the Byobu at the time of login or boot." }, { "code": null, "e": 3317, "s": 3212, "text": "To Start the Bybou, we can just use the below command automatically and the environment will be changed." }, { "code": null, "e": 3325, "s": 3317, "text": "$ byobu" }, { "code": null, "e": 3424, "s": 3325, "text": "If we want to start the byobu to our login profile, we needed to enable by using the below command" }, { "code": null, "e": 3439, "s": 3424, "text": "$ byobu–enable" }, { "code": null, "e": 3515, "s": 3439, "text": "The Byobu window manager will be launched automatically at each text login." }, { "code": null, "e": 3557, "s": 3515, "text": "To disable this behavior later, just run:" }, { "code": null, "e": 3573, "s": 3557, "text": "$ byobu-disable" }, { "code": null, "e": 3680, "s": 3573, "text": "And if we want to stop using the byobu, just we can use the byobu-disable command to stop using the Byobu." }, { "code": null, "e": 3826, "s": 3680, "text": "By default, the Byobu will use the tmux as the backend multiplexer, if we want to change the multiplexer to screen we can use the below command –" }, { "code": null, "e": 3875, "s": 3826, "text": "$ byobu-select-backend\nSelect the byobu backend:" }, { "code": null, "e": 3880, "s": 3875, "text": "tmux" }, { "code": null, "e": 3887, "s": 3880, "text": "screen" }, { "code": null, "e": 3984, "s": 3887, "text": "By default the tmux is enabled and if we want to change the multiplexer we can choose the screen" }, { "code": null, "e": 4160, "s": 3984, "text": "Byobu has a good feature included with colorful prompt, which also includes the return code of the last executed command. We can use the below command to enable this feature –" }, { "code": null, "e": 4224, "s": 4160, "text": "$ byobu-enable-prompt\n. ~/.bashrc\nroot@ubuntu-16:~# . ~/.bashrc" }, { "code": null, "e": 4273, "s": 4224, "text": "See the below image for the changes in the shell" }, { "code": null, "e": 4327, "s": 4273, "text": "As we have configured the Byobu to get ready for use." }, { "code": null, "e": 4419, "s": 4327, "text": "As Byobu uses the default keybindis from F1 through F12 the default keyboard function keys." }, { "code": null, "e": 4477, "s": 4419, "text": "Byobu has many features like sessions, panes and windows." }, { "code": null, "e": 4743, "s": 4477, "text": "We start the sessions so that we can have our own window size with connections to the multiple devices with different screen sizes. We can start a new session using Ctrl+Shift+F2 and we can use Alt+UP ad Alt+Down to move forward and backward of the opened sessions." }, { "code": null, "e": 4991, "s": 4743, "text": "Ctrl+ D -> to exit from Byobu and close all the session we connected.\nF6 - > Will logout the current session and log you out of the SSH connection.\nShift+F6 - > This will be used to detach the session, but the SSH connection will remain connected." }, { "code": null, "e": 5149, "s": 4991, "text": "Byobu has the ability of switching between the windows within in a single session, which will allow us to do the multi-tasks easily with a single connection." }, { "code": null, "e": 5256, "s": 5149, "text": "F2 → Will be used to open a new window with a new command prompt and can be used to do the multiple tasks." }, { "code": null, "e": 5320, "s": 5256, "text": "F3 & F4 is used to scroll the windows up and down respectively." }, { "code": null, "e": 5374, "s": 5320, "text": "F8 → To add names to the current windows. Ctrl+Shift+" }, { "code": null, "e": 5462, "s": 5374, "text": "F3 or F4 → To move the current windows left or right through the list for respectively." }, { "code": null, "e": 5491, "s": 5462, "text": "F7 → Scrollback the history." }, { "code": null, "e": 5617, "s": 5491, "text": "Byobu also provides the ability to split the windows into a multiple panes in both directions vertical and horizontal splits." }, { "code": null, "e": 5822, "s": 5617, "text": "Shift+F2 -> To split the current windows into horizontal splits.\nCtrl+F2 - > To split the panes into vertical.\nShift+F11 - > To Zoom the windows and back again.\nAlt+F11 -> To split a pane in a new window." }, { "code": null, "e": 6130, "s": 5822, "text": "We have to press the F9 key to enable the status notifications. When we press F9 key, then the Byobu configuration menu will be displayed and we needed to select the Toggle status notification press Enter key, we can see a list of available options on the screen we can enable them by selecting the options." }, { "code": null, "e": 6333, "s": 6130, "text": "After we select the options which are available, then select the Apply and exit from the menu, press F5 to refresh the status bar as the notifications are useful to see the information about the system." }, { "code": null, "e": 6418, "s": 6333, "text": "Here are the some of the options available with the status notification in the Byobu" }, { "code": null, "e": 7451, "s": 6418, "text": "arch -> shows notification in the system architecture.\nbattery -> shows notification for the current battery level for laptops.\ndate -> shows notification of the current system date.\ndisk -> shows the notification for current disk space usage.\nhostname -> shows the notification for a current system hostname.\nip_address -> notification for shows the current system IP address.\nload_average -> shows the notification for current system load average.\nmemory -> shows the notification for current memory usage.\nnetwork -> shows the notification for current network usage, sending and receiving.\nreboot_required -> shows notification for an indicator when a system reboot is required.\nrelease -> shows the notification for current distribution version (e.g. 14.04).\ntime -> shows the notification for current system time.\nupdates_available -> shows notification for an indicator when there are updates available.\nuptime -> shows the notification for current system uptime.\nwhoami -> shows the notification for currently logged in user." }, { "code": null, "e": 7680, "s": 7451, "text": "In the above article we can see a wide range of functions and we have covered some of the functions available with the Byobu, we can use these functions which fit into your environment and get the things done easily and quickly." } ]
How to run PowerShell commands from the command prompt?
To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe. See the sample example, C:\> Powershell.exe -Command "Write-Output 'Hello world'" Hello world Similarly, you can call any command. We will use another example to get service information C:\> Powershell.exe -Command "Get-Service Spooler" Status Name DisplayName ------ ---- ----------- Running Spooler Print Spooler To run multiple commands, C:\> Powershell.exe -Command "Stop-Service Spooler -verbose -passthru; Start-Service Spooler -verbose -passthru" VERBOSE: Performing the operation "Stop-Service" on target "Print Spooler (Spooler)". Status Name DisplayName ------ ---- ----------- Stopped Spooler Print Spooler VERBOSE: Performing the operation "Start-Service" on target "Print Spooler (Spooler)". Running Spooler Print Spooler The above command is similar to, C:\> Powershell.exe Invoke-Command -scriptblock { "Stop-Service Spooler -verbose - passthru; Start-Service Spooler -verbose -passthru" }
[ { "code": null, "e": 1301, "s": 1187, "text": "To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe." }, { "code": null, "e": 1325, "s": 1301, "text": "See the sample example," }, { "code": null, "e": 1395, "s": 1325, "text": "C:\\> Powershell.exe -Command \"Write-Output 'Hello world'\"\nHello world" }, { "code": null, "e": 1487, "s": 1395, "text": "Similarly, you can call any command. We will use another example to get service information" }, { "code": null, "e": 1627, "s": 1487, "text": "C:\\> Powershell.exe -Command \"Get-Service Spooler\"\nStatus Name DisplayName\n------ ---- -----------\nRunning Spooler Print Spooler" }, { "code": null, "e": 1653, "s": 1627, "text": "To run multiple commands," }, { "code": null, "e": 1766, "s": 1653, "text": "C:\\> Powershell.exe -Command \"Stop-Service Spooler -verbose -passthru;\nStart-Service\nSpooler -verbose -passthru\"" }, { "code": null, "e": 2047, "s": 1766, "text": "VERBOSE: Performing the operation \"Stop-Service\" on target \"Print Spooler (Spooler)\".\nStatus Name DisplayName\n------ ---- -----------\nStopped Spooler Print Spooler\nVERBOSE: Performing the operation \"Start-Service\" on target \"Print Spooler (Spooler)\".\nRunning Spooler Print Spooler" }, { "code": null, "e": 2080, "s": 2047, "text": "The above command is similar to," }, { "code": null, "e": 2223, "s": 2080, "text": "C:\\> Powershell.exe Invoke-Command -scriptblock {\n \"Stop-Service Spooler -verbose - passthru;\n Start-Service Spooler -verbose -passthru\"\n}" } ]
Convert String to LowerCase | Practice | GeeksforGeeks
Given a string S. The task is to convert characters of string to lowercase. Example 1: Input: S = "ABCddE" Output: "abcdde" Explanation: A, B, C and E are converted to a, b, c and E thus all uppercase characters of the string converted to lowercase letter. Example 2: Input: S = "LMNOppQQ" Output: "lmnoppqq" Explanation: L, M, N, O, and Q are converted to l, m, n, o and q thus all uppercase characters of the string converted to lowercase letter. Your Task: You dont need to read input or print anything. Complete the function toLower() which takes S as input parameter and returns the converted string. Expected Time Complexity:O(n) Expected Auxiliary Space: O(1) Constraints: 1 <= |S| <= 1000 0 rohitjaroli226 hours ago class Solution { static String toLower(String S) { String str=""; str=S.toLowerCase(); return str; }} 0 bpanchal758 hours ago class Solution { static String toLower(String S) { String s = S.toLowerCase(); return s; }} 0 dwcahtyin16 hours ago CPP class Solution { public: string toLower(string S) { // code here for(auto& s : S){ s = tolower(s); } return S; }}; 0 sojwal2 days ago //JAVA class Solution { static String toLower(String S) { // code here char [] a = S.toCharArray(); for(int i = 0; i < a.length; i++){ if(a[i] <91 && a[i] > 64 ){ a[i] = (char)((int) a[i] + 32); } } return String.valueOf(a); } } 0 balagopen82x66 days ago WITHOUT USING ANY PREDEFINED FUNCTON class Solution { static String toLower(String S) { char [] a= S.toCharArray(); int n= a.length; for(int i=0;i<n;i++) { if(a[i]>='A' && a[i]<='Z') { a[i]=(char)((int)a[i]+32); } } String s=String.valueOf(a); return s; } +1 smartankit19981 week ago Simple Code in JavascripttoLower(arr,n){ //code here return arr.toLowerCase() } 0 yogeshbisht2122 weeks ago //1st method string toLower(string S) { for(int i=0;i<S.size();i++) { if(S[i]>='A' && S[i]<='Z') { S[i]+=32; } } cout<<S;// code here } //2nd method transform(S.begin(),S.end(),S.begin(),::tolower); +1 amkamble222 weeks ago Simple code in java..... class Solution { static String toLower(String S) { // code here return S.toLowerCase(); }} 0 brmdinhata2 weeks ago class Solution { public: string toLower(string S) { transform(S.begin(),S.end(),S.begin(),::tolower); // code here return S; }}; 0 sakshinagdive153 weeks ago For Python3 class Solution: def toLower (ob, S): return S.lower() 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 302, "s": 226, "text": "Given a string S. The task is to convert characters of string to lowercase." }, { "code": null, "e": 313, "s": 302, "text": "Example 1:" }, { "code": null, "e": 484, "s": 313, "text": "Input: S = \"ABCddE\"\nOutput: \"abcdde\"\nExplanation: A, B, C and E are converted to\na, b, c and E thus all uppercase characters \nof the string converted to lowercase letter." }, { "code": null, "e": 495, "s": 484, "text": "Example 2:" }, { "code": null, "e": 679, "s": 495, "text": "Input: S = \"LMNOppQQ\"\nOutput: \"lmnoppqq\"\nExplanation: L, M, N, O, and Q are \nconverted to l, m, n, o and q thus \nall uppercase characters of the \nstring converted to lowercase letter." }, { "code": null, "e": 838, "s": 679, "text": "Your Task: \nYou dont need to read input or print anything. Complete the function toLower() which takes S as input parameter and returns the converted string." }, { "code": null, "e": 900, "s": 838, "text": "Expected Time Complexity:O(n)\nExpected Auxiliary Space: O(1) " }, { "code": null, "e": 930, "s": 900, "text": "Constraints:\n1 <= |S| <= 1000" }, { "code": null, "e": 932, "s": 930, "text": "0" }, { "code": null, "e": 957, "s": 932, "text": "rohitjaroli226 hours ago" }, { "code": null, "e": 1079, "s": 957, "text": "class Solution { static String toLower(String S) { String str=\"\"; str=S.toLowerCase(); return str; }}" }, { "code": null, "e": 1081, "s": 1079, "text": "0" }, { "code": null, "e": 1103, "s": 1081, "text": "bpanchal758 hours ago" }, { "code": null, "e": 1211, "s": 1103, "text": "class Solution { static String toLower(String S) { String s = S.toLowerCase(); return s; }}" }, { "code": null, "e": 1213, "s": 1211, "text": "0" }, { "code": null, "e": 1235, "s": 1213, "text": "dwcahtyin16 hours ago" }, { "code": null, "e": 1239, "s": 1235, "text": "CPP" }, { "code": null, "e": 1392, "s": 1239, "text": "class Solution { public: string toLower(string S) { // code here for(auto& s : S){ s = tolower(s); } return S; }};" }, { "code": null, "e": 1394, "s": 1392, "text": "0" }, { "code": null, "e": 1411, "s": 1394, "text": "sojwal2 days ago" }, { "code": null, "e": 1418, "s": 1411, "text": "//JAVA" }, { "code": null, "e": 1757, "s": 1420, "text": "class Solution {\n static String toLower(String S) {\n // code here\n \n char [] a = S.toCharArray();\n \n for(int i = 0; i < a.length; i++){\n if(a[i] <91 && a[i] > 64 ){\n a[i] = (char)((int) a[i] + 32);\n }\n }\n \n return String.valueOf(a);\n }\n}" }, { "code": null, "e": 1759, "s": 1757, "text": "0" }, { "code": null, "e": 1783, "s": 1759, "text": "balagopen82x66 days ago" }, { "code": null, "e": 1821, "s": 1783, "text": "WITHOUT USING ANY PREDEFINED FUNCTON " }, { "code": null, "e": 2123, "s": 1821, "text": "class Solution { static String toLower(String S) { char [] a= S.toCharArray(); int n= a.length; for(int i=0;i<n;i++) { if(a[i]>='A' && a[i]<='Z') { a[i]=(char)((int)a[i]+32); } } String s=String.valueOf(a); return s;" }, { "code": null, "e": 2125, "s": 2123, "text": "}" }, { "code": null, "e": 2128, "s": 2125, "text": "+1" }, { "code": null, "e": 2153, "s": 2128, "text": "smartankit19981 week ago" }, { "code": null, "e": 2247, "s": 2153, "text": "Simple Code in JavascripttoLower(arr,n){ //code here return arr.toLowerCase() }" }, { "code": null, "e": 2249, "s": 2247, "text": "0" }, { "code": null, "e": 2275, "s": 2249, "text": "yogeshbisht2122 weeks ago" }, { "code": null, "e": 2288, "s": 2275, "text": "//1st method" }, { "code": null, "e": 2483, "s": 2290, "text": "string toLower(string S) { for(int i=0;i<S.size();i++) { if(S[i]>='A' && S[i]<='Z') { S[i]+=32; } } cout<<S;// code here }" }, { "code": null, "e": 2498, "s": 2485, "text": "//2nd method" }, { "code": null, "e": 2550, "s": 2500, "text": "transform(S.begin(),S.end(),S.begin(),::tolower);" }, { "code": null, "e": 2553, "s": 2550, "text": "+1" }, { "code": null, "e": 2575, "s": 2553, "text": "amkamble222 weeks ago" }, { "code": null, "e": 2600, "s": 2575, "text": "Simple code in java....." }, { "code": null, "e": 2709, "s": 2602, "text": "class Solution { static String toLower(String S) { // code here return S.toLowerCase(); }}" }, { "code": null, "e": 2715, "s": 2713, "text": "0" }, { "code": null, "e": 2737, "s": 2715, "text": "brmdinhata2 weeks ago" }, { "code": null, "e": 2888, "s": 2737, "text": "class Solution { public: string toLower(string S) { transform(S.begin(),S.end(),S.begin(),::tolower); // code here return S; }};" }, { "code": null, "e": 2890, "s": 2888, "text": "0" }, { "code": null, "e": 2917, "s": 2890, "text": "sakshinagdive153 weeks ago" }, { "code": null, "e": 2929, "s": 2917, "text": "For Python3" }, { "code": null, "e": 2994, "s": 2931, "text": "class Solution: def toLower (ob, S): return S.lower()" }, { "code": null, "e": 3140, "s": 2994, "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": 3176, "s": 3140, "text": " Login to access your submissions. " }, { "code": null, "e": 3186, "s": 3176, "text": "\nProblem\n" }, { "code": null, "e": 3196, "s": 3186, "text": "\nContest\n" }, { "code": null, "e": 3259, "s": 3196, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3444, "s": 3259, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3728, "s": 3444, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 3874, "s": 3728, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 3951, "s": 3874, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 3992, "s": 3951, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 4020, "s": 3992, "text": "Disable browser extensions." }, { "code": null, "e": 4091, "s": 4020, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 4278, "s": 4091, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Private Constructors in C#
23 Jan, 2019 Prerequisite: Constructors in C# Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members. The private constructor is always declared by using a private keyword. Important points: It is the implementation of a singleton class pattern. Use private constructor when class have only static members. Using private constructor, prevents the creation of the instances of that class. If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor. If a class contains only private constructors and does not contain public constructor, then other classes are not allowed to create instances of that class except nested class. Syntax : private constructor_name { // Code } Note: If we don’t use any access modifier to define a constructor, then the compiler takes that constructor as a private. Example 1: // C# program to illustrate the// concept of private Constructorusing System; public class Geeks { // Private constructor // without parameter private Geeks() { Console.WriteLine("Private Constructor"); }} // Driver Classclass GFG { // Main Method static void Main() { // This line raise error because // the constructor is inaccessible Geeks obj = new Geeks(); }} Compile-time Error: prog.cs(40, 13): error CS0122: `Geeks.Geeks()’ is inaccessible due to its protection level Explanation: In the above example, we have a class named as Geeks. Geeks class contains the private constructor, i.e. private Geeks(). In the Main method, when we are trying to access private constructor using this statement Geeks obj = new Geeks();, the compiler will give an error because the constructor is inaccessible. Example 2: // C# program to illustrate the// concept of private Constructorusing System; class Geeks { // Variables public static string name; public static int num; // Creating private Constructor // using private keyword private Geeks() { Console.WriteLine("Welcome to Private Constructor"); } // Default Constructor // with parameters public Geeks(string a, int b) { name = a; num = b; }} // Driver Classclass GFG { // Main Method static void Main() { // This line raises error because // the constructor is inaccessible // Geeks obj1 = new Geeks(); // Here, the only default // constructor will invoke Geeks obj2 = new Geeks("Ankita", 2); // Here, the data members of Geeks // class are directly accessed // because they are static members // and static members are accessed // directly with the class name Console.WriteLine(Geeks.name + ", " + Geeks.num); }} Output: Ankita, 2 Explanation: The above example contains a class named as Geeks. This Geeks class contains two static variables, i.e. name, and num and two constructors one is a private constructor, i.e. private Geeks() and another one is default constructor with two parameters, i.e. public Geeks(string a, int b). In the Main method, when we try to invoke private constructor using this statement Geeks obj1 = new Geeks(); will give an error because the private constructor does not allow to create instances of Geeks class. The only default constructor will invoke. CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Arrays C# | Data Types C# | Replace() Method Introduction to .NET Framework C# | .NET Framework (Basic Architecture and Component Stack) Linked List Implementation in C# Difference between Managed and Unmanaged code in .NET C# | Namespaces C# | Boxing And Unboxing
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2019" }, { "code": null, "e": 295, "s": 28, "text": "Prerequisite: Constructors in C# Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members. The private constructor is always declared by using a private keyword." }, { "code": null, "e": 313, "s": 295, "text": "Important points:" }, { "code": null, "e": 368, "s": 313, "text": "It is the implementation of a singleton class pattern." }, { "code": null, "e": 429, "s": 368, "text": "Use private constructor when class have only static members." }, { "code": null, "e": 510, "s": 429, "text": "Using private constructor, prevents the creation of the instances of that class." }, { "code": null, "e": 640, "s": 510, "text": "If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor." }, { "code": null, "e": 817, "s": 640, "text": "If a class contains only private constructors and does not contain public constructor, then other classes are not allowed to create instances of that class except nested class." }, { "code": null, "e": 826, "s": 817, "text": "Syntax :" }, { "code": null, "e": 867, "s": 826, "text": "private constructor_name\n{\n // Code\n}\n" }, { "code": null, "e": 989, "s": 867, "text": "Note: If we don’t use any access modifier to define a constructor, then the compiler takes that constructor as a private." }, { "code": null, "e": 1000, "s": 989, "text": "Example 1:" }, { "code": "// C# program to illustrate the// concept of private Constructorusing System; public class Geeks { // Private constructor // without parameter private Geeks() { Console.WriteLine(\"Private Constructor\"); }} // Driver Classclass GFG { // Main Method static void Main() { // This line raise error because // the constructor is inaccessible Geeks obj = new Geeks(); }}", "e": 1425, "s": 1000, "text": null }, { "code": null, "e": 1445, "s": 1425, "text": "Compile-time Error:" }, { "code": null, "e": 1536, "s": 1445, "text": "prog.cs(40, 13): error CS0122: `Geeks.Geeks()’ is inaccessible due to its protection level" }, { "code": null, "e": 1860, "s": 1536, "text": "Explanation: In the above example, we have a class named as Geeks. Geeks class contains the private constructor, i.e. private Geeks(). In the Main method, when we are trying to access private constructor using this statement Geeks obj = new Geeks();, the compiler will give an error because the constructor is inaccessible." }, { "code": null, "e": 1871, "s": 1860, "text": "Example 2:" }, { "code": "// C# program to illustrate the// concept of private Constructorusing System; class Geeks { // Variables public static string name; public static int num; // Creating private Constructor // using private keyword private Geeks() { Console.WriteLine(\"Welcome to Private Constructor\"); } // Default Constructor // with parameters public Geeks(string a, int b) { name = a; num = b; }} // Driver Classclass GFG { // Main Method static void Main() { // This line raises error because // the constructor is inaccessible // Geeks obj1 = new Geeks(); // Here, the only default // constructor will invoke Geeks obj2 = new Geeks(\"Ankita\", 2); // Here, the data members of Geeks // class are directly accessed // because they are static members // and static members are accessed // directly with the class name Console.WriteLine(Geeks.name + \", \" + Geeks.num); }}", "e": 2893, "s": 1871, "text": null }, { "code": null, "e": 2901, "s": 2893, "text": "Output:" }, { "code": null, "e": 2911, "s": 2901, "text": "Ankita, 2" }, { "code": null, "e": 3463, "s": 2911, "text": "Explanation: The above example contains a class named as Geeks. This Geeks class contains two static variables, i.e. name, and num and two constructors one is a private constructor, i.e. private Geeks() and another one is default constructor with two parameters, i.e. public Geeks(string a, int b). In the Main method, when we try to invoke private constructor using this statement Geeks obj1 = new Geeks(); will give an error because the private constructor does not allow to create instances of Geeks class. The only default constructor will invoke." }, { "code": null, "e": 3474, "s": 3463, "text": "CSharp-OOP" }, { "code": null, "e": 3477, "s": 3474, "text": "C#" }, { "code": null, "e": 3575, "s": 3477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3603, "s": 3575, "text": "C# Dictionary with examples" }, { "code": null, "e": 3615, "s": 3603, "text": "C# | Arrays" }, { "code": null, "e": 3631, "s": 3615, "text": "C# | Data Types" }, { "code": null, "e": 3653, "s": 3631, "text": "C# | Replace() Method" }, { "code": null, "e": 3684, "s": 3653, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3745, "s": 3684, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 3778, "s": 3745, "text": "Linked List Implementation in C#" }, { "code": null, "e": 3832, "s": 3778, "text": "Difference between Managed and Unmanaged code in .NET" }, { "code": null, "e": 3848, "s": 3832, "text": "C# | Namespaces" } ]
Variable Entrant Map (VEM) in Digital Logic
18 Jan, 2022 Prerequisite – Karnaugh Map (K-map)K-map is the best manual technique to solve Boolean equations, but it becomes difficult to manage when number of variables exceed 5 or 6. So, a technique called Variable Entrant Map (VEM) is used to increase the effective size of k-map. It allows a smaller map to handle large number of variables. This is done by writing output in terms of input. Example – A 3-variable function can be defined as a function of 2-variables if the output is written in terms of third variable. Consider a function F(A,B,C) = (0,1,2,5) If we define F in terms of ‘C’, then this function can be written as: And the VEM for this is: Advantages of using VEM – A VEM can be used to plot more than ‘n’ variables using an ‘n’ variable K-map. It is commonly used to solve problems involving multiplexers. Minimization procedure for VEM – Now, let’s see how to find SOP expression if a VEM is given. Write all the variables(original and complimented forms are treated as two different variables) in the map as 0, leave 0’s, minterms and don’t cares as it is and obtain the SOP expression.(a) Select one variable and make all occurrences of that variable as 1, write minterms (1’s) as don’t cares, leave 0’s and don’t cares as it is. Now, obtain the SOP expression.(b) Multiply the obtained SOP expression with the concerned variable.Repeat step 2 for all the variables in the k-map.SOP of VEM is obtained by ORing all the obtained SOP expressions. Write all the variables(original and complimented forms are treated as two different variables) in the map as 0, leave 0’s, minterms and don’t cares as it is and obtain the SOP expression. (a) Select one variable and make all occurrences of that variable as 1, write minterms (1’s) as don’t cares, leave 0’s and don’t cares as it is. Now, obtain the SOP expression.(b) Multiply the obtained SOP expression with the concerned variable. Repeat step 2 for all the variables in the k-map. SOP of VEM is obtained by ORing all the obtained SOP expressions. Let’s apply the above procedure on a sample VEM (X is used to represent don’t care): Step 1: Write all the variables as 0 (D and D’ are considered as two different variables), leave minterms, 0’s and don’t cares as it is and obtain the SOP expression. SOP obtained: A'C Step 2:(a) Replace all occurrences of D with 1, all occurrences of D’ with 0 and all 1’s with don’t care. Leave 0’s and don’t cares as it is. (b) Multiply the obtained SOP with the concerned variable. SOP obtained: AC'D Step 3: Repeat step 2 for D’ (a) Replace all occurrences of D’ with 1, all occurrences of D with 0 and all 1’s with don’t care. Leave 0’s and don’t cares as it is. (b) Multiply the obtained SOP with the concerned variable. SOP obtained: CD' Step 4: SOP of VEM is obtained by ORing all the obtained SOP expressions. Therefore, the SOP expression for the given VEM is: A'C + AC'D + CD' sweetyty Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers Difference between RAM and ROM Introduction to memory and memory units Analog to Digital Conversion Difference between Half adder and full adder Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jan, 2022" }, { "code": null, "e": 437, "s": 54, "text": "Prerequisite – Karnaugh Map (K-map)K-map is the best manual technique to solve Boolean equations, but it becomes difficult to manage when number of variables exceed 5 or 6. So, a technique called Variable Entrant Map (VEM) is used to increase the effective size of k-map. It allows a smaller map to handle large number of variables. This is done by writing output in terms of input." }, { "code": null, "e": 566, "s": 437, "text": "Example – A 3-variable function can be defined as a function of 2-variables if the output is written in terms of third variable." }, { "code": null, "e": 607, "s": 566, "text": "Consider a function F(A,B,C) = (0,1,2,5)" }, { "code": null, "e": 677, "s": 607, "text": "If we define F in terms of ‘C’, then this function can be written as:" }, { "code": null, "e": 702, "s": 677, "text": "And the VEM for this is:" }, { "code": null, "e": 728, "s": 702, "text": "Advantages of using VEM –" }, { "code": null, "e": 807, "s": 728, "text": "A VEM can be used to plot more than ‘n’ variables using an ‘n’ variable K-map." }, { "code": null, "e": 869, "s": 807, "text": "It is commonly used to solve problems involving multiplexers." }, { "code": null, "e": 963, "s": 869, "text": "Minimization procedure for VEM – Now, let’s see how to find SOP expression if a VEM is given." }, { "code": null, "e": 1511, "s": 963, "text": "Write all the variables(original and complimented forms are treated as two different variables) in the map as 0, leave 0’s, minterms and don’t cares as it is and obtain the SOP expression.(a) Select one variable and make all occurrences of that variable as 1, write minterms (1’s) as don’t cares, leave 0’s and don’t cares as it is. Now, obtain the SOP expression.(b) Multiply the obtained SOP expression with the concerned variable.Repeat step 2 for all the variables in the k-map.SOP of VEM is obtained by ORing all the obtained SOP expressions." }, { "code": null, "e": 1700, "s": 1511, "text": "Write all the variables(original and complimented forms are treated as two different variables) in the map as 0, leave 0’s, minterms and don’t cares as it is and obtain the SOP expression." }, { "code": null, "e": 1946, "s": 1700, "text": "(a) Select one variable and make all occurrences of that variable as 1, write minterms (1’s) as don’t cares, leave 0’s and don’t cares as it is. Now, obtain the SOP expression.(b) Multiply the obtained SOP expression with the concerned variable." }, { "code": null, "e": 1996, "s": 1946, "text": "Repeat step 2 for all the variables in the k-map." }, { "code": null, "e": 2062, "s": 1996, "text": "SOP of VEM is obtained by ORing all the obtained SOP expressions." }, { "code": null, "e": 2147, "s": 2062, "text": "Let’s apply the above procedure on a sample VEM (X is used to represent don’t care):" }, { "code": null, "e": 2314, "s": 2147, "text": "Step 1: Write all the variables as 0 (D and D’ are considered as two different variables), leave minterms, 0’s and don’t cares as it is and obtain the SOP expression." }, { "code": null, "e": 2333, "s": 2314, "text": " SOP obtained: A'C" }, { "code": null, "e": 2475, "s": 2333, "text": "Step 2:(a) Replace all occurrences of D with 1, all occurrences of D’ with 0 and all 1’s with don’t care. Leave 0’s and don’t cares as it is." }, { "code": null, "e": 2534, "s": 2475, "text": "(b) Multiply the obtained SOP with the concerned variable." }, { "code": null, "e": 2553, "s": 2534, "text": "SOP obtained: AC'D" }, { "code": null, "e": 2582, "s": 2553, "text": "Step 3: Repeat step 2 for D’" }, { "code": null, "e": 2717, "s": 2582, "text": "(a) Replace all occurrences of D’ with 1, all occurrences of D with 0 and all 1’s with don’t care. Leave 0’s and don’t cares as it is." }, { "code": null, "e": 2776, "s": 2717, "text": "(b) Multiply the obtained SOP with the concerned variable." }, { "code": null, "e": 2795, "s": 2776, "text": "SOP obtained: CD' " }, { "code": null, "e": 2921, "s": 2795, "text": "Step 4: SOP of VEM is obtained by ORing all the obtained SOP expressions. Therefore, the SOP expression for the given VEM is:" }, { "code": null, "e": 2939, "s": 2921, "text": "A'C + AC'D + CD' " }, { "code": null, "e": 2948, "s": 2939, "text": "sweetyty" }, { "code": null, "e": 2983, "s": 2948, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 2991, "s": 2983, "text": "GATE CS" }, { "code": null, "e": 3089, "s": 2991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3130, "s": 3089, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 3161, "s": 3130, "text": "Difference between RAM and ROM" }, { "code": null, "e": 3201, "s": 3161, "text": "Introduction to memory and memory units" }, { "code": null, "e": 3230, "s": 3201, "text": "Analog to Digital Conversion" }, { "code": null, "e": 3275, "s": 3230, "text": "Difference between Half adder and full adder" }, { "code": null, "e": 3295, "s": 3275, "text": "Layers of OSI Model" }, { "code": null, "e": 3319, "s": 3295, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3332, "s": 3319, "text": "TCP/IP Model" }, { "code": null, "e": 3359, "s": 3332, "text": "Types of Operating Systems" } ]
MySQL | BINARY Function
21 Nov, 2019 The MySQL BINARY function is used for converting a value to a binary string. The BINARY function can also be implemented using CAST function as CAST(value AS BINARY).The BINARY function accepts one parameter which is the value to be converted and returns a binary string. Syntax: BINARY value Parameters Used: value – It is used to specify the value to be converted. Return Value:The MySQL BINARY function returns a binary string after converting a value specified by the user. Supported Versions of MySQL: MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23 Example-1: Implementing BINARY function to return a binary string. SELECT BINARY('Geeksforgeeks'); Output: Geeksforgeeks Example-2: Character-by-character comparison of two string without using BINARY function. SELECT 'GEEKSFORGEEKS' = 'geeksforgeeks'; Output: 1 Example-3: Byte-by-Byte comparison of two string using BINARY function. SELECT BINARY 'GEEKSFORGEEKS' = 'geeksforgeeks'; Output: 0 Example-4: Byte-by-Byte comparison of two string using BINARY function. SELECT BINARY 'GEEKSFORGEEKS' = 'GEEKSFORGEEKS'; Output: 1 mysql SQLmysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Trigger | Student Database SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Window functions in SQL MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2019" }, { "code": null, "e": 300, "s": 28, "text": "The MySQL BINARY function is used for converting a value to a binary string. The BINARY function can also be implemented using CAST function as CAST(value AS BINARY).The BINARY function accepts one parameter which is the value to be converted and returns a binary string." }, { "code": null, "e": 308, "s": 300, "text": "Syntax:" }, { "code": null, "e": 321, "s": 308, "text": "BINARY value" }, { "code": null, "e": 338, "s": 321, "text": "Parameters Used:" }, { "code": null, "e": 395, "s": 338, "text": "value – It is used to specify the value to be converted." }, { "code": null, "e": 506, "s": 395, "text": "Return Value:The MySQL BINARY function returns a binary string after converting a value specified by the user." }, { "code": null, "e": 535, "s": 506, "text": "Supported Versions of MySQL:" }, { "code": null, "e": 545, "s": 535, "text": "MySQL 5.7" }, { "code": null, "e": 555, "s": 545, "text": "MySQL 5.6" }, { "code": null, "e": 565, "s": 555, "text": "MySQL 5.5" }, { "code": null, "e": 575, "s": 565, "text": "MySQL 5.1" }, { "code": null, "e": 585, "s": 575, "text": "MySQL 5.0" }, { "code": null, "e": 595, "s": 585, "text": "MySQL 4.1" }, { "code": null, "e": 605, "s": 595, "text": "MySQL 4.0" }, { "code": null, "e": 616, "s": 605, "text": "MySQL 3.23" }, { "code": null, "e": 683, "s": 616, "text": "Example-1: Implementing BINARY function to return a binary string." }, { "code": null, "e": 717, "s": 683, "text": "SELECT BINARY('Geeksforgeeks'); " }, { "code": null, "e": 725, "s": 717, "text": "Output:" }, { "code": null, "e": 740, "s": 725, "text": "Geeksforgeeks " }, { "code": null, "e": 830, "s": 740, "text": "Example-2: Character-by-character comparison of two string without using BINARY function." }, { "code": null, "e": 873, "s": 830, "text": "SELECT 'GEEKSFORGEEKS' = 'geeksforgeeks'; " }, { "code": null, "e": 881, "s": 873, "text": "Output:" }, { "code": null, "e": 884, "s": 881, "text": "1 " }, { "code": null, "e": 956, "s": 884, "text": "Example-3: Byte-by-Byte comparison of two string using BINARY function." }, { "code": null, "e": 1006, "s": 956, "text": "SELECT BINARY 'GEEKSFORGEEKS' = 'geeksforgeeks'; " }, { "code": null, "e": 1014, "s": 1006, "text": "Output:" }, { "code": null, "e": 1017, "s": 1014, "text": "0 " }, { "code": null, "e": 1089, "s": 1017, "text": "Example-4: Byte-by-Byte comparison of two string using BINARY function." }, { "code": null, "e": 1139, "s": 1089, "text": "SELECT BINARY 'GEEKSFORGEEKS' = 'GEEKSFORGEEKS'; " }, { "code": null, "e": 1147, "s": 1139, "text": "Output:" }, { "code": null, "e": 1150, "s": 1147, "text": "1 " }, { "code": null, "e": 1156, "s": 1150, "text": "mysql" }, { "code": null, "e": 1165, "s": 1156, "text": "SQLmysql" }, { "code": null, "e": 1169, "s": 1165, "text": "SQL" }, { "code": null, "e": 1173, "s": 1169, "text": "SQL" }, { "code": null, "e": 1271, "s": 1173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1282, "s": 1271, "text": "CTE in SQL" }, { "code": null, "e": 1348, "s": 1282, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1379, "s": 1348, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1403, "s": 1379, "text": "SQL Interview Questions" }, { "code": null, "e": 1415, "s": 1403, "text": "SQL | Views" }, { "code": null, "e": 1460, "s": 1415, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1493, "s": 1460, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1517, "s": 1493, "text": "Window functions in SQL" }, { "code": null, "e": 1549, "s": 1517, "text": "MySQL | Group_CONCAT() Function" } ]
Grouped Boxplots in Python with Seaborn
26 Nov, 2020 Boxplot depicts the distribution of quantitative data facilitating comparisons between different variables, continuous or categorical. It is a common data dispersion measure. Boxplots consist of a five-number summary which helps in detecting and removing outliers from the dataset. Minimum observationQ1 (25% or Quartile 1)Median or Q2Q3 (75% or Quartile 2)Maximum Observation Minimum observation Q1 (25% or Quartile 1) Median or Q2 Q3 (75% or Quartile 2) Maximum Observation Grouped Boxplots are used to visualize the data having multiple subgroups. Also, we can visualize three variables at a time with grouped boxplot where one variable is numerical and the other two are categorical variables. We will be using the Seaborn library of Python to create Grouped Boxplots. We will use dataset ‘tips’ from the Seaborn library. Python3 # import seaborn libraryimport seaborn as sns # load the datasetdata = sns.load_dataset('tips') # view the datasetprint(data.head(5)) Output: Example 1: Let us create a boxplot to know the distribution of the ‘total_bill’ on each ‘day’ of the ‘tips’ dataset. But we also want to group it on the basis of ‘sex’ attribute. So we will plot a grouped boxplots for these three attributes where ‘sex’ and ‘day’ are categorical attributes and ‘total_bill’ is a numeric attribute. Python3 # create grouped boxplot sns.boxplot(x = data['day'], y = data['total_bill'], hue = data['sex']) Output: Example 2: The next example is similar to the previous one. The only difference is the value of the ‘hue’ parameter taken as the ‘smoker’ attribute. Here we want to know the distribution of ‘total_bill’ vs ‘day’ group on the basis of if a person smokes or not. Also, we have learned how to change the colors of the boxplots using the ‘palette’ attribute of the boxplot(). Python3 # create another grouped boxplot sns.boxplot(x = data['day'], y = data['total_bill'], hue = data['smoker'], palette = 'Set2') Output: Example 3: In this example, we will cover how to draw more than 2 grouped boxplots. if the value for the ‘hue’ parameter has more than 2 categories, then we can plot more than 2 grouped boxplots as shown below. Here, ‘hue’ = data[‘size’] has six categories, and so we can see more than 2 grouped boxplots using the same method as above. Python3 # create 3rd grouped boxplot sns.boxplot(x = data['day'], y = data['total_bill'], hue = data['size'], palette = 'husl') Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 310, "s": 28, "text": "Boxplot depicts the distribution of quantitative data facilitating comparisons between different variables, continuous or categorical. It is a common data dispersion measure. Boxplots consist of a five-number summary which helps in detecting and removing outliers from the dataset." }, { "code": null, "e": 405, "s": 310, "text": "Minimum observationQ1 (25% or Quartile 1)Median or Q2Q3 (75% or Quartile 2)Maximum Observation" }, { "code": null, "e": 425, "s": 405, "text": "Minimum observation" }, { "code": null, "e": 448, "s": 425, "text": "Q1 (25% or Quartile 1)" }, { "code": null, "e": 461, "s": 448, "text": "Median or Q2" }, { "code": null, "e": 484, "s": 461, "text": "Q3 (75% or Quartile 2)" }, { "code": null, "e": 504, "s": 484, "text": "Maximum Observation" }, { "code": null, "e": 727, "s": 504, "text": "Grouped Boxplots are used to visualize the data having multiple subgroups. Also, we can visualize three variables at a time with grouped boxplot where one variable is numerical and the other two are categorical variables. " }, { "code": null, "e": 855, "s": 727, "text": "We will be using the Seaborn library of Python to create Grouped Boxplots. We will use dataset ‘tips’ from the Seaborn library." }, { "code": null, "e": 863, "s": 855, "text": "Python3" }, { "code": "# import seaborn libraryimport seaborn as sns # load the datasetdata = sns.load_dataset('tips') # view the datasetprint(data.head(5))", "e": 999, "s": 863, "text": null }, { "code": null, "e": 1007, "s": 999, "text": "Output:" }, { "code": null, "e": 1338, "s": 1007, "text": "Example 1: Let us create a boxplot to know the distribution of the ‘total_bill’ on each ‘day’ of the ‘tips’ dataset. But we also want to group it on the basis of ‘sex’ attribute. So we will plot a grouped boxplots for these three attributes where ‘sex’ and ‘day’ are categorical attributes and ‘total_bill’ is a numeric attribute." }, { "code": null, "e": 1346, "s": 1338, "text": "Python3" }, { "code": "# create grouped boxplot sns.boxplot(x = data['day'], y = data['total_bill'], hue = data['sex'])", "e": 1465, "s": 1346, "text": null }, { "code": null, "e": 1473, "s": 1465, "text": "Output:" }, { "code": null, "e": 1735, "s": 1473, "text": "Example 2: The next example is similar to the previous one. The only difference is the value of the ‘hue’ parameter taken as the ‘smoker’ attribute. Here we want to know the distribution of ‘total_bill’ vs ‘day’ group on the basis of if a person smokes or not. " }, { "code": null, "e": 1846, "s": 1735, "text": "Also, we have learned how to change the colors of the boxplots using the ‘palette’ attribute of the boxplot()." }, { "code": null, "e": 1854, "s": 1846, "text": "Python3" }, { "code": "# create another grouped boxplot sns.boxplot(x = data['day'], y = data['total_bill'], hue = data['smoker'], palette = 'Set2')", "e": 2013, "s": 1854, "text": null }, { "code": null, "e": 2021, "s": 2013, "text": "Output:" }, { "code": null, "e": 2233, "s": 2021, "text": "Example 3: In this example, we will cover how to draw more than 2 grouped boxplots. if the value for the ‘hue’ parameter has more than 2 categories, then we can plot more than 2 grouped boxplots as shown below. " }, { "code": null, "e": 2359, "s": 2233, "text": "Here, ‘hue’ = data[‘size’] has six categories, and so we can see more than 2 grouped boxplots using the same method as above." }, { "code": null, "e": 2367, "s": 2359, "text": "Python3" }, { "code": "# create 3rd grouped boxplot sns.boxplot(x = data['day'], y = data['total_bill'], hue = data['size'], palette = 'husl')", "e": 2520, "s": 2367, "text": null }, { "code": null, "e": 2528, "s": 2520, "text": "Output:" }, { "code": null, "e": 2543, "s": 2528, "text": "Python-Seaborn" }, { "code": null, "e": 2550, "s": 2543, "text": "Python" }, { "code": null, "e": 2648, "s": 2550, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2676, "s": 2648, "text": "Read JSON file using Python" }, { "code": null, "e": 2698, "s": 2676, "text": "Python map() function" }, { "code": null, "e": 2748, "s": 2698, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2766, "s": 2748, "text": "Python Dictionary" }, { "code": null, "e": 2810, "s": 2766, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2852, "s": 2810, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2875, "s": 2852, "text": "Taking input in Python" }, { "code": null, "e": 2897, "s": 2875, "text": "Enumerate() in Python" }, { "code": null, "e": 2932, "s": 2897, "text": "Read a file line by line in Python" } ]
Program to print first n Fibonacci Numbers | Set 1
07 Jul, 2022 Following is a simple program to print first n Fibonacci numbers. Examples : Input : n = 3 Output : 0 1 1 Input : n = 7 Output : 0 1 1 2 3 5 8 C++ C Java Python3 C# PHP Javascript // C++ program to print// first n Fibonacci numbers#include <bits/stdc++.h>using namespace std; // Function to print// first n Fibonacci Numbersvoid printFibonacciNumbers(int n){ int f1 = 0, f2 = 1, i; if (n < 1) return; cout << f1 << " "; for (i = 1; i < n; i++) { cout << f2 << " "; int next = f1 + f2; f1 = f2; f2 = next; }} // Driver Codeint main(){ printFibonacciNumbers(7); return 0;} // This code is contributed by rathbhupendra // C program to print// first n Fibonacci numbers#include <stdio.h> // Function to print// first n Fibonacci Numbersvoid printFibonacciNumbers(int n){ int f1 = 0, f2 = 1, i; if (n < 1) return; printf("%d ", f1); for (i = 1; i < n; i++) { printf("%d ", f2); int next = f1 + f2; f1 = f2; f2 = next; }} // Driver Codeint main(){ printFibonacciNumbers(7); return 0;} // Java program to print// first n Fibonacci Numbers class Test { // Method to print // first n Fibonacci Numbers static void printFibonacciNumbers(int n) { int f1 = 0, f2 = 1, i; if (n < 1) return; System.out.print(f1 + " "); for (i = 1; i < n; i++) { System.out.print(f2 + " "); int next = f1 + f2; f1 = f2; f2 = next; } } // Driver Code public static void main(String[] args) { printFibonacciNumbers(7); }} # Python program to print first n# Fibonacci numbers # Function to print first n# Fibonacci Numbers def printFibonacciNumbers(n): f1 = 0 f2 = 1 if (n < 1): return print(f1, end=" ") for x in range(1, n): print(f2, end=" ") next = f1 + f2 f1 = f2 f2 = next # Driven codeprintFibonacciNumbers(7) # This code is contributed by Danish Raza // C# program to print// first n Fibonacci Numbersusing System; class Test { // Method to print // first n Fibonacci Numbers static void printFibonacciNumbers(int n) { int f1 = 0, f2 = 1, i; if (n < 1) return; Console.Write(f1 + " "); for (i = 1; i < n; i++) { Console.Write(f2 + " "); int next = f1 + f2; f1 = f2; f2 = next; } } // Driver Code public static void Main() { printFibonacciNumbers(7); }} // This code is contributed by nitin mittal. <?php// PHP program to print first// n Fibonacci numbers // Function to print first n// Fibonacci Numbersfunction printFibonacciNumbers($n){ $f1 = 0; $f2 = 1; $i; if ($n < 1) return; echo($f1); echo(" "); for ($i = 1; $i < $n; $i++) { echo($f2); echo(" "); $next = $f1 + $f2; $f1 = $f2; $f2 = $next; }} // Driver Code printFibonacciNumbers(7); // This code is contributed by nitin mittal?> <script> // Javascript program to print// first n Fibonacci numbers // Function to print// first n Fibonacci Numbersfunction printFibonacciNumbers(n){ let f1 = 0, f2 = 1, i; if (n < 1) return; document.write(f1 + " "); for (i = 1; i < n; i++) { document.write(f2 + " "); let next = f1 + f2; f1 = f2; f2 = next; }} // Driver Code printFibonacciNumbers(7); // This code is contributed by Mayank Tyagi </script> 0 1 1 2 3 5 8 C++ Java Python3 C# Javascript #include <iostream>using namespace std; int fibonacci_numbers(int n){ if(n == 0){ return 0; } else if(n == 1){ return 1; } else{ return fibonacci_numbers(n-2) + fibonacci_numbers(n-1); }} int main() { int n = 7; for(int i = 0; i < n; i++) { cout << fibonacci_numbers(i) << " "; } return 0;}// This code is contributed by Rupesh Kapse /*package whatever //do not write package name here */import java.io.*; class GFG { public static int fibonacci_numbers(int n) { if(n == 0){ return 0; } else if(n == 1){ return 1; } else{ return fibonacci_numbers(n-2) + fibonacci_numbers(n-1); } } public static void main (String[] args) { int n = 7; for(int i = 0; i < n; i++){ System.out.print(fibonacci_numbers(i)+ " "); } }} // This code is contributed by Rupesh Kapse # python code to print first n fibonacci numbers def fibonacci_numbers(num): if num == 0: return 0 elif num == 1: return 1 else: # printing fibonacci numbers return fibonacci_numbers(num-2)+fibonacci_numbers(num-1) n = 7for i in range(0, n): print(fibonacci_numbers(i), end=" ") # this code is contributed by gangarajula laxmi // C# code to implement the approachusing System; class GFG { // Method to calculate the nth fibonacci number public static int fibonacci_numbers(int n) { if(n == 0){ return 0; } else if(n == 1){ return 1; } else{ return fibonacci_numbers(n-2) + fibonacci_numbers(n-1); } } // Driver Code public static void Main (string[] args) { int n = 7; for(int i = 0; i < n; i++){ // Function call Console.Write(fibonacci_numbers(i)+ " "); } }} // This code is contributed by phasing17 <script> // JavaScript code for the above approach function fibonacci_numbers(n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fibonacci_numbers(n - 2) + fibonacci_numbers(n - 1); } } let n = 7; for (let i = 0; i < n; i++) { document.write(fibonacci_numbers(i) + " "); } // This code is contributed by Potta Lokesh </script> 0 1 1 2 3 5 8 Time Complexity: O(n) Auxiliary Space: O(1) If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geekforgeeks.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 if you want to share more information about the topic discussed above. Sahil_Chhabra nitin mittal rathbhupendra kajalkukreja694 mayanktyagi1709 subham348 laxmigangarajula03 rupeshsk30 lokeshpotta20 phasing17 Fibonacci Wipro Mathematical School Programming Wipro Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 119, "s": 52, "text": "Following is a simple program to print first n Fibonacci numbers. " }, { "code": null, "e": 131, "s": 119, "text": "Examples : " }, { "code": null, "e": 198, "s": 131, "text": "Input : n = 3\nOutput : 0 1 1\n\nInput : n = 7\nOutput : 0 1 1 2 3 5 8" }, { "code": null, "e": 202, "s": 198, "text": "C++" }, { "code": null, "e": 204, "s": 202, "text": "C" }, { "code": null, "e": 209, "s": 204, "text": "Java" }, { "code": null, "e": 217, "s": 209, "text": "Python3" }, { "code": null, "e": 220, "s": 217, "text": "C#" }, { "code": null, "e": 224, "s": 220, "text": "PHP" }, { "code": null, "e": 235, "s": 224, "text": "Javascript" }, { "code": "// C++ program to print// first n Fibonacci numbers#include <bits/stdc++.h>using namespace std; // Function to print// first n Fibonacci Numbersvoid printFibonacciNumbers(int n){ int f1 = 0, f2 = 1, i; if (n < 1) return; cout << f1 << \" \"; for (i = 1; i < n; i++) { cout << f2 << \" \"; int next = f1 + f2; f1 = f2; f2 = next; }} // Driver Codeint main(){ printFibonacciNumbers(7); return 0;} // This code is contributed by rathbhupendra", "e": 728, "s": 235, "text": null }, { "code": "// C program to print// first n Fibonacci numbers#include <stdio.h> // Function to print// first n Fibonacci Numbersvoid printFibonacciNumbers(int n){ int f1 = 0, f2 = 1, i; if (n < 1) return; printf(\"%d \", f1); for (i = 1; i < n; i++) { printf(\"%d \", f2); int next = f1 + f2; f1 = f2; f2 = next; }} // Driver Codeint main(){ printFibonacciNumbers(7); return 0;}", "e": 1148, "s": 728, "text": null }, { "code": "// Java program to print// first n Fibonacci Numbers class Test { // Method to print // first n Fibonacci Numbers static void printFibonacciNumbers(int n) { int f1 = 0, f2 = 1, i; if (n < 1) return; System.out.print(f1 + \" \"); for (i = 1; i < n; i++) { System.out.print(f2 + \" \"); int next = f1 + f2; f1 = f2; f2 = next; } } // Driver Code public static void main(String[] args) { printFibonacciNumbers(7); }}", "e": 1691, "s": 1148, "text": null }, { "code": "# Python program to print first n# Fibonacci numbers # Function to print first n# Fibonacci Numbers def printFibonacciNumbers(n): f1 = 0 f2 = 1 if (n < 1): return print(f1, end=\" \") for x in range(1, n): print(f2, end=\" \") next = f1 + f2 f1 = f2 f2 = next # Driven codeprintFibonacciNumbers(7) # This code is contributed by Danish Raza", "e": 2080, "s": 1691, "text": null }, { "code": "// C# program to print// first n Fibonacci Numbersusing System; class Test { // Method to print // first n Fibonacci Numbers static void printFibonacciNumbers(int n) { int f1 = 0, f2 = 1, i; if (n < 1) return; Console.Write(f1 + \" \"); for (i = 1; i < n; i++) { Console.Write(f2 + \" \"); int next = f1 + f2; f1 = f2; f2 = next; } } // Driver Code public static void Main() { printFibonacciNumbers(7); }} // This code is contributed by nitin mittal.", "e": 2654, "s": 2080, "text": null }, { "code": "<?php// PHP program to print first// n Fibonacci numbers // Function to print first n// Fibonacci Numbersfunction printFibonacciNumbers($n){ $f1 = 0; $f2 = 1; $i; if ($n < 1) return; echo($f1); echo(\" \"); for ($i = 1; $i < $n; $i++) { echo($f2); echo(\" \"); $next = $f1 + $f2; $f1 = $f2; $f2 = $next; }} // Driver Code printFibonacciNumbers(7); // This code is contributed by nitin mittal?>", "e": 3125, "s": 2654, "text": null }, { "code": "<script> // Javascript program to print// first n Fibonacci numbers // Function to print// first n Fibonacci Numbersfunction printFibonacciNumbers(n){ let f1 = 0, f2 = 1, i; if (n < 1) return; document.write(f1 + \" \"); for (i = 1; i < n; i++) { document.write(f2 + \" \"); let next = f1 + f2; f1 = f2; f2 = next; }} // Driver Code printFibonacciNumbers(7); // This code is contributed by Mayank Tyagi </script>", "e": 3593, "s": 3125, "text": null }, { "code": null, "e": 3608, "s": 3593, "text": "0 1 1 2 3 5 8 " }, { "code": null, "e": 3612, "s": 3608, "text": "C++" }, { "code": null, "e": 3617, "s": 3612, "text": "Java" }, { "code": null, "e": 3625, "s": 3617, "text": "Python3" }, { "code": null, "e": 3628, "s": 3625, "text": "C#" }, { "code": null, "e": 3639, "s": 3628, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int fibonacci_numbers(int n){ if(n == 0){ return 0; } else if(n == 1){ return 1; } else{ return fibonacci_numbers(n-2) + fibonacci_numbers(n-1); }} int main() { int n = 7; for(int i = 0; i < n; i++) { cout << fibonacci_numbers(i) << \" \"; } return 0;}// This code is contributed by Rupesh Kapse", "e": 4036, "s": 3639, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*; class GFG { public static int fibonacci_numbers(int n) { if(n == 0){ return 0; } else if(n == 1){ return 1; } else{ return fibonacci_numbers(n-2) + fibonacci_numbers(n-1); } } public static void main (String[] args) { int n = 7; for(int i = 0; i < n; i++){ System.out.print(fibonacci_numbers(i)+ \" \"); } }} // This code is contributed by Rupesh Kapse", "e": 4511, "s": 4036, "text": null }, { "code": "# python code to print first n fibonacci numbers def fibonacci_numbers(num): if num == 0: return 0 elif num == 1: return 1 else: # printing fibonacci numbers return fibonacci_numbers(num-2)+fibonacci_numbers(num-1) n = 7for i in range(0, n): print(fibonacci_numbers(i), end=\" \") # this code is contributed by gangarajula laxmi", "e": 4883, "s": 4511, "text": null }, { "code": "// C# code to implement the approachusing System; class GFG { // Method to calculate the nth fibonacci number public static int fibonacci_numbers(int n) { if(n == 0){ return 0; } else if(n == 1){ return 1; } else{ return fibonacci_numbers(n-2) + fibonacci_numbers(n-1); } } // Driver Code public static void Main (string[] args) { int n = 7; for(int i = 0; i < n; i++){ // Function call Console.Write(fibonacci_numbers(i)+ \" \"); } }} // This code is contributed by phasing17", "e": 5427, "s": 4883, "text": null }, { "code": "<script> // JavaScript code for the above approach function fibonacci_numbers(n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fibonacci_numbers(n - 2) + fibonacci_numbers(n - 1); } } let n = 7; for (let i = 0; i < n; i++) { document.write(fibonacci_numbers(i) + \" \"); } // This code is contributed by Potta Lokesh </script>", "e": 5954, "s": 5427, "text": null }, { "code": null, "e": 5969, "s": 5954, "text": "0 1 1 2 3 5 8 " }, { "code": null, "e": 5991, "s": 5969, "text": "Time Complexity: O(n)" }, { "code": null, "e": 6013, "s": 5991, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6395, "s": 6013, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geekforgeeks.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 if you want to share more information about the topic discussed above." }, { "code": null, "e": 6409, "s": 6395, "text": "Sahil_Chhabra" }, { "code": null, "e": 6422, "s": 6409, "text": "nitin mittal" }, { "code": null, "e": 6436, "s": 6422, "text": "rathbhupendra" }, { "code": null, "e": 6452, "s": 6436, "text": "kajalkukreja694" }, { "code": null, "e": 6468, "s": 6452, "text": "mayanktyagi1709" }, { "code": null, "e": 6478, "s": 6468, "text": "subham348" }, { "code": null, "e": 6497, "s": 6478, "text": "laxmigangarajula03" }, { "code": null, "e": 6508, "s": 6497, "text": "rupeshsk30" }, { "code": null, "e": 6522, "s": 6508, "text": "lokeshpotta20" }, { "code": null, "e": 6532, "s": 6522, "text": "phasing17" }, { "code": null, "e": 6542, "s": 6532, "text": "Fibonacci" }, { "code": null, "e": 6548, "s": 6542, "text": "Wipro" }, { "code": null, "e": 6561, "s": 6548, "text": "Mathematical" }, { "code": null, "e": 6580, "s": 6561, "text": "School Programming" }, { "code": null, "e": 6586, "s": 6580, "text": "Wipro" }, { "code": null, "e": 6599, "s": 6586, "text": "Mathematical" }, { "code": null, "e": 6609, "s": 6599, "text": "Fibonacci" }, { "code": null, "e": 6707, "s": 6609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6731, "s": 6707, "text": "Merge two sorted arrays" }, { "code": null, "e": 6752, "s": 6731, "text": "Operators in C / C++" }, { "code": null, "e": 6774, "s": 6752, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 6788, "s": 6774, "text": "Prime Numbers" }, { "code": null, "e": 6830, "s": 6788, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 6848, "s": 6830, "text": "Python Dictionary" }, { "code": null, "e": 6873, "s": 6848, "text": "Reverse a string in Java" }, { "code": null, "e": 6889, "s": 6873, "text": "Arrays in C/C++" }, { "code": null, "e": 6912, "s": 6889, "text": "Introduction To PYTHON" } ]
Perl chop Function
This function removes the last character from EXPR, each element of LIST, or $_ if no value is specified. Following is the simple syntax for this function − chop VARIABLE chop( LIST ) chop This function returns the character removed from EXPR and in list context, the character is removed from the last element of LIST. Following is the example code showing its basic usage − #!/usr/bin/perl $string1 = "This is test"; $retval = chop( $string1 ); print " Choped String is : $string1\n"; print " Character removed : $retval\n"; When above code is executed, it produces the following result − Choped String is : This is tes Number of characters removed : t
[ { "code": null, "e": 2460, "s": 2354, "text": "This function removes the last character from EXPR, each element of LIST, or $_ if no value is specified." }, { "code": null, "e": 2511, "s": 2460, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2546, "s": 2511, "text": "chop VARIABLE\n\nchop( LIST )\n\nchop\n" }, { "code": null, "e": 2677, "s": 2546, "text": "This function returns the character removed from EXPR and in list context, the character is removed from the last element of LIST." }, { "code": null, "e": 2733, "s": 2677, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2887, "s": 2733, "text": "#!/usr/bin/perl\n\n$string1 = \"This is test\";\n$retval = chop( $string1 );\n\nprint \" Choped String is : $string1\\n\";\nprint \" Character removed : $retval\\n\";" }, { "code": null, "e": 2951, "s": 2887, "text": "When above code is executed, it produces the following result −" } ]
Trains, Boats and Streams
01 Jun, 2022 We recommend that you read about Time Speed Distance before proceeding on with this topic. If two trains are moving in same direction with speeds a km / hr and b km / hr, then their relative speed would be |a – b| km / hr. If two trains are moving in different directions, i.e., coming towards each other or going away from each other, with speeds a km / hr and b km / hr, then their relative speed would be (a + b) km / hr. Time taken by a train, ‘t’ meters long, to pass a stationary object of length ‘l’ meters would be the time taken by the train to travel ‘t + l’ meters. For example, to cover a platform of 800 m, a train of length 200 m moving at the speed of 10 m / s would be the time taken by the train to cover 800 + 200 = 1000 m at the speed of 10 m / s, i.e., 1000 / 10 = 100 s. To pass a pole or a man or a post (or any stationary object with negligible length as compared to the length of the train, like if the train is 500 m long and a pole is 1 m in length), the time taken by the train would be the time it takes to travel the length of the train. For example, if a train of length 100 m is moving at the speed of 10 m / s, it would take 100 / 10 = 10 s to pass a pole / man / post. If two trains of lengths L1 and L2 are moving in the same direction with speeds S1 and S2, then the time required by faster train to overtake the slower train would be the time taken to cover an equivalent distance of L1 + L2, with relative speed |S1 – S2|, i.e., Time = (L1 + L2) / |S1 – S2|. If two trains of lengths L1 and L2 are moving in opposite directions with speeds S1 and S2, then the time required by the trains to cross each other completely would be the time taken to cover an equivalent distance of L1 + L2, with relative speed (S1 + S2), i.e., Time = (L1 + L2) / (S1 + S2). If two trains started moving towards each other at the same time with speeds S1 and S2 respectively and after meeting, they take ‘T1’ and ‘T2’ seconds respectively, then S1 : S2 = T21/2 : T11/2 If the boat is moving in the direction of the stream, it is said to be going downstream. And if the boat is moving opposite to the direction of stream, it is said to be going upstream. If the speed of boat in still water is B km / hr and speed of the stream is S km / hr, Speed Upstream = B – S km / hrSpeed Downstream = B + S km / hr Speed Upstream = B – S km / hrSpeed Downstream = B + S km / hr Speed Upstream = B – S km / hr Speed Downstream = B + S km / hr If the speed upstream is U km / hr and speed downstream is D km / hr, Speed of boat in still water = 0.5 x (D + U) km / hrSpeed of stream = 0.5 x (D – U) km / hr Speed of boat in still water = 0.5 x (D + U) km / hrSpeed of stream = 0.5 x (D – U) km / hr Speed of boat in still water = 0.5 x (D + U) km / hr Speed of stream = 0.5 x (D – U) km / hr Question 1 : A 100 m long train moving at a speed of 60 km / hr passes a man standing on a pavement near a railway track. Find the time taken by the train to pass the man. Solution : Length of the train = 100 m = 0.1 km Speed of the train = 60 km / hr So, time taken by the train to pass the man = time taken to cover 0.1 km at the speed of 60 km / hr Therefore, time taken by the train to pass the man = 0.1 / 60 hour = (0.1 / 60) x 3600 sec = 6 sec Question 2 : How long does a train 1000 m long moving at a speed of 90 km / hr would take to pass through a 500 m long bridge? Solution : Here, time taken by the train to pass the bridge completely would be the time it takes to cover 1000 + 500 = 1500 m at the speed of 90 km / hr = 90 x (5/18) = 25 m / sec. Therefore, time required = 1500 / 25 = 60 sec = 1 minute Question 3 : A man standing near a railway track observes that a train passes him in 80 seconds but to pass by a 180 m long bridge, the same train takes 200 seconds. Find the speed of the train. Solution : Let the length of the train be L meters. => The train covers L meters in 80 seconds and L + 180 meters in 200 seconds, with the same speed. We know that Speed = Distance / Time. => Speed = L / 80 = (L + 180) / 200 => L / 80 = (L + 180) / 200 => 2.5 L = L + 180 => 1.5 L = 180 => L = 120 Thus, speed of the train = 120 / 80 = 1.5 m / sec Question 4 : Two trains 140 m and 160 m long are moving towards each other on parallel tracks with speeds 40 km / hr and 50 km / hr respectively. How much time would they take to pass each other completely ? Solution : Total distance to be covered = 140 + 160 m = 300 m Relative speed = 40 + 50 = 90 km / hr = 90 x (5 / 18) m / sec = 25 m / sec Therefore, time taken to pass each other = 300 / 25 = 12 sec Question 5 : Two trains 140 m and 160 m long are moving in the same direction on parallel tracks with speeds 40 km / hr and 50 km / hr respectively. How much time would the faster train require to overtake the slower train ? Solution : Total distance to be covered = 140 + 160 m = 300 m Relative speed = 50 – 40 = 10 km / hr = 10 x (5 / 18) m / sec = 50 / 18 m / sec Therefore, time taken by faster train to overtake the slower train = 300 / (50/18) = 108 sec Question 6 : A 500 m long train takes 36 seconds to cross a man walking in the opposite direction at the speed of 10 km / hr. Find the speed of the train. Solution : Let the speed of the train be T km / hr. => Relative speed = T + 10 km / hr => Length of the train = 500 m = 0.5 km We know that Distance = Speed x Time => 0.5 = (T + 10) x (36 / 3600) => 50 = T + 10 => T = 40 km / hr Therefore, speed of the train is 40 km / hr. Question 7 : A non – stop train started from Delhi towards Mumbai and at the same time, another non – stop train started from Mumbai towards Delhi. If after meeting in Bhopal they took 9 and 16 hours respectively to reach their destinations, find the speed of the train that started from Delhi, given that the speed of the train that started from Mumbai was moving at a speed of 90 km / hr. Solution : We know that for two trains starting at the same time, S1 : S2 = T21/2 : T11/2 Here, S2 = 90 km / hr T1 = 9 hrs T2 = 16 hrs => S1 : 90 = 4 : 3 => S1 = 120 km / hr Therefore, speed of train that started from Delhi = 120 km / hr Question 8 : A boatman can row a boat upstream at 14 km / hr and downstream at 20 km / hr. Find the speed of the boat in still water and speed of the stream. Solution : We are given that speed downstream, D = 20 km / hr and speed upstream, U = 14 km / hr Therefore, Speed of boat in still water = 0.5 x (D + U) km / hr = 0.5 x (14 + 20) = 17 km / hr Also, speed of the stream = 0.5 x (D – U) km / hr = 0.5 x (20 – 14) = 3 km / hr Another method : Speed of the stream = 0.5 x (D – U) = 0.5 x 6 = 3 km / hr Speed of the boat in still water = Speed of the stream + Speed Upstream = 3 + 14 = 17 km / hr Question 9 : A boatman can row a boat at the speed of 5 km upstream and 15 km downstream. To cover upstream he needs 2.5 hours and to cover downstream, he needs 1.5 hours. Find the speed of the stream and speed of the boat in still water. Solution : We are given that the boatman covers 5 km upstream in 2.5 hours and 15 km downstream in 10 hours. => Speed upstream, U = 5 / 2.5 = 2 km / hr => Speed downstream, D = 15 / 1.5 = 10 km / hr Therefore, Speed of boat in still water = 0.5 x (D + U) km / hr = 0.5 x (10 + 2) = 6 km / hr Also, speed of the stream = 0.5 x (D – U) km / hr = 0.5 x (10 – 2) = 4 km / hr Question 10 : A man has to go from a port to an island and return. He can row a boat with the speed 7 km / hr in still water. The speed of the stream is 2 km / hr. If he takes 56 minutes to complete the round trip, find the distance between the port and the island. Solution : Speed upstream = 7 – 2 = 5 km / hr Speed downstream = 7 + 2 = 9 km / hr Let the distance between the port and the island be D km. Also, we know that Time = Distance / Speed => (D/5) + (D/9) = 56/60 => (14 D) / 45 = 56 / 60 => D = 3 km Therefore, the distance between the port and the island = 3 km Question 11 : In a boat race, a person rows a boat 6 km upstream and return to the starting point in 4 hours. If the speed of the stream is 2 km / hr, find the speed of the boat in still water. Solution : Let the speed of the boat in still water be B km / hr. => Speed upstream = (B – 2) km / hr => Speed downstream = (B + 2) km / hr We know that Time = Distance / Speed => 6/(B-2) + 6/(B+2) = 4 => 6 B + 12 + 6 B – 12 = 4 (B – 2) (B + 2) => 12 B = 4 (B – 2) (B + 2) => 3 B = B2 – 4 => B2 – 3 B – 4 = 0 => (B + 1) (B – 4) = 0 => B = 4 km / hr (Speed cannot be negative) Question 12 : A racer can row a boat 30 km upstream and 44 km downstream in 10 hours. Also, he can row 40 km upstream and 55 km downstream in 13 hours. Find the speed of the boat in still water and speed of the stream. Solution : Let the speed upstream be U km / hr and speed downstream be D km / hr. We know that Distance / Speed = Time => (30 / U) + (44 / D) = 10 and (40 / U) + (55 / D) = 13 Solving the above pair of linear equations, we get D = 11 km / hr U = 5 km / hr Therefore, Speed of boat in still water = 0.5 x (D + U) km / hr = 0.5 x (11 + 5) = 8 km / hr Also, speed of the stream = 0.5 x (D – U) km / hr = 0.5 x (11 – 5) = 3 km / hr Program on Trains Find the minimum cost to reach destination using a train Program to find Length of Bridge using Speed and Length of Train Maximum trains for which stoppage can be provided Program on Boats and Streams Distance between two points travelled by a boat Speed of boat upstream and downstream Speed of boat in still water from speed of stream and times taken Find speed of man from speed of stream and ratio of time with up and down streams Speed of boat in still water from speed of stream and times taken This article has been contributed by Nishant Arora Please write comments if you have any doubts related to the topic discussed above, or if you are facing difficulty in any question or if you would like to discuss a question other than those mentioned above. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rathichirag07 namanaggarwal250 Placements QA - Placements Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2022" }, { "code": null, "e": 145, "s": 52, "text": "We recommend that you read about Time Speed Distance before proceeding on with this topic. " }, { "code": null, "e": 279, "s": 147, "text": "If two trains are moving in same direction with speeds a km / hr and b km / hr, then their relative speed would be |a – b| km / hr." }, { "code": null, "e": 481, "s": 279, "text": "If two trains are moving in different directions, i.e., coming towards each other or going away from each other, with speeds a km / hr and b km / hr, then their relative speed would be (a + b) km / hr." }, { "code": null, "e": 848, "s": 481, "text": "Time taken by a train, ‘t’ meters long, to pass a stationary object of length ‘l’ meters would be the time taken by the train to travel ‘t + l’ meters. For example, to cover a platform of 800 m, a train of length 200 m moving at the speed of 10 m / s would be the time taken by the train to cover 800 + 200 = 1000 m at the speed of 10 m / s, i.e., 1000 / 10 = 100 s." }, { "code": null, "e": 1258, "s": 848, "text": "To pass a pole or a man or a post (or any stationary object with negligible length as compared to the length of the train, like if the train is 500 m long and a pole is 1 m in length), the time taken by the train would be the time it takes to travel the length of the train. For example, if a train of length 100 m is moving at the speed of 10 m / s, it would take 100 / 10 = 10 s to pass a pole / man / post." }, { "code": null, "e": 1552, "s": 1258, "text": "If two trains of lengths L1 and L2 are moving in the same direction with speeds S1 and S2, then the time required by faster train to overtake the slower train would be the time taken to cover an equivalent distance of L1 + L2, with relative speed |S1 – S2|, i.e., Time = (L1 + L2) / |S1 – S2|." }, { "code": null, "e": 1847, "s": 1552, "text": "If two trains of lengths L1 and L2 are moving in opposite directions with speeds S1 and S2, then the time required by the trains to cross each other completely would be the time taken to cover an equivalent distance of L1 + L2, with relative speed (S1 + S2), i.e., Time = (L1 + L2) / (S1 + S2)." }, { "code": null, "e": 2041, "s": 1847, "text": "If two trains started moving towards each other at the same time with speeds S1 and S2 respectively and after meeting, they take ‘T1’ and ‘T2’ seconds respectively, then S1 : S2 = T21/2 : T11/2" }, { "code": null, "e": 2230, "s": 2045, "text": "If the boat is moving in the direction of the stream, it is said to be going downstream. And if the boat is moving opposite to the direction of stream, it is said to be going upstream." }, { "code": null, "e": 2380, "s": 2230, "text": "If the speed of boat in still water is B km / hr and speed of the stream is S km / hr, Speed Upstream = B – S km / hrSpeed Downstream = B + S km / hr" }, { "code": null, "e": 2443, "s": 2380, "text": "Speed Upstream = B – S km / hrSpeed Downstream = B + S km / hr" }, { "code": null, "e": 2474, "s": 2443, "text": "Speed Upstream = B – S km / hr" }, { "code": null, "e": 2507, "s": 2474, "text": "Speed Downstream = B + S km / hr" }, { "code": null, "e": 2669, "s": 2507, "text": "If the speed upstream is U km / hr and speed downstream is D km / hr, Speed of boat in still water = 0.5 x (D + U) km / hrSpeed of stream = 0.5 x (D – U) km / hr" }, { "code": null, "e": 2761, "s": 2669, "text": "Speed of boat in still water = 0.5 x (D + U) km / hrSpeed of stream = 0.5 x (D – U) km / hr" }, { "code": null, "e": 2814, "s": 2761, "text": "Speed of boat in still water = 0.5 x (D + U) km / hr" }, { "code": null, "e": 2854, "s": 2814, "text": "Speed of stream = 0.5 x (D – U) km / hr" }, { "code": null, "e": 3308, "s": 2856, "text": "Question 1 : A 100 m long train moving at a speed of 60 km / hr passes a man standing on a pavement near a railway track. Find the time taken by the train to pass the man. Solution : Length of the train = 100 m = 0.1 km Speed of the train = 60 km / hr So, time taken by the train to pass the man = time taken to cover 0.1 km at the speed of 60 km / hr Therefore, time taken by the train to pass the man = 0.1 / 60 hour = (0.1 / 60) x 3600 sec = 6 sec " }, { "code": null, "e": 3675, "s": 3308, "text": "Question 2 : How long does a train 1000 m long moving at a speed of 90 km / hr would take to pass through a 500 m long bridge? Solution : Here, time taken by the train to pass the bridge completely would be the time it takes to cover 1000 + 500 = 1500 m at the speed of 90 km / hr = 90 x (5/18) = 25 m / sec. Therefore, time required = 1500 / 25 = 60 sec = 1 minute " }, { "code": null, "e": 4219, "s": 3675, "text": "Question 3 : A man standing near a railway track observes that a train passes him in 80 seconds but to pass by a 180 m long bridge, the same train takes 200 seconds. Find the speed of the train. Solution : Let the length of the train be L meters. => The train covers L meters in 80 seconds and L + 180 meters in 200 seconds, with the same speed. We know that Speed = Distance / Time. => Speed = L / 80 = (L + 180) / 200 => L / 80 = (L + 180) / 200 => 2.5 L = L + 180 => 1.5 L = 180 => L = 120 Thus, speed of the train = 120 / 80 = 1.5 m / sec " }, { "code": null, "e": 4626, "s": 4219, "text": "Question 4 : Two trains 140 m and 160 m long are moving towards each other on parallel tracks with speeds 40 km / hr and 50 km / hr respectively. How much time would they take to pass each other completely ? Solution : Total distance to be covered = 140 + 160 m = 300 m Relative speed = 40 + 50 = 90 km / hr = 90 x (5 / 18) m / sec = 25 m / sec Therefore, time taken to pass each other = 300 / 25 = 12 sec " }, { "code": null, "e": 5087, "s": 4626, "text": "Question 5 : Two trains 140 m and 160 m long are moving in the same direction on parallel tracks with speeds 40 km / hr and 50 km / hr respectively. How much time would the faster train require to overtake the slower train ? Solution : Total distance to be covered = 140 + 160 m = 300 m Relative speed = 50 – 40 = 10 km / hr = 10 x (5 / 18) m / sec = 50 / 18 m / sec Therefore, time taken by faster train to overtake the slower train = 300 / (50/18) = 108 sec " }, { "code": null, "e": 5517, "s": 5087, "text": "Question 6 : A 500 m long train takes 36 seconds to cross a man walking in the opposite direction at the speed of 10 km / hr. Find the speed of the train. Solution : Let the speed of the train be T km / hr. => Relative speed = T + 10 km / hr => Length of the train = 500 m = 0.5 km We know that Distance = Speed x Time => 0.5 = (T + 10) x (36 / 3600) => 50 = T + 10 => T = 40 km / hr Therefore, speed of the train is 40 km / hr. " }, { "code": null, "e": 6149, "s": 5517, "text": "Question 7 : A non – stop train started from Delhi towards Mumbai and at the same time, another non – stop train started from Mumbai towards Delhi. If after meeting in Bhopal they took 9 and 16 hours respectively to reach their destinations, find the speed of the train that started from Delhi, given that the speed of the train that started from Mumbai was moving at a speed of 90 km / hr. Solution : We know that for two trains starting at the same time, S1 : S2 = T21/2 : T11/2 Here, S2 = 90 km / hr T1 = 9 hrs T2 = 16 hrs => S1 : 90 = 4 : 3 => S1 = 120 km / hr Therefore, speed of train that started from Delhi = 120 km / hr " }, { "code": null, "e": 6580, "s": 6149, "text": "Question 8 : A boatman can row a boat upstream at 14 km / hr and downstream at 20 km / hr. Find the speed of the boat in still water and speed of the stream. Solution : We are given that speed downstream, D = 20 km / hr and speed upstream, U = 14 km / hr Therefore, Speed of boat in still water = 0.5 x (D + U) km / hr = 0.5 x (14 + 20) = 17 km / hr Also, speed of the stream = 0.5 x (D – U) km / hr = 0.5 x (20 – 14) = 3 km / hr " }, { "code": null, "e": 7360, "s": 6580, "text": "Another method : Speed of the stream = 0.5 x (D – U) = 0.5 x 6 = 3 km / hr Speed of the boat in still water = Speed of the stream + Speed Upstream = 3 + 14 = 17 km / hr Question 9 : A boatman can row a boat at the speed of 5 km upstream and 15 km downstream. To cover upstream he needs 2.5 hours and to cover downstream, he needs 1.5 hours. Find the speed of the stream and speed of the boat in still water. Solution : We are given that the boatman covers 5 km upstream in 2.5 hours and 15 km downstream in 10 hours. => Speed upstream, U = 5 / 2.5 = 2 km / hr => Speed downstream, D = 15 / 1.5 = 10 km / hr Therefore, Speed of boat in still water = 0.5 x (D + U) km / hr = 0.5 x (10 + 2) = 6 km / hr Also, speed of the stream = 0.5 x (D – U) km / hr = 0.5 x (10 – 2) = 4 km / hr " }, { "code": null, "e": 7936, "s": 7360, "text": "Question 10 : A man has to go from a port to an island and return. He can row a boat with the speed 7 km / hr in still water. The speed of the stream is 2 km / hr. If he takes 56 minutes to complete the round trip, find the distance between the port and the island. Solution : Speed upstream = 7 – 2 = 5 km / hr Speed downstream = 7 + 2 = 9 km / hr Let the distance between the port and the island be D km. Also, we know that Time = Distance / Speed => (D/5) + (D/9) = 56/60 => (14 D) / 45 = 56 / 60 => D = 3 km Therefore, the distance between the port and the island = 3 km " }, { "code": null, "e": 8507, "s": 7936, "text": "Question 11 : In a boat race, a person rows a boat 6 km upstream and return to the starting point in 4 hours. If the speed of the stream is 2 km / hr, find the speed of the boat in still water. Solution : Let the speed of the boat in still water be B km / hr. => Speed upstream = (B – 2) km / hr => Speed downstream = (B + 2) km / hr We know that Time = Distance / Speed => 6/(B-2) + 6/(B+2) = 4 => 6 B + 12 + 6 B – 12 = 4 (B – 2) (B + 2) => 12 B = 4 (B – 2) (B + 2) => 3 B = B2 – 4 => B2 – 3 B – 4 = 0 => (B + 1) (B – 4) = 0 => B = 4 km / hr (Speed cannot be negative) " }, { "code": null, "e": 9155, "s": 8507, "text": "Question 12 : A racer can row a boat 30 km upstream and 44 km downstream in 10 hours. Also, he can row 40 km upstream and 55 km downstream in 13 hours. Find the speed of the boat in still water and speed of the stream. Solution : Let the speed upstream be U km / hr and speed downstream be D km / hr. We know that Distance / Speed = Time => (30 / U) + (44 / D) = 10 and (40 / U) + (55 / D) = 13 Solving the above pair of linear equations, we get D = 11 km / hr U = 5 km / hr Therefore, Speed of boat in still water = 0.5 x (D + U) km / hr = 0.5 x (11 + 5) = 8 km / hr Also, speed of the stream = 0.5 x (D – U) km / hr = 0.5 x (11 – 5) = 3 km / hr " }, { "code": null, "e": 9177, "s": 9157, "text": "Program on Trains " }, { "code": null, "e": 9234, "s": 9177, "text": "Find the minimum cost to reach destination using a train" }, { "code": null, "e": 9299, "s": 9234, "text": "Program to find Length of Bridge using Speed and Length of Train" }, { "code": null, "e": 9349, "s": 9299, "text": "Maximum trains for which stoppage can be provided" }, { "code": null, "e": 9380, "s": 9349, "text": "Program on Boats and Streams " }, { "code": null, "e": 9428, "s": 9380, "text": "Distance between two points travelled by a boat" }, { "code": null, "e": 9466, "s": 9428, "text": "Speed of boat upstream and downstream" }, { "code": null, "e": 9532, "s": 9466, "text": "Speed of boat in still water from speed of stream and times taken" }, { "code": null, "e": 9614, "s": 9532, "text": "Find speed of man from speed of stream and ratio of time with up and down streams" }, { "code": null, "e": 9680, "s": 9614, "text": "Speed of boat in still water from speed of stream and times taken" }, { "code": null, "e": 9732, "s": 9680, "text": "This article has been contributed by Nishant Arora " }, { "code": null, "e": 9941, "s": 9732, "text": "Please write comments if you have any doubts related to the topic discussed above, or if you are facing difficulty in any question or if you would like to discuss a question other than those mentioned above. " }, { "code": null, "e": 10066, "s": 9941, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10080, "s": 10066, "text": "rathichirag07" }, { "code": null, "e": 10097, "s": 10080, "text": "namanaggarwal250" }, { "code": null, "e": 10108, "s": 10097, "text": "Placements" }, { "code": null, "e": 10124, "s": 10108, "text": "QA - Placements" } ]
Ways to print escape characters in Python
17 Nov, 2017 Escape characters are characters that are generally used to perform certain tasks and their usage in code directs the compiler to take a suitable action mapped to that character. Example : '\n' --> Leaves a line '\t' --> Leaves a space # Python code to demonstrate escape character# string ch = "I\nLove\tGeeksforgeeks" print ("The string after resolving escape character is : ")print (ch) Output : The string after resolving escape character is : I Love Geeksforgeeks But in certain cases it is desired not to resolve escapes, i.e the entire unresolved string hasto be printed. These are achieved by following ways. This function returns a string in its printable format, i.e doesn’t resolve the escape sequences. # Python code to demonstrate printing # escape characters from repr() # initializing target string ch = "I\nLove\tGeeksforgeeks" print ("The string without repr() is : ")print (ch) print ("\r") print ("The string after using repr() is : ")print (repr(ch)) Output : The string without repr() is : I Love Geeksforgeeks The string after using repr() is : 'I\nLove\tGeeksforgeeks' Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from the resolution of escape characters. # Python code to demonstrate printing # escape characters from "r" or "R" # initializing target string ch = "I\nLove\tGeeksforgeeks" print ("The string without r / R is : ")print (ch) print ("\r") # using "r" to prevent resolutionch1 = r"I\nLove\tGeeksforgeeks" print ("The string after using r is : ")print (ch1) print ("\r") # using "R" to prevent resolutionch2 = R"I\nLove\tGeeksforgeeks" print ("The string after using R is : ")print (ch2) Output : The string without r/R is : I Love Geeksforgeeks The string after using r is : I\nLove\tGeeksforgeeks The string after using R is : I\nLove\tGeeksforgeeks Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Nov, 2017" }, { "code": null, "e": 231, "s": 52, "text": "Escape characters are characters that are generally used to perform certain tasks and their usage in code directs the compiler to take a suitable action mapped to that character." }, { "code": null, "e": 241, "s": 231, "text": "Example :" }, { "code": null, "e": 294, "s": 241, "text": "'\\n' --> Leaves a line\n'\\t' --> Leaves a space \n" }, { "code": "# Python code to demonstrate escape character# string ch = \"I\\nLove\\tGeeksforgeeks\" print (\"The string after resolving escape character is : \")print (ch)", "e": 451, "s": 294, "text": null }, { "code": null, "e": 460, "s": 451, "text": "Output :" }, { "code": null, "e": 535, "s": 460, "text": "The string after resolving escape character is : \nI\nLove Geeksforgeeks\n" }, { "code": null, "e": 683, "s": 535, "text": "But in certain cases it is desired not to resolve escapes, i.e the entire unresolved string hasto be printed. These are achieved by following ways." }, { "code": null, "e": 781, "s": 683, "text": "This function returns a string in its printable format, i.e doesn’t resolve the escape sequences." }, { "code": "# Python code to demonstrate printing # escape characters from repr() # initializing target string ch = \"I\\nLove\\tGeeksforgeeks\" print (\"The string without repr() is : \")print (ch) print (\"\\r\") print (\"The string after using repr() is : \")print (repr(ch))", "e": 1041, "s": 781, "text": null }, { "code": null, "e": 1050, "s": 1041, "text": "Output :" }, { "code": null, "e": 1170, "s": 1050, "text": "The string without repr() is : \nI\nLove Geeksforgeeks\n\n\nThe string after using repr() is : \n'I\\nLove\\tGeeksforgeeks'\n" }, { "code": null, "e": 1304, "s": 1170, "text": "Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from the resolution of escape characters." }, { "code": "# Python code to demonstrate printing # escape characters from \"r\" or \"R\" # initializing target string ch = \"I\\nLove\\tGeeksforgeeks\" print (\"The string without r / R is : \")print (ch) print (\"\\r\") # using \"r\" to prevent resolutionch1 = r\"I\\nLove\\tGeeksforgeeks\" print (\"The string after using r is : \")print (ch1) print (\"\\r\") # using \"R\" to prevent resolutionch2 = R\"I\\nLove\\tGeeksforgeeks\" print (\"The string after using R is : \")print (ch2)", "e": 1756, "s": 1304, "text": null }, { "code": null, "e": 1765, "s": 1756, "text": "Output :" }, { "code": null, "e": 1931, "s": 1765, "text": "The string without r/R is : \nI\nLove Geeksforgeeks\n\n\nThe string after using r is : \nI\\nLove\\tGeeksforgeeks\n\n\nThe string after using R is : \nI\\nLove\\tGeeksforgeeks\n" }, { "code": null, "e": 1938, "s": 1931, "text": "Python" }, { "code": null, "e": 2036, "s": 1938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2078, "s": 2036, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2100, "s": 2078, "text": "Enumerate() in Python" }, { "code": null, "e": 2135, "s": 2100, "text": "Read a file line by line in Python" }, { "code": null, "e": 2161, "s": 2135, "text": "Python String | replace()" }, { "code": null, "e": 2193, "s": 2161, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2222, "s": 2193, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2249, "s": 2222, "text": "Python Classes and Objects" }, { "code": null, "e": 2279, "s": 2249, "text": "Iterate over a list in Python" }, { "code": null, "e": 2300, "s": 2279, "text": "Python OOPs Concepts" } ]
GATE | GATE-CS-2016 (Set 2) | Question 56 - GeeksforGeeks
16 Sep, 2021 A student wrote two context-free grammars G1 and G2 for generating a single C-like array declaration. The dimension of the array is at least one. For example, int a[10][3]; The grammars use D as the start symbol, and use six terminal symbols int ; id [ ] num. Grammar G1 D → int L; L → id [E E → num] E → num] [E Grammar G2 D → int L; L → id E E → E[num] E → [num] Which of the grammars correctly generate the declaration mentioned above? (A) Both G1 and G2(B) Only G1(C) Only G2(D) Neither G1 nor G2Answer: (A)Explanation: Context-Free Grammars A context-free grammar (CFG) is a set of recursive rewriting rules (or productions) used to generate patterns of strings. A CFG consists of the following components:1) A set of terminal symbols, which are the characters of the alphabet that appear in the strings generated by the grammar.2) A set of nonterminal symbols, which are placeholders for patterns of terminal symbols that can be generated by the nonterminal symbols.3) A set of productions, which are rules for replacing (or rewriting) nonterminal symbols (on the left side of the production) in a string with other nonterminal or terminal symbols (on the right side of the production).4) A start symbol, which is a special nonterminal symbol that appears in the initial string generated by the grammar. To generate a string of terminal symbols from a CFG, we:1) Begin with a string consisting of the start symbol;2) Apply one of the productions with the start symbol on the left hand size, replacing the start symbol with the right hand side of the production;3) Repeat the process of selecting nonterminal symbols in the string, and replacing them with the right hand side of some corresponding production, until all nonterminals have been replaced by terminal symbols. Given a grammar G with start symbol S, if there is some sequence of productions that, when applied to the initial string S, result in the string s, then s is in L(G), the language of the grammar. We need to check which of the two grammars correctly generate “int a[10][3];”. This means we need to check if int id[num][num]; Grammar G1 D → int L; L → id [E E → num] E → num] [E Grammar G2 D → int L; L → id E E → E[num] E → [num] YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0017:05 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question parthbanathia GATE-CS-2016 (Set 2) GATE-GATE-CS-2016 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE CS 2012 | Question 40
[ { "code": null, "e": 24169, "s": 24141, "text": "\n16 Sep, 2021" }, { "code": null, "e": 24328, "s": 24169, "text": "A student wrote two context-free grammars G1 and G2 for generating a single C-like array declaration. The dimension of the array is at least one. For example," }, { "code": null, "e": 24343, "s": 24328, "text": "int a[10][3]; " }, { "code": null, "e": 24430, "s": 24343, "text": "The grammars use D as the start symbol, and use six terminal symbols int ; id [ ] num." }, { "code": null, "e": 24537, "s": 24430, "text": "Grammar G1\nD → int L;\nL → id [E\nE → num]\nE → num] [E\n\nGrammar G2\nD → int L;\nL → id E\nE → E[num]\nE → [num] " }, { "code": null, "e": 24611, "s": 24537, "text": "Which of the grammars correctly generate the declaration mentioned above?" }, { "code": null, "e": 24718, "s": 24611, "text": "(A) Both G1 and G2(B) Only G1(C) Only G2(D) Neither G1 nor G2Answer: (A)Explanation: Context-Free Grammars" }, { "code": null, "e": 24840, "s": 24718, "text": "A context-free grammar (CFG) is a set of recursive rewriting rules (or productions) used to generate patterns of strings." }, { "code": null, "e": 25482, "s": 24840, "text": "A CFG consists of the following components:1) A set of terminal symbols, which are the characters of the alphabet that appear in the strings generated by the grammar.2) A set of nonterminal symbols, which are placeholders for patterns of terminal symbols that can be generated by the nonterminal symbols.3) A set of productions, which are rules for replacing (or rewriting) nonterminal symbols (on the left side of the production) in a string with other nonterminal or terminal symbols (on the right side of the production).4) A start symbol, which is a special nonterminal symbol that appears in the initial string generated by the grammar." }, { "code": null, "e": 25950, "s": 25482, "text": "To generate a string of terminal symbols from a CFG, we:1) Begin with a string consisting of the start symbol;2) Apply one of the productions with the start symbol on the left hand size, replacing the start symbol with the right hand side of the production;3) Repeat the process of selecting nonterminal symbols in the string, and replacing them with the right hand side of some corresponding production, until all nonterminals have been replaced by terminal symbols." }, { "code": null, "e": 26146, "s": 25950, "text": "Given a grammar G with start symbol S, if there is some sequence of productions that, when applied to the initial string S, result in the string s, then s is in L(G), the language of the grammar." }, { "code": null, "e": 26274, "s": 26146, "text": "We need to check which of the two grammars correctly generate “int a[10][3];”. This means we need to check if int id[num][num];" }, { "code": null, "e": 26381, "s": 26274, "text": "Grammar G1\nD → int L;\nL → id [E\nE → num]\nE → num] [E\n\nGrammar G2\nD → int L;\nL → id E\nE → E[num]\nE → [num] " }, { "code": null, "e": 27296, "s": 26381, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0017:05 / 59:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4ab8S2Qs7h8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 27310, "s": 27296, "text": "parthbanathia" }, { "code": null, "e": 27331, "s": 27310, "text": "GATE-CS-2016 (Set 2)" }, { "code": null, "e": 27357, "s": 27331, "text": "GATE-GATE-CS-2016 (Set 2)" }, { "code": null, "e": 27362, "s": 27357, "text": "GATE" }, { "code": null, "e": 27460, "s": 27362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27469, "s": 27460, "text": "Comments" }, { "code": null, "e": 27482, "s": 27469, "text": "Old Comments" }, { "code": null, "e": 27524, "s": 27482, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 27566, "s": 27524, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 27600, "s": 27566, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 27642, "s": 27600, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 27676, "s": 27642, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 27718, "s": 27676, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 27751, "s": 27718, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 27793, "s": 27751, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 27847, "s": 27793, "text": "C++ Program to count Vowels in a string using Pointer" } ]
How to build a simple Neural Network from scratch with Python | by Konstantinos Kitsios | Towards Data Science
Neural Networks are becoming more and more popular every day and as a core field of Machine Learning and Artificial Intelligence, they are going to play a major role in technology, science and industry over the next years. This high popularity has given rise to many frameworks that allow you to implement Neural Networks very easily without knowing the complete theory behind them. On the other side, the strict theoretical explanation of neural network mechanisms demands some knowledge on high-level mathematics. In this post, we will do something between. Specifically, in order to get a more solid understanding of neural networks, we will go through the actual implementation of a NN from scratch without using any framework, but we will omit the proofs for the sake of simplicity. This may be a bit more difficult than using a framework but you will gain a much better understanding of the mechanism behind the algorithm. Of course, in large scale projects a framework implementation is preferred as it is easier and faster to set up. The tools used in this tutorial are just Python with numpy library (Scientific library for Linear Algebra operations). Supposing that you have python and pip installed, you can install numpy by running this command: pip install numpy A Neural Network is actually a function of many variables: It takes an input, makes computations and produces an output. We like to visualize it as neurons in different layers, with each neuron in a layer connected with all neurons in the previous and the next layer. All the computations take place inside those neurons and depend on the weights that connect the neurons with each other. So all we have to do is learn the right weights in order to get the desired output. Their structure is generally very complex including a lot of layers and even more than a million (Dec 2020 Update: GPT-3 now uses 175B parameters! ) neurons in order to be able to handle the large datasets of our era. However, in order to understand how large deep neural networks work one should start with the simplest ones. Consequently, below we will implement a very simple network with 2 layers. In order to do that we need a very simple dataset as well, so we will use the XOR dataset in our example, as shown below. A and B are the 2 inputs of the NN and A XOR B is the output. We will try to make our NN learn weights such that whatever pair of A and B it takes as input, it will return the corresponding result. So, let’s start! First, we need to define the structure of our Neural Network. Because our dataset is relatively simple, a network with just a hidden layer will do fine. So we will have an input layer, a hidden layer and an output layer. Next, we need an activation function. The sigmoid function is a good choice for the last layer because it outputs values between 0 and 1 while tanh (hyperbolic tangent) works better in the hidden layer, but every other commonly used function will work(e.g. ReLU). So the structure of our Neural Network will look like this: Here, the parameters to be learned are the weights W1, W2 and the biases b1, b2. As you can see W1 and b1 connect the input layer with the hidden layer while W2, b2 connect the hidden layer with the output layer. From the basic theory we know that the activations A1 and A2 are calculated as follows: A1 = h(W1*X + b1)A2 = g(W2*A1 + b2) where g and h are the two activation functions we chose (for us sigmoid and tanh) and W1, W1, b1, b2 are generally Matrices. Now let’s jump into the actual code. The code style follows the guidelines proposed by prof. Andrew Ng at this course in general. Note: You can find the fully working code in my repository here First we will implement our sigmoid activation function defined as follows: g(z) = 1/(1+e^(-z)) where z will be a matrix in general. Luckily numpy supports calculations with matrices so the code is relatively simple: Next, we have to initialize our parameters. Weight matrices W1 and W2 will be randomly initialized from a normal distribution while biases b1 and b2 will be initialized to zero. The function initialize_parameters(n_x, n_h, n_y) takes as input the number of units in each of the 3 layers and initializes the parameters properly: The next step is to implement the Forward Propagation. The function forward_prop(X, parameters) takes as input the neural network input matrix X and the parameters dictionary and returns the output of the NN A2 with a cache dictionary that will be used later in backpropagation. We now have to compute the loss function. We will use the Cross-Entropy Loss function. Calculate_cost(A2, Y) takes as input the result of the NN A2 and the ground truth matrix Y and returns the cross-entropy cost: Now the most difficult part of the Neural Network algorithm, Back Propagation. The code here may seem a bit weird and difficult to understand but we will not dive into details of why it works here. This function will return the gradients of the Loss function with respect to the 4 parameters of our network(W1, W2, b1, b2): Nice, now we have all the gradients of the Loss function, so we can proceed to the actual learning! We will use Gradient Descent algorithm to update our parameters and make our model learn with the learning rate passed as a parameter: By now we have implemented all the functions needed for one circle of training. Now, all we have to do is just put them all together inside a function called model() and call model() from the main program. Model() function takes as input the features matrix X, the labels matrix Y, the number of units n_x, n_h, n_y, the number of iterations we want our Gradient Descent algorithm to run and the learning rate of Gradient Descent and combines all the functions above to return the trained parameters of our model: The training part is now over. The function above will return the trained parameters of our NN. Now we just have to make our prediction. The function predict(X, parameters) takes as input the matrix X with elements the 2 numbers for which we want to compute the XOR function and the trained parameters of the model and returns the desired result y_predict by using a threshold of 0.5: We are done with all the functions needed finally. Now let’s go to the main program and declare our matrices X, Y and the hyperparameters n_x, n_h, n_y, num_of_iters, learning_rate: Having all the above set up, training the model on them is as easy as calling this line of code: Finally, let’s make our prediction for a random pair of numbers, let’s say (1,1): That was the actual code! Let’s see our results. If we run our file, let’s say xor_nn.py, with this command python xor_nn.py we get the following result, which is indeed correct because 1XOR1=0. That’s it! We have trained a Neural Network from scratch using just Python. Of course, in order to train larger networks with many layers and hidden units you may need to use some variations of the algorithms above, for example, you may need to use Batch Gradient Descent instead of Gradient Descent or use many more layers but the main idea of a simple NN is as described above. Feel free to play with the hyperparameters yourself and try different architectures of the Neural Network. For example, you can try a smaller number of iterations because the Cost seems to be going down quickly and 1000 of them may be a bit large. Remember that you can find the fully working code in my GitLab repository here. Thanks for reading and I will be glad to discuss any questions or corrections you may have :) Find me on LinkedIn or my webpage if you want to talk about Machine Learning or anything else.
[ { "code": null, "e": 688, "s": 172, "text": "Neural Networks are becoming more and more popular every day and as a core field of Machine Learning and Artificial Intelligence, they are going to play a major role in technology, science and industry over the next years. This high popularity has given rise to many frameworks that allow you to implement Neural Networks very easily without knowing the complete theory behind them. On the other side, the strict theoretical explanation of neural network mechanisms demands some knowledge on high-level mathematics." }, { "code": null, "e": 1214, "s": 688, "text": "In this post, we will do something between. Specifically, in order to get a more solid understanding of neural networks, we will go through the actual implementation of a NN from scratch without using any framework, but we will omit the proofs for the sake of simplicity. This may be a bit more difficult than using a framework but you will gain a much better understanding of the mechanism behind the algorithm. Of course, in large scale projects a framework implementation is preferred as it is easier and faster to set up." }, { "code": null, "e": 1430, "s": 1214, "text": "The tools used in this tutorial are just Python with numpy library (Scientific library for Linear Algebra operations). Supposing that you have python and pip installed, you can install numpy by running this command:" }, { "code": null, "e": 1448, "s": 1430, "text": "pip install numpy" }, { "code": null, "e": 1921, "s": 1448, "text": "A Neural Network is actually a function of many variables: It takes an input, makes computations and produces an output. We like to visualize it as neurons in different layers, with each neuron in a layer connected with all neurons in the previous and the next layer. All the computations take place inside those neurons and depend on the weights that connect the neurons with each other. So all we have to do is learn the right weights in order to get the desired output." }, { "code": null, "e": 2248, "s": 1921, "text": "Their structure is generally very complex including a lot of layers and even more than a million (Dec 2020 Update: GPT-3 now uses 175B parameters! ) neurons in order to be able to handle the large datasets of our era. However, in order to understand how large deep neural networks work one should start with the simplest ones." }, { "code": null, "e": 2643, "s": 2248, "text": "Consequently, below we will implement a very simple network with 2 layers. In order to do that we need a very simple dataset as well, so we will use the XOR dataset in our example, as shown below. A and B are the 2 inputs of the NN and A XOR B is the output. We will try to make our NN learn weights such that whatever pair of A and B it takes as input, it will return the corresponding result." }, { "code": null, "e": 2660, "s": 2643, "text": "So, let’s start!" }, { "code": null, "e": 3205, "s": 2660, "text": "First, we need to define the structure of our Neural Network. Because our dataset is relatively simple, a network with just a hidden layer will do fine. So we will have an input layer, a hidden layer and an output layer. Next, we need an activation function. The sigmoid function is a good choice for the last layer because it outputs values between 0 and 1 while tanh (hyperbolic tangent) works better in the hidden layer, but every other commonly used function will work(e.g. ReLU). So the structure of our Neural Network will look like this:" }, { "code": null, "e": 3506, "s": 3205, "text": "Here, the parameters to be learned are the weights W1, W2 and the biases b1, b2. As you can see W1 and b1 connect the input layer with the hidden layer while W2, b2 connect the hidden layer with the output layer. From the basic theory we know that the activations A1 and A2 are calculated as follows:" }, { "code": null, "e": 3542, "s": 3506, "text": "A1 = h(W1*X + b1)A2 = g(W2*A1 + b2)" }, { "code": null, "e": 3667, "s": 3542, "text": "where g and h are the two activation functions we chose (for us sigmoid and tanh) and W1, W1, b1, b2 are generally Matrices." }, { "code": null, "e": 3797, "s": 3667, "text": "Now let’s jump into the actual code. The code style follows the guidelines proposed by prof. Andrew Ng at this course in general." }, { "code": null, "e": 3861, "s": 3797, "text": "Note: You can find the fully working code in my repository here" }, { "code": null, "e": 4078, "s": 3861, "text": "First we will implement our sigmoid activation function defined as follows: g(z) = 1/(1+e^(-z)) where z will be a matrix in general. Luckily numpy supports calculations with matrices so the code is relatively simple:" }, { "code": null, "e": 4406, "s": 4078, "text": "Next, we have to initialize our parameters. Weight matrices W1 and W2 will be randomly initialized from a normal distribution while biases b1 and b2 will be initialized to zero. The function initialize_parameters(n_x, n_h, n_y) takes as input the number of units in each of the 3 layers and initializes the parameters properly:" }, { "code": null, "e": 4685, "s": 4406, "text": "The next step is to implement the Forward Propagation. The function forward_prop(X, parameters) takes as input the neural network input matrix X and the parameters dictionary and returns the output of the NN A2 with a cache dictionary that will be used later in backpropagation." }, { "code": null, "e": 4899, "s": 4685, "text": "We now have to compute the loss function. We will use the Cross-Entropy Loss function. Calculate_cost(A2, Y) takes as input the result of the NN A2 and the ground truth matrix Y and returns the cross-entropy cost:" }, { "code": null, "e": 5223, "s": 4899, "text": "Now the most difficult part of the Neural Network algorithm, Back Propagation. The code here may seem a bit weird and difficult to understand but we will not dive into details of why it works here. This function will return the gradients of the Loss function with respect to the 4 parameters of our network(W1, W2, b1, b2):" }, { "code": null, "e": 5458, "s": 5223, "text": "Nice, now we have all the gradients of the Loss function, so we can proceed to the actual learning! We will use Gradient Descent algorithm to update our parameters and make our model learn with the learning rate passed as a parameter:" }, { "code": null, "e": 5664, "s": 5458, "text": "By now we have implemented all the functions needed for one circle of training. Now, all we have to do is just put them all together inside a function called model() and call model() from the main program." }, { "code": null, "e": 5972, "s": 5664, "text": "Model() function takes as input the features matrix X, the labels matrix Y, the number of units n_x, n_h, n_y, the number of iterations we want our Gradient Descent algorithm to run and the learning rate of Gradient Descent and combines all the functions above to return the trained parameters of our model:" }, { "code": null, "e": 6357, "s": 5972, "text": "The training part is now over. The function above will return the trained parameters of our NN. Now we just have to make our prediction. The function predict(X, parameters) takes as input the matrix X with elements the 2 numbers for which we want to compute the XOR function and the trained parameters of the model and returns the desired result y_predict by using a threshold of 0.5:" }, { "code": null, "e": 6539, "s": 6357, "text": "We are done with all the functions needed finally. Now let’s go to the main program and declare our matrices X, Y and the hyperparameters n_x, n_h, n_y, num_of_iters, learning_rate:" }, { "code": null, "e": 6636, "s": 6539, "text": "Having all the above set up, training the model on them is as easy as calling this line of code:" }, { "code": null, "e": 6718, "s": 6636, "text": "Finally, let’s make our prediction for a random pair of numbers, let’s say (1,1):" }, { "code": null, "e": 6826, "s": 6718, "text": "That was the actual code! Let’s see our results. If we run our file, let’s say xor_nn.py, with this command" }, { "code": null, "e": 6843, "s": 6826, "text": "python xor_nn.py" }, { "code": null, "e": 6913, "s": 6843, "text": "we get the following result, which is indeed correct because 1XOR1=0." }, { "code": null, "e": 6989, "s": 6913, "text": "That’s it! We have trained a Neural Network from scratch using just Python." }, { "code": null, "e": 7293, "s": 6989, "text": "Of course, in order to train larger networks with many layers and hidden units you may need to use some variations of the algorithms above, for example, you may need to use Batch Gradient Descent instead of Gradient Descent or use many more layers but the main idea of a simple NN is as described above." }, { "code": null, "e": 7621, "s": 7293, "text": "Feel free to play with the hyperparameters yourself and try different architectures of the Neural Network. For example, you can try a smaller number of iterations because the Cost seems to be going down quickly and 1000 of them may be a bit large. Remember that you can find the fully working code in my GitLab repository here." } ]
How to implement a custom AlertDialog View in Android?
This example demonstrates how to implement a custom AlertDialog View 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"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/buttonShowDialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@color/colorPrimary" android:padding="15dp" android:text="Android Custom Dialog Example" android:textAllCaps="false" android:textColor="#ffffff" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to res/layout/my_dialog.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="80dp" android:background="@color/colorPrimary"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_centerInParent="true" android:background="@drawable/ic_success" /> </RelativeLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Success" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Headline"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu erat tincidunt lacus fermentum rutrum." android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Medium"/> <Button android:id="@+id/buttonOk" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="15dp" android:background="@drawable/button_background" android:text="Ok" android:textColor="@color/colorPrimary" /> </LinearLayout> Step 4 − Add the following code to res/drawable/button_background.xml. <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <stroke android:width="2dp" android:color="@color/colorPrimary" /> <solid android:color="@android:color/transparent" /> <corners android:bottomLeftRadius="6dp" android:bottomRightRadius="6dp" android:topLeftRadius="6dp" android:topRightRadius="6dp" /> </shape> </item> </selector> Step 5 − Add the following code to res/drawable/ic_success.xml. <?xml version="1.0" encoding="utf-8"?> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="24dp" android:viewportHeight="512" android:viewportWidth="512" android:width="24dp"> <path android:fillColor="#FFFFFF" android:pathData="M468.907,214.604c-11.423,0 -20.682,9.26 -20.682,20.682v20.831c-0.031,54.338 -21.221,105.412 -59.666,143.812c38.417,38.372 -89.467,59.5 -143.761,59.5c-0.04,0 -0.08,0 -0.12,0C132.506,459.365 41.3,368.056 41.364,255.883c0.031, -54.337 21.221,-105.411 59.667,-143.813c38.417,- 38.372 89.468,-59.5 143.761, -59.5c0.04,0 0.08,0 0.12,0c28.672,0.016 56.49,5.942 82.68,17.611c10.436,4.65 22.659, -0.041 27.309,-10.474c4.648,-10.433 -0.04,-22.659 - 10.474,-27.309c-31.516,-14.043 -64.989,-21.173 -99.492,-21.192c-0.052,0 -0.092,0 - 0.144,0c-65.329,0 -126.767,25.428 -172.993,71.6C25.536,129.014 0.038,190.473 0,255.861c-0.037,65.386 25.389,126.874 71.599, 173.136c46.21,46.262 107.668,71.76 173.055,71.798c0.051,0 0.092,0 0.144,0c65.329,0 126.767, -25.427 172.993,-71.6c46.262,-46.20971.76,-107.66871.798,-173.066v20.842C489.589, 223.864 480.33,214.604 468.907,214.604z"/> <path android:fillColor="#FFFFFF" android:pathData="M505.942,39.803c-8.077,- 8.076 -21.172,-8.076 -29.249,0L244.794,271.701l-52.609,-52.609c-8.076,-8.077 -21.172,-8.077 -29.248,0c-8.077,8.077 -8.077,21.172 0,29.249l67.234,67.234c4.038,4.0399.332,6.058 14.625,6.058c5.293,0 10.586,-2.019 14.625, -6.058L505.942,69.052C514.019,60.975 514.019,47.88 505.942,39.803z"/> </vector> Step 6 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.buttonShowDialog).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showCustomDialog(); } }); } private void showCustomDialog() { ViewGroup viewGroup = findViewById(android.R.id.content); View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(dialogView); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } Step 7 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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 − Click here to download the project code.
[ { "code": null, "e": 1143, "s": 1062, "text": "This example demonstrates how to implement a custom AlertDialog View in Android." }, { "code": null, "e": 1272, "s": 1143, "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": 1337, "s": 1272, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2138, "s": 1337, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\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 <Button\n android:id=\"@+id/buttonShowDialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:background=\"@color/colorPrimary\"\n android:padding=\"15dp\"\n android:text=\"Android Custom Dialog Example\"\n android:textAllCaps=\"false\"\n android:textColor=\"#ffffff\" />\n</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2199, "s": 2138, "text": "Step 3 − Add the following code to res/layout/my_dialog.xml." }, { "code": null, "e": 3739, "s": 2199, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <RelativeLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"80dp\"\n android:background=\"@color/colorPrimary\">\n <ImageView\n android:layout_width=\"50dp\"\n android:layout_height=\"50dp\"\n android:layout_centerInParent=\"true\"\n android:background=\"@drawable/ic_success\" />\n </RelativeLayout>\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Success\"\n android:textAlignment=\"center\"\n android:textAppearance=\"@style/TextAppearance.AppCompat.Headline\"/>\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n Nulla eu erat tincidunt lacus fermentum rutrum.\"\n android:textAlignment=\"center\"\n android:textAppearance=\"@style/TextAppearance.AppCompat.Medium\"/>\n <Button\n android:id=\"@+id/buttonOk\"\n android:layout_width=\"200dp\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:layout_marginTop=\"15dp\"\n android:background=\"@drawable/button_background\"\n android:text=\"Ok\"\n android:textColor=\"@color/colorPrimary\" />\n</LinearLayout>" }, { "code": null, "e": 3810, "s": 3739, "text": "Step 4 − Add the following code to res/drawable/button_background.xml." }, { "code": null, "e": 4260, "s": 3810, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item>\n <shape>\n <stroke android:width=\"2dp\" android:color=\"@color/colorPrimary\" />\n <solid android:color=\"@android:color/transparent\" />\n <corners android:bottomLeftRadius=\"6dp\" android:bottomRightRadius=\"6dp\" android:topLeftRadius=\"6dp\" android:topRightRadius=\"6dp\" />\n </shape>\n </item>\n</selector>" }, { "code": null, "e": 4324, "s": 4260, "text": "Step 5 − Add the following code to res/drawable/ic_success.xml." }, { "code": null, "e": 5917, "s": 4324, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:height=\"24dp\"\n android:viewportHeight=\"512\"\n android:viewportWidth=\"512\"\n android:width=\"24dp\">\n <path android:fillColor=\"#FFFFFF\" android:pathData=\"M468.907,214.604c-11.423,0 -20.682,9.26\n -20.682,20.682v20.831c-0.031,54.338 -21.221,105.412 -59.666,143.812c38.417,38.372\n -89.467,59.5 -143.761,59.5c-0.04,0 -0.08,0 -0.12,0C132.506,459.365 41.3,368.056 41.364,255.883c0.031,\n -54.337 21.221,-105.411 59.667,-143.813c38.417,- 38.372 89.468,-59.5 143.761,\n -59.5c0.04,0 0.08,0 0.12,0c28.672,0.016 56.49,5.942 82.68,17.611c10.436,4.65 22.659,\n -0.041 27.309,-10.474c4.648,-10.433 -0.04,-22.659 - 10.474,-27.309c-31.516,-14.043\n -64.989,-21.173 -99.492,-21.192c-0.052,0 -0.092,0 - 0.144,0c-65.329,0 -126.767,25.428\n -172.993,71.6C25.536,129.014 0.038,190.473 0,255.861c-0.037,65.386 25.389,126.874 71.599,\n 173.136c46.21,46.262 107.668,71.76 173.055,71.798c0.051,0 0.092,0 0.144,0c65.329,0 126.767,\n -25.427 172.993,-71.6c46.262,-46.20971.76,-107.66871.798,-173.066v20.842C489.589,\n 223.864 480.33,214.604 468.907,214.604z\"/>\n <path android:fillColor=\"#FFFFFF\" android:pathData=\"M505.942,39.803c-8.077,- 8.076 -21.172,-8.076\n -29.249,0L244.794,271.701l-52.609,-52.609c-8.076,-8.077 -21.172,-8.077 -29.248,0c-8.077,8.077\n -8.077,21.172 0,29.249l67.234,67.234c4.038,4.0399.332,6.058 14.625,6.058c5.293,0 10.586,-2.019 14.625,\n -6.058L505.942,69.052C514.019,60.975 514.019,47.88 505.942,39.803z\"/>\n</vector>" }, { "code": null, "e": 5974, "s": 5917, "text": "Step 6 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 7041, "s": 5974, "text": "package com.app.sample;\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n findViewById(R.id.buttonShowDialog).setOnClickListener(new\n View.OnClickListener() {\n @Override\n public void onClick(View v) {\n showCustomDialog();\n }\n });\n }\n private void showCustomDialog() {\n ViewGroup viewGroup = findViewById(android.R.id.content);\n View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false);\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setView(dialogView);\n AlertDialog alertDialog = builder.create();\n alertDialog.show();\n }\n}" }, { "code": null, "e": 7106, "s": 7041, "text": "Step 7 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 7777, "s": 7106, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\"> \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 8128, "s": 7777, "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 the 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": 8169, "s": 8128, "text": "Click here to download the project code." } ]
How to Invest like a Data Scientist | by Noah Xiao | Towards Data Science
Surely you know data science is a multi-disciplinary field that has something to do with statistics, mathematics, computer science, and business knowledge. The mindset and the multi-disciplinary skill set required for being a data scientist are powerful tools. Instead of a Ph.D. degree1, they are the qualifications of a good data scientist. They not only benefit your career, but also have a huge and positive influence on how you deal with things in life. Investment is a life-long task for anyone who seeks financial freedom. Whether it is investing in stocks or yourself, there are a handful of principles one should keep in mind. These principles are important but also easy to forget. Why? Because “thanks” to human nature, it is certain that one needs an unsuccessful investment experience to appreciate the importance of them. Is there a way to truly master these principles without going through failure? Yes, with the mindset and the multi-disciplinary skill set, good data scientists should know the shortcut. Hope you will be amazed by how these two skills can benefit the way you invest too. “The whole of science is nothing more than a refinement of everyday thinking.” — Albert Einstein A casino is a very profitable business, which can even feed an entire city’s welfare system, like in Las Vagas. Apart from tourists and casual visitors, the largest profit earned by a casino is from gamblers’ greed. You rarely see data scientists in Casinos. If you do, they either work for the casino or they were just pretending to be “social” with their non-data scientist friends there 😲. Why? Because a good data scientist knows mathematics. Let‘s see a simplified example: A gambler plays a game, with exactly 50% of chance of winning and losingIf he wins, he earns 1 dollar; if he loses, he loses 1 dollarThe gambler has $X at the startThere are only two ways to finish the game: 1) lose all $X, 2) the total money reaches his target, $Y A gambler plays a game, with exactly 50% of chance of winning and losing If he wins, he earns 1 dollar; if he loses, he loses 1 dollar The gambler has $X at the start There are only two ways to finish the game: 1) lose all $X, 2) the total money reaches his target, $Y The game seems straightforward but unveils two attributes of all gambling games. Firstly, they all look fair games which make you feel you would simply end up a draw if your luck is average. Secondly, gamblers are greedy. Let’s say, the probability of losing all $X is P(X) Therefore P(X) = 50% × P(X - 1) + 50% × P(X + 1) i.e., 2 × P(X) = P(X - 1) + P(X + 1) i.e., P(X) - P(X - 1) = P(X + 1) - P(X), this satisfies the property of a typical arithmetic progression It is known that for any arithmetic progressions2, i.e. the nth term of the sequence = the first term + the distance between 1th and nth, which can be seen as (n - 1) × the common distance between any two terms. We also know that: P(0) = 1, when one has 0 dollars, the probability of losing everything is 100% P(Y) = 0, when one has Y dollars, the game is finished, so the probability of losing everything is 0% Thus, d = 1 / Y The sequence can now be transformed into below: With the formula above, P(X) = P(Y) + (n - 1)d = P(Y) + (Y - X) ▪ 1 / Y = (Y - X) / Y That is to say, if X = $1,000 if Y = $1,200, P(X) = 1/6if Y = $1,500, P(X) = 1/3if Y = $2,000, P(X) = 1/2if Y = $5,000, P(X) = 4/5 if Y = $1,200, P(X) = 1/6 if Y = $1,500, P(X) = 1/3 if Y = $2,000, P(X) = 1/2 if Y = $5,000, P(X) = 4/5 If you want to make $200, it is relatively easy to achieve. However, if you get greedy and want to make 5 times, there’s an 80% chance you will lose everything. “Quit while you’re ahead” — Old Chinese Wisdom You may have heard about the craziness of cryptocurrencies in 2017 when Bitcoin increased its value by 20 times within a year, followed by a big crash till today. Let us start with a simplified example and you may see how to invest in volatile markets in the future: Sofia invites Noah to play a game that each of them is given a coinIn each round, both of them show a side of the coinIf the result is 2 heads, Noah wins $3 dollarsIf the result is 2 tails, Noah wins $1 dollarIf the result 1 head and 1 tail, then Noah loses $2 dollars Sofia invites Noah to play a game that each of them is given a coin In each round, both of them show a side of the coin If the result is 2 heads, Noah wins $3 dollars If the result is 2 tails, Noah wins $1 dollar If the result 1 head and 1 tail, then Noah loses $2 dollars It is not hard to imagine that the result of tossing a coin is 50–50, so there are 25% of the times the result is 2 heads, 25% 2 tails, and 50% 1 head and 1 tail. Therefore, the expectation of Noah and Sofia’s reward is $0: 25% × $3 + 25% × $1 - 50% × $2 = $0 Yes, it seems to be a fair game plus Noah always wants to play a game with a charming lady, like Sofia, so why not playing. But, after hours of the gaming date, the outcome shows that Noah has almost lost everything in his wallet, including the wallet. How did that happen? The trick is: instead of randomly showing the coin every round, Sofia gets to control the probability. What strategy did she use? Here is what Sofia did: Let’s say A represent the event in which Sofia shows the head, B for the event Noah shows the head. The expectation of Noah’s reward: Plotting this equation: The areas under the flat surface represent the negative E(Noah), and there is a certain range of P(A), Sofia’s probability of showing head, that makes the E(Noah) always negative! This is Sofia’s trick. The code below reveals the range: [0.34 0.35 0.36 ... 0.38 0.39 0.4] That’s it. If Sofia manages to force the probability falls between 0.34 and 0.4, she will always make Noah lose money! This game is a problem in game theory. It can be a perfect analogy teaching us how one can get tricked from a “fair” game. Here, the game can be seen as an investment, Noah represents the individual investors, and Sofia represents the institutional investors, a.k.a., big whales. In small capital investments, such as cryptocurrency and penny stocks, big whales can easily manipulate the market with a big amount of money, i.e., big sell-out or buy-in. Individual investors can make money if they luckily follow the movement of the “whales”, but ultimately individual investors will lose because they are just being manipulated. During an investment, it is the most common thing that one will both win and lose at different points of time. When you are winning, never get greedy (proved earlier). When you are losing, cut the loss wisely. Sam has been holding a stock which worths $10k. Recently the company hasn’t been in the wrong hands and the stock price suddenly dropped to below the purchase price, now it only worths $8k. If Sam keeps holding or adding positions, 90% of chances he will lose more. Obviously cutting the loss is the way to go. However, many people fail to do this, even they were presented with the stats beforehand. This is all due to human egos, such as “You can’t lose money if you never sell”, “Never lose money”. Do NOT be dogmatic about these words. Setting the ego aside, a.k.a., objective thinking, is not as simple as it seems, it requires regular training and one’s persistence. This skill is a fundamental requisite for any scientists and researchers. When the loss is not recoverable, e.g., the company is a scam/bubble, do NOT hope it may get better anytime soon, admit the loss has already become a sunk cost, and pull out immediately. Although sometimes the loss might get recovered by HODLing, considering the opportunity cost, the time you spend waiting till the investment gets back to the previous level, you may have already doubled your position if you chose to move the money somewhere else. When it comes to investment survival, it’s always recommended to conduct more research about the stock and do some calculations to support the investment decision. Another simple and smart way is to treat the stock was given to you for FREE. You will find the decision becomes much easier to make if Sam received a free $10k stock but one day the stock dropped to $8k with very little chance to come back up. There are countless good and bad ways to evaluate an investment, and three of the worst ones are listed above. For individual investors, value investing, discounting, scorecard, PB + PE + PEG are great ways to start. I won’t elaborate on them in this article, please click through the links and you will discover how useful they are. What I would like to call out is an interesting and sometimes counter-intuitive way that lots of people including professionals rely TOO MUCH on — Expected Return. Below shows when it does and doesn’t. Say there is a coin-tossing game. Every round, if it is the head, the player makes $1, if it is the tail, the player makes $2. How much should (s)he pay for playing one round of this game? The expected return is $1.5 so the game is worth playing only if the entry fee is less than $1.5. Say you have $X, there are 50% of chances it will become 0.9 × $X and 50% 1.11 × $X in the next unit time. Is it rationale to all-in every time? This means, in the next unit time, you are expected to gain 0.5% from the $X you have. That is to say, every time you invest, you would make a profit, so of course, you should all-in every time! However, in reality, you are would lose everything if you do so. Counter-intuitive right? Below shows you why. With Monte Carlo simulation, I created 10,000 investors over 500 time units, all start at $100. Each point on the graph represents the return of an investor at a particular time unit. From it, we can see that a few investors have achieved very significant return as time moves on, while the majority of the investors are not so lucky. How unlucky are they? 88.56% of the investors have a return lower than where they started at, $100. What is more unfortunate is that 84.76% of the 10,000 investors end up with $0. Yes, the majority of the investors lose every single cent in the end. It seems that the investment is extremely optimistic, and one should theoretically gain an infinite amount of money if (s)he keeps playing, but there is almost NO real winner in the market. Below code reproduces the simulation: In case you are not 100% convinced, below explains why from a mathematical lens: We already know that the Expected Return is How about one’s Limit of Return: Because Thanks to the law of large numbers Therefore Boom! Counter-intuitive again! The Expected Return is positive but the Limit is zero. This is because some of the Xs are very large in the end, but that is extremely hard to achieve. The average return is dragged to positive due to these very few large Xs, but the truth is the majority of the Xs are almost zero. While investing, one should use the tools wisely. Expected Return is a simple and useful tool but overly relying on it will make you ignore certain important information, which could be fatal sometimes. I have two messages I would love to convey from this article: Data science is beyond just a day-to-day job. The mindset and multi-disciplinary skill set required for being a good data scientist are powerful equipment, which benefits the way one interacts with everything in life.Don’t get greedy, keep distance with volatile markets, cut the loss short, and use tools knowing what they are first. These four investment principles probably are well known among many investors. However not many keep them in mind every time because the principles are taught by words, rather by real-life experiences, a.k.a, failures. I hope by revealing the data and the science behind these lessons, you won’t have to experience the failure to become a master of investment. Data science is beyond just a day-to-day job. The mindset and multi-disciplinary skill set required for being a good data scientist are powerful equipment, which benefits the way one interacts with everything in life. Don’t get greedy, keep distance with volatile markets, cut the loss short, and use tools knowing what they are first. These four investment principles probably are well known among many investors. However not many keep them in mind every time because the principles are taught by words, rather by real-life experiences, a.k.a, failures. I hope by revealing the data and the science behind these lessons, you won’t have to experience the failure to become a master of investment. Hope you enjoy and find it useful. Please follow and connect if you’d like to read more. [1] Medium, Towards Data Science. (2018). Do you need a graduate degree for data science? https://towardsdatascience.com/do-you-need-a-graduate-degree-for-data-science-8e3d0ef39253 [2] Wikipedia. Arithmetic progression. https://en.wikipedia.org/wiki/Arithmetic_progression
[ { "code": null, "e": 327, "s": 171, "text": "Surely you know data science is a multi-disciplinary field that has something to do with statistics, mathematics, computer science, and business knowledge." }, { "code": null, "e": 630, "s": 327, "text": "The mindset and the multi-disciplinary skill set required for being a data scientist are powerful tools. Instead of a Ph.D. degree1, they are the qualifications of a good data scientist. They not only benefit your career, but also have a huge and positive influence on how you deal with things in life." }, { "code": null, "e": 1007, "s": 630, "text": "Investment is a life-long task for anyone who seeks financial freedom. Whether it is investing in stocks or yourself, there are a handful of principles one should keep in mind. These principles are important but also easy to forget. Why? Because “thanks” to human nature, it is certain that one needs an unsuccessful investment experience to appreciate the importance of them." }, { "code": null, "e": 1277, "s": 1007, "text": "Is there a way to truly master these principles without going through failure? Yes, with the mindset and the multi-disciplinary skill set, good data scientists should know the shortcut. Hope you will be amazed by how these two skills can benefit the way you invest too." }, { "code": null, "e": 1356, "s": 1277, "text": "“The whole of science is nothing more than a refinement of everyday thinking.”" }, { "code": null, "e": 1374, "s": 1356, "text": "— Albert Einstein" }, { "code": null, "e": 1590, "s": 1374, "text": "A casino is a very profitable business, which can even feed an entire city’s welfare system, like in Las Vagas. Apart from tourists and casual visitors, the largest profit earned by a casino is from gamblers’ greed." }, { "code": null, "e": 1821, "s": 1590, "text": "You rarely see data scientists in Casinos. If you do, they either work for the casino or they were just pretending to be “social” with their non-data scientist friends there 😲. Why? Because a good data scientist knows mathematics." }, { "code": null, "e": 1853, "s": 1821, "text": "Let‘s see a simplified example:" }, { "code": null, "e": 2119, "s": 1853, "text": "A gambler plays a game, with exactly 50% of chance of winning and losingIf he wins, he earns 1 dollar; if he loses, he loses 1 dollarThe gambler has $X at the startThere are only two ways to finish the game: 1) lose all $X, 2) the total money reaches his target, $Y" }, { "code": null, "e": 2192, "s": 2119, "text": "A gambler plays a game, with exactly 50% of chance of winning and losing" }, { "code": null, "e": 2254, "s": 2192, "text": "If he wins, he earns 1 dollar; if he loses, he loses 1 dollar" }, { "code": null, "e": 2286, "s": 2254, "text": "The gambler has $X at the start" }, { "code": null, "e": 2388, "s": 2286, "text": "There are only two ways to finish the game: 1) lose all $X, 2) the total money reaches his target, $Y" }, { "code": null, "e": 2610, "s": 2388, "text": "The game seems straightforward but unveils two attributes of all gambling games. Firstly, they all look fair games which make you feel you would simply end up a draw if your luck is average. Secondly, gamblers are greedy." }, { "code": null, "e": 2662, "s": 2610, "text": "Let’s say, the probability of losing all $X is P(X)" }, { "code": null, "e": 2672, "s": 2662, "text": "Therefore" }, { "code": null, "e": 2711, "s": 2672, "text": "P(X) = 50% × P(X - 1) + 50% × P(X + 1)" }, { "code": null, "e": 2748, "s": 2711, "text": "i.e., 2 × P(X) = P(X - 1) + P(X + 1)" }, { "code": null, "e": 2853, "s": 2748, "text": "i.e., P(X) - P(X - 1) = P(X + 1) - P(X), this satisfies the property of a typical arithmetic progression" }, { "code": null, "e": 2904, "s": 2853, "text": "It is known that for any arithmetic progressions2," }, { "code": null, "e": 3065, "s": 2904, "text": "i.e. the nth term of the sequence = the first term + the distance between 1th and nth, which can be seen as (n - 1) × the common distance between any two terms." }, { "code": null, "e": 3084, "s": 3065, "text": "We also know that:" }, { "code": null, "e": 3163, "s": 3084, "text": "P(0) = 1, when one has 0 dollars, the probability of losing everything is 100%" }, { "code": null, "e": 3265, "s": 3163, "text": "P(Y) = 0, when one has Y dollars, the game is finished, so the probability of losing everything is 0%" }, { "code": null, "e": 3281, "s": 3265, "text": "Thus, d = 1 / Y" }, { "code": null, "e": 3329, "s": 3281, "text": "The sequence can now be transformed into below:" }, { "code": null, "e": 3353, "s": 3329, "text": "With the formula above," }, { "code": null, "e": 3415, "s": 3353, "text": "P(X) = P(Y) + (n - 1)d = P(Y) + (Y - X) ▪ 1 / Y = (Y - X) / Y" }, { "code": null, "e": 3445, "s": 3415, "text": "That is to say, if X = $1,000" }, { "code": null, "e": 3546, "s": 3445, "text": "if Y = $1,200, P(X) = 1/6if Y = $1,500, P(X) = 1/3if Y = $2,000, P(X) = 1/2if Y = $5,000, P(X) = 4/5" }, { "code": null, "e": 3572, "s": 3546, "text": "if Y = $1,200, P(X) = 1/6" }, { "code": null, "e": 3598, "s": 3572, "text": "if Y = $1,500, P(X) = 1/3" }, { "code": null, "e": 3624, "s": 3598, "text": "if Y = $2,000, P(X) = 1/2" }, { "code": null, "e": 3650, "s": 3624, "text": "if Y = $5,000, P(X) = 4/5" }, { "code": null, "e": 3811, "s": 3650, "text": "If you want to make $200, it is relatively easy to achieve. However, if you get greedy and want to make 5 times, there’s an 80% chance you will lose everything." }, { "code": null, "e": 3858, "s": 3811, "text": "“Quit while you’re ahead” — Old Chinese Wisdom" }, { "code": null, "e": 4021, "s": 3858, "text": "You may have heard about the craziness of cryptocurrencies in 2017 when Bitcoin increased its value by 20 times within a year, followed by a big crash till today." }, { "code": null, "e": 4125, "s": 4021, "text": "Let us start with a simplified example and you may see how to invest in volatile markets in the future:" }, { "code": null, "e": 4394, "s": 4125, "text": "Sofia invites Noah to play a game that each of them is given a coinIn each round, both of them show a side of the coinIf the result is 2 heads, Noah wins $3 dollarsIf the result is 2 tails, Noah wins $1 dollarIf the result 1 head and 1 tail, then Noah loses $2 dollars" }, { "code": null, "e": 4462, "s": 4394, "text": "Sofia invites Noah to play a game that each of them is given a coin" }, { "code": null, "e": 4514, "s": 4462, "text": "In each round, both of them show a side of the coin" }, { "code": null, "e": 4561, "s": 4514, "text": "If the result is 2 heads, Noah wins $3 dollars" }, { "code": null, "e": 4607, "s": 4561, "text": "If the result is 2 tails, Noah wins $1 dollar" }, { "code": null, "e": 4667, "s": 4607, "text": "If the result 1 head and 1 tail, then Noah loses $2 dollars" }, { "code": null, "e": 4830, "s": 4667, "text": "It is not hard to imagine that the result of tossing a coin is 50–50, so there are 25% of the times the result is 2 heads, 25% 2 tails, and 50% 1 head and 1 tail." }, { "code": null, "e": 4891, "s": 4830, "text": "Therefore, the expectation of Noah and Sofia’s reward is $0:" }, { "code": null, "e": 4927, "s": 4891, "text": "25% × $3 + 25% × $1 - 50% × $2 = $0" }, { "code": null, "e": 5201, "s": 4927, "text": "Yes, it seems to be a fair game plus Noah always wants to play a game with a charming lady, like Sofia, so why not playing. But, after hours of the gaming date, the outcome shows that Noah has almost lost everything in his wallet, including the wallet. How did that happen?" }, { "code": null, "e": 5355, "s": 5201, "text": "The trick is: instead of randomly showing the coin every round, Sofia gets to control the probability. What strategy did she use? Here is what Sofia did:" }, { "code": null, "e": 5455, "s": 5355, "text": "Let’s say A represent the event in which Sofia shows the head, B for the event Noah shows the head." }, { "code": null, "e": 5489, "s": 5455, "text": "The expectation of Noah’s reward:" }, { "code": null, "e": 5513, "s": 5489, "text": "Plotting this equation:" }, { "code": null, "e": 5750, "s": 5513, "text": "The areas under the flat surface represent the negative E(Noah), and there is a certain range of P(A), Sofia’s probability of showing head, that makes the E(Noah) always negative! This is Sofia’s trick. The code below reveals the range:" }, { "code": null, "e": 5785, "s": 5750, "text": "[0.34 0.35 0.36 ... 0.38 0.39 0.4]" }, { "code": null, "e": 5904, "s": 5785, "text": "That’s it. If Sofia manages to force the probability falls between 0.34 and 0.4, she will always make Noah lose money!" }, { "code": null, "e": 6533, "s": 5904, "text": "This game is a problem in game theory. It can be a perfect analogy teaching us how one can get tricked from a “fair” game. Here, the game can be seen as an investment, Noah represents the individual investors, and Sofia represents the institutional investors, a.k.a., big whales. In small capital investments, such as cryptocurrency and penny stocks, big whales can easily manipulate the market with a big amount of money, i.e., big sell-out or buy-in. Individual investors can make money if they luckily follow the movement of the “whales”, but ultimately individual investors will lose because they are just being manipulated." }, { "code": null, "e": 6743, "s": 6533, "text": "During an investment, it is the most common thing that one will both win and lose at different points of time. When you are winning, never get greedy (proved earlier). When you are losing, cut the loss wisely." }, { "code": null, "e": 6933, "s": 6743, "text": "Sam has been holding a stock which worths $10k. Recently the company hasn’t been in the wrong hands and the stock price suddenly dropped to below the purchase price, now it only worths $8k." }, { "code": null, "e": 7283, "s": 6933, "text": "If Sam keeps holding or adding positions, 90% of chances he will lose more. Obviously cutting the loss is the way to go. However, many people fail to do this, even they were presented with the stats beforehand. This is all due to human egos, such as “You can’t lose money if you never sell”, “Never lose money”. Do NOT be dogmatic about these words." }, { "code": null, "e": 7490, "s": 7283, "text": "Setting the ego aside, a.k.a., objective thinking, is not as simple as it seems, it requires regular training and one’s persistence. This skill is a fundamental requisite for any scientists and researchers." }, { "code": null, "e": 7941, "s": 7490, "text": "When the loss is not recoverable, e.g., the company is a scam/bubble, do NOT hope it may get better anytime soon, admit the loss has already become a sunk cost, and pull out immediately. Although sometimes the loss might get recovered by HODLing, considering the opportunity cost, the time you spend waiting till the investment gets back to the previous level, you may have already doubled your position if you chose to move the money somewhere else." }, { "code": null, "e": 8350, "s": 7941, "text": "When it comes to investment survival, it’s always recommended to conduct more research about the stock and do some calculations to support the investment decision. Another simple and smart way is to treat the stock was given to you for FREE. You will find the decision becomes much easier to make if Sam received a free $10k stock but one day the stock dropped to $8k with very little chance to come back up." }, { "code": null, "e": 8684, "s": 8350, "text": "There are countless good and bad ways to evaluate an investment, and three of the worst ones are listed above. For individual investors, value investing, discounting, scorecard, PB + PE + PEG are great ways to start. I won’t elaborate on them in this article, please click through the links and you will discover how useful they are." }, { "code": null, "e": 8886, "s": 8684, "text": "What I would like to call out is an interesting and sometimes counter-intuitive way that lots of people including professionals rely TOO MUCH on — Expected Return. Below shows when it does and doesn’t." }, { "code": null, "e": 9075, "s": 8886, "text": "Say there is a coin-tossing game. Every round, if it is the head, the player makes $1, if it is the tail, the player makes $2. How much should (s)he pay for playing one round of this game?" }, { "code": null, "e": 9173, "s": 9075, "text": "The expected return is $1.5 so the game is worth playing only if the entry fee is less than $1.5." }, { "code": null, "e": 9318, "s": 9173, "text": "Say you have $X, there are 50% of chances it will become 0.9 × $X and 50% 1.11 × $X in the next unit time. Is it rationale to all-in every time?" }, { "code": null, "e": 9513, "s": 9318, "text": "This means, in the next unit time, you are expected to gain 0.5% from the $X you have. That is to say, every time you invest, you would make a profit, so of course, you should all-in every time!" }, { "code": null, "e": 9624, "s": 9513, "text": "However, in reality, you are would lose everything if you do so. Counter-intuitive right? Below shows you why." }, { "code": null, "e": 9720, "s": 9624, "text": "With Monte Carlo simulation, I created 10,000 investors over 500 time units, all start at $100." }, { "code": null, "e": 9959, "s": 9720, "text": "Each point on the graph represents the return of an investor at a particular time unit. From it, we can see that a few investors have achieved very significant return as time moves on, while the majority of the investors are not so lucky." }, { "code": null, "e": 10209, "s": 9959, "text": "How unlucky are they? 88.56% of the investors have a return lower than where they started at, $100. What is more unfortunate is that 84.76% of the 10,000 investors end up with $0. Yes, the majority of the investors lose every single cent in the end." }, { "code": null, "e": 10399, "s": 10209, "text": "It seems that the investment is extremely optimistic, and one should theoretically gain an infinite amount of money if (s)he keeps playing, but there is almost NO real winner in the market." }, { "code": null, "e": 10437, "s": 10399, "text": "Below code reproduces the simulation:" }, { "code": null, "e": 10518, "s": 10437, "text": "In case you are not 100% convinced, below explains why from a mathematical lens:" }, { "code": null, "e": 10562, "s": 10518, "text": "We already know that the Expected Return is" }, { "code": null, "e": 10595, "s": 10562, "text": "How about one’s Limit of Return:" }, { "code": null, "e": 10603, "s": 10595, "text": "Because" }, { "code": null, "e": 10638, "s": 10603, "text": "Thanks to the law of large numbers" }, { "code": null, "e": 10648, "s": 10638, "text": "Therefore" }, { "code": null, "e": 10962, "s": 10648, "text": "Boom! Counter-intuitive again! The Expected Return is positive but the Limit is zero. This is because some of the Xs are very large in the end, but that is extremely hard to achieve. The average return is dragged to positive due to these very few large Xs, but the truth is the majority of the Xs are almost zero." }, { "code": null, "e": 11165, "s": 10962, "text": "While investing, one should use the tools wisely. Expected Return is a simple and useful tool but overly relying on it will make you ignore certain important information, which could be fatal sometimes." }, { "code": null, "e": 11227, "s": 11165, "text": "I have two messages I would love to convey from this article:" }, { "code": null, "e": 11923, "s": 11227, "text": "Data science is beyond just a day-to-day job. The mindset and multi-disciplinary skill set required for being a good data scientist are powerful equipment, which benefits the way one interacts with everything in life.Don’t get greedy, keep distance with volatile markets, cut the loss short, and use tools knowing what they are first. These four investment principles probably are well known among many investors. However not many keep them in mind every time because the principles are taught by words, rather by real-life experiences, a.k.a, failures. I hope by revealing the data and the science behind these lessons, you won’t have to experience the failure to become a master of investment." }, { "code": null, "e": 12141, "s": 11923, "text": "Data science is beyond just a day-to-day job. The mindset and multi-disciplinary skill set required for being a good data scientist are powerful equipment, which benefits the way one interacts with everything in life." }, { "code": null, "e": 12620, "s": 12141, "text": "Don’t get greedy, keep distance with volatile markets, cut the loss short, and use tools knowing what they are first. These four investment principles probably are well known among many investors. However not many keep them in mind every time because the principles are taught by words, rather by real-life experiences, a.k.a, failures. I hope by revealing the data and the science behind these lessons, you won’t have to experience the failure to become a master of investment." }, { "code": null, "e": 12709, "s": 12620, "text": "Hope you enjoy and find it useful. Please follow and connect if you’d like to read more." }, { "code": null, "e": 12890, "s": 12709, "text": "[1] Medium, Towards Data Science. (2018). Do you need a graduate degree for data science? https://towardsdatascience.com/do-you-need-a-graduate-degree-for-data-science-8e3d0ef39253" } ]
Check if a point lies on or inside a rectangle in Python
Suppose we have a rectangle represented by two points bottom-left and top-right corner points. We have to check whether a given point (x, y) is present inside this rectangle or not. So, if the input is like bottom_left = (1, 1), top_right = (8, 5), point = (5, 4), then the output will be True To solve this, we will follow these steps − Define a function solve() . This will take bl, tr, p if x of p > x of bl and x of p < x of tr and y of p > y of bl and y of p < y of tr, thenreturn True return True otherwise,return False return False Let us see the following implementation to get better understanding − Live Demo def solve(bl, tr, p) : if (p[0] > bl[0] and p[0] < tr[0] and p[1] > bl[1] and p[1] < tr[1]) : return True else : return False bottom_left = (1, 1) top_right = (8, 5) point = (5, 4) print(solve(bottom_left, top_right, point)) (1, 1), (8, 5), (5, 4) True
[ { "code": null, "e": 1244, "s": 1062, "text": "Suppose we have a rectangle represented by two points bottom-left and top-right corner points. We have to check whether a given point (x, y) is present inside this rectangle or not." }, { "code": null, "e": 1356, "s": 1244, "text": "So, if the input is like bottom_left = (1, 1), top_right = (8, 5), point = (5, 4), then the output will be True" }, { "code": null, "e": 1400, "s": 1356, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1453, "s": 1400, "text": "Define a function solve() . This will take bl, tr, p" }, { "code": null, "e": 1553, "s": 1453, "text": "if x of p > x of bl and x of p < x of tr and y of p > y of bl and y of p < y of tr, thenreturn True" }, { "code": null, "e": 1565, "s": 1553, "text": "return True" }, { "code": null, "e": 1588, "s": 1565, "text": "otherwise,return False" }, { "code": null, "e": 1601, "s": 1588, "text": "return False" }, { "code": null, "e": 1671, "s": 1601, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1682, "s": 1671, "text": " Live Demo" }, { "code": null, "e": 1925, "s": 1682, "text": "def solve(bl, tr, p) :\n if (p[0] > bl[0] and p[0] < tr[0] and p[1] > bl[1] and p[1] < tr[1]) :\n return True\n else :\n return False\nbottom_left = (1, 1)\ntop_right = (8, 5)\npoint = (5, 4)\nprint(solve(bottom_left, top_right, point))" }, { "code": null, "e": 1948, "s": 1925, "text": "(1, 1), (8, 5), (5, 4)" }, { "code": null, "e": 1953, "s": 1948, "text": "True" } ]
What is the #define Preprocessor in C++?
The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file. #define identifier token-string This is how the preprocessor is used. The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier. #include<iostream> #define MY_VAR 55 using namespace std; int main() { int x = 10; cout << x + MY_VAR; // After preprocessing this expression becomes: x + 55 return 0; } This will give the output − 65 You can read more about the #define directive in MSDN https://docs.microsoft.com/en-us/cpp/preprocessor/hash-define-directive-c-cpp
[ { "code": null, "e": 1313, "s": 1062, "text": "The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file." }, { "code": null, "e": 1345, "s": 1313, "text": "#define identifier token-string" }, { "code": null, "e": 1673, "s": 1345, "text": "This is how the preprocessor is used. The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier." }, { "code": null, "e": 1859, "s": 1673, "text": "#include<iostream>\n#define MY_VAR 55\nusing namespace std;\n\nint main() {\n int x = 10;\n cout << x + MY_VAR; // After preprocessing this expression becomes: x + 55\n return 0;\n}\n" }, { "code": null, "e": 1887, "s": 1859, "text": "This will give the output −" }, { "code": null, "e": 1890, "s": 1887, "text": "65" }, { "code": null, "e": 2022, "s": 1890, "text": "You can read more about the #define directive in MSDN https://docs.microsoft.com/en-us/cpp/preprocessor/hash-define-directive-c-cpp" } ]
Python SQLite - Create Table
Using the SQLite CREATE TABLE statement you can create a table in a database. Following is the syntax to create a table in SQLite database − CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); Following SQLite query/statement creates a table with name CRICKETERS in SQLite database − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table. sqlite> CREATE TABLE ODIStats ( First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, Centuries INT, HalfCenturies INT ); sqlite> You can get the list of tables in a database in SQLite database using the .tables command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as − sqlite> . tables CRICKETERS ODIStats sqlite> The Cursor object contains all the methods to execute quires and fetch data etc. The cursor method of the connection class returns a cursor object. Therefore, to create a table in SQLite database using python − Establish connection with a database using the connect() method. Establish connection with a database using the connect() method. Create a cursor object by invoking the cursor() method on the above created connection object. Create a cursor object by invoking the cursor() method on the above created connection object. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Following Python program creates a table named Employee in SQLite3 − import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql ='''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) print("Table created successfully........") #Commit your changes in the database conn.commit() #Closing the connection conn.close() Table created successfully........ 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": 2060, "s": 1982, "text": "Using the SQLite CREATE TABLE statement you can create a table in a database." }, { "code": null, "e": 2123, "s": 2060, "text": "Following is the syntax to create a table in SQLite database −" }, { "code": null, "e": 2291, "s": 2123, "text": "CREATE TABLE database_name.table_name(\n column1 datatype PRIMARY KEY(one or more columns),\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype\n);\n" }, { "code": null, "e": 2382, "s": 2291, "text": "Following SQLite query/statement creates a table with name CRICKETERS in SQLite database −" }, { "code": null, "e": 2550, "s": 2382, "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": 2666, "s": 2550, "text": "Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table." }, { "code": null, "e": 2820, "s": 2666, "text": "sqlite> CREATE TABLE ODIStats (\n First_Name VARCHAR(255),\n Matches INT,\n Runs INT,\n AVG FLOAT,\n Centuries INT,\n HalfCenturies INT \n);\nsqlite>" }, { "code": null, "e": 3023, "s": 2820, "text": "You can get the list of tables in a database in SQLite database using the .tables command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as −" }, { "code": null, "e": 3069, "s": 3023, "text": "sqlite> . tables\nCRICKETERS ODIStats\nsqlite>\n" }, { "code": null, "e": 3217, "s": 3069, "text": "The Cursor object contains all the methods to execute quires and fetch data etc. The cursor method of the connection class returns a cursor object." }, { "code": null, "e": 3280, "s": 3217, "text": "Therefore, to create a table in SQLite database using python −" }, { "code": null, "e": 3345, "s": 3280, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 3410, "s": 3345, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 3505, "s": 3410, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 3600, "s": 3505, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 3687, "s": 3600, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 3774, "s": 3687, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 3843, "s": 3774, "text": "Following Python program creates a table named Employee in SQLite3 −" }, { "code": null, "e": 4409, "s": 3843, "text": "import sqlite3\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n#Creating table as per requirement\nsql ='''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\nprint(\"Table created successfully........\")\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 4445, "s": 4409, "text": "Table created successfully........\n" }, { "code": null, "e": 4482, "s": 4445, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4498, "s": 4482, "text": " Malhar Lathkar" }, { "code": null, "e": 4531, "s": 4498, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4550, "s": 4531, "text": " Arnab Chakraborty" }, { "code": null, "e": 4585, "s": 4550, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4607, "s": 4585, "text": " In28Minutes Official" }, { "code": null, "e": 4641, "s": 4607, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4669, "s": 4641, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4704, "s": 4669, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4718, "s": 4704, "text": " Lets Kode It" }, { "code": null, "e": 4751, "s": 4718, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4768, "s": 4751, "text": " Abhilash Nelson" }, { "code": null, "e": 4775, "s": 4768, "text": " Print" }, { "code": null, "e": 4786, "s": 4775, "text": " Add Notes" } ]
SymPy - Logical Expressions
Boolean functions are defined in sympy.basic.booleanarg module. It is possible to build Boolean expressions with the standard python operators & (And), | (Or), ~ (Not) as well as with >> and <<. Boolean expressions inherit from Basic class defined in SymPy's core module. This function is equivalent of True as in core Python. It returns a singleton that can be retrieved by S.true. >>> from sympy import * >>> x=sympify(true) >>> x, S.true The above code snippet gives the following output − Similarly, this function is equivalent to Boolean False in Python and can be accessed by S.false >>> from sympy import * >>> x=sympify(false) >>> x, S.false The above code snippet gives the following output − A logical AND function evaluates its two arguments and returns False if either of them is False. The function emulates & operator. >>> from sympy import * >>> from sympy.logic.boolalg import And >>> x,y=symbols('x y') >>> x=True >>> y=True >>> And(x,y), x"&"y The above code snippet gives the following output − >>> y=False >>> And(x,y), x"&"y The above code snippet gives the following output − This function evaluates two Boolean arguments and returns True if either of them is True. The | operator conveniently emulates its behaviour. >>> from sympy import * >>> from sympy.logic.boolalg import Or >>> x,y=symbols('x y') >>> x=True >>> y=False >>> Or(x,y), x|y The above code snippet gives the following output − >>> x=False >>> y=False >>> Or(x,y), x|y The above code snippet gives the following output − A Logical Not function results in negation of the Boolean argument. It returns True if its argument is False and returns False if True. The ~ operator performs the operation similar to Not function. It is shown in the example below − >>> from sympy import * >>> from sympy.logic.boolalg import Or, And, Not >>> x,y=symbols('x y') >>> x=True >>> y=False >>> Not(x), Not(y) The above code snippet gives the following output − >>> Not(And(x,y)), Not(Or(x,y)) The above code snippet gives the following output − The Logical XOR (exclusive OR) function returns True if an odd number of the arguments are True and the rest are False and returns False if an even number of the arguments are True and the rest are False. Similar operation is performed by ^ operator. >>> from sympy import * >>> from sympy.logic.boolalg import Xor >>> x,y=symbols('x y') >>> x=True >>> y=False >>> Xor(x,y), x^y The above code snippet gives the following output − >>> a,b,c,d,e=symbols('a b c d e') >>> a,b,c,d,e=(True, False, True, True, False) >>> Xor(a,b,c,d,e) The above code snippet gives the following output − In above case, three (odd number) arguments are True, hence Xor returns true. However, if number of True arguments is even, it results in False, as shown below − >>> a,b,c,d,e=(True, False, False, True, False) >>> Xor(a,b,c,d,e) The above code snippet gives the following output − This function performs Logical NAND operation. It evaluates its arguments and returns True if any of them are False, and False if they are all True. >>> from sympy import * >>> from sympy.logic.boolalg import Nand >>> a,b,c=symbols('a b c') >>> a,b,c=(True, False, True) >>> Nand(a,b,c), Nand(a,c) The above code snippet gives the following output − This function performs Logical NOR operation. It evaluates its arguments and returns False if any of them are True, and True if they are all False. >>> from sympy import * >>> from sympy.logic.boolalg import Nor >>> a,b,c=symbols('a b c') >>> a,b,c=(True, False, True) >>> Nor(a,b,c), Nor(a,c) The above code snippet gives the following output − Note that even though SymPy provides ^ operator for Xor, ~ for Not, | for Or and & for And functions as convenience, their normal use in Python is as bitwise operators. Hence, if operands are integers, results would be different. This function returns equivalence relation. Equivalent(A, B) is True if and only if A and B are both True or both False. The function returns True if all of the arguments are logically equivalent. Returns False otherwise. >>> from sympy import * >>> from sympy.logic.boolalg import Equivalent >>> a,b,c=symbols('a b c') >>> a,b,c=(True, False, True) >>> Equivalent(a,b), Equivalent(a,c) The above code snippet gives the following output − This function acts as If then else clause in a programming language.ITE(A, B, C) evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans. >>> from sympy import * >>> from sympy.logic.boolalg import ITE >>> a,b,c=symbols('a b c') >>> a,b,c=(True, False, True) >>> ITE(a,b,c), ITE(a,c,b) The above code snippet gives the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2291, "s": 2019, "text": "Boolean functions are defined in sympy.basic.booleanarg module. It is possible to build Boolean expressions with the standard python operators & (And), | (Or), ~ (Not) as well as with >> and <<. Boolean expressions inherit from Basic class defined in SymPy's core module." }, { "code": null, "e": 2402, "s": 2291, "text": "This function is equivalent of True as in core Python. It returns a singleton that can be retrieved by S.true." }, { "code": null, "e": 2463, "s": 2402, "text": ">>> from sympy import * \n>>> x=sympify(true) \n>>> x, S.true\n" }, { "code": null, "e": 2515, "s": 2463, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 2612, "s": 2515, "text": "Similarly, this function is equivalent to Boolean False in Python and can be accessed by S.false" }, { "code": null, "e": 2675, "s": 2612, "text": ">>> from sympy import * \n>>> x=sympify(false) \n>>> x, S.false\n" }, { "code": null, "e": 2727, "s": 2675, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 2858, "s": 2727, "text": "A logical AND function evaluates its two arguments and returns False if either of them is False. The function emulates & operator." }, { "code": null, "e": 2993, "s": 2858, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import And \n>>> x,y=symbols('x y') \n>>> x=True \n>>> y=True \n>>> And(x,y), x\"&\"y\n" }, { "code": null, "e": 3045, "s": 2993, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 3079, "s": 3045, "text": ">>> y=False \n>>> And(x,y), x\"&\"y\n" }, { "code": null, "e": 3131, "s": 3079, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 3273, "s": 3131, "text": "This function evaluates two Boolean arguments and returns True if either of them is True. The | operator conveniently emulates its behaviour." }, { "code": null, "e": 3405, "s": 3273, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import Or \n>>> x,y=symbols('x y') \n>>> x=True \n>>> y=False \n>>> Or(x,y), x|y\n" }, { "code": null, "e": 3457, "s": 3405, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 3501, "s": 3457, "text": ">>> x=False \n>>> y=False \n>>> Or(x,y), x|y\n" }, { "code": null, "e": 3553, "s": 3501, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 3787, "s": 3553, "text": "A Logical Not function results in negation of the Boolean argument. It returns True if its argument is False and returns False if True. The ~ operator performs the operation similar to Not function. It is shown in the example below −" }, { "code": null, "e": 3931, "s": 3787, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import Or, And, Not \n>>> x,y=symbols('x y') \n>>> x=True \n>>> y=False \n>>> Not(x), Not(y)\n" }, { "code": null, "e": 3983, "s": 3931, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 4016, "s": 3983, "text": ">>> Not(And(x,y)), Not(Or(x,y))\n" }, { "code": null, "e": 4068, "s": 4016, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 4319, "s": 4068, "text": "The Logical XOR (exclusive OR) function returns True if an odd number of the arguments are True and the rest are False and returns False if an even number of the arguments are True and the rest are False. Similar operation is performed by ^ operator." }, { "code": null, "e": 4453, "s": 4319, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import Xor \n>>> x,y=symbols('x y') \n>>> x=True \n>>> y=False\n\n>>> Xor(x,y), x^y\n" }, { "code": null, "e": 4505, "s": 4453, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 4609, "s": 4505, "text": ">>> a,b,c,d,e=symbols('a b c d e') \n>>> a,b,c,d,e=(True, False, True, True, False) \n>>> Xor(a,b,c,d,e)\n" }, { "code": null, "e": 4661, "s": 4609, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 4823, "s": 4661, "text": "In above case, three (odd number) arguments are True, hence Xor returns true. However, if number of True arguments is even, it results in False, as shown below −" }, { "code": null, "e": 4892, "s": 4823, "text": ">>> a,b,c,d,e=(True, False, False, True, False) \n>>> Xor(a,b,c,d,e)\n" }, { "code": null, "e": 4944, "s": 4892, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 5093, "s": 4944, "text": "This function performs Logical NAND operation. It evaluates its arguments and returns True if any of them are False, and False if they are all True." }, { "code": null, "e": 5247, "s": 5093, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import Nand \n>>> a,b,c=symbols('a b c') \n>>> a,b,c=(True, False, True) \n>>> Nand(a,b,c), Nand(a,c)\n" }, { "code": null, "e": 5299, "s": 5247, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 5447, "s": 5299, "text": "This function performs Logical NOR operation. It evaluates its arguments and returns False if any of them are True, and True if they are all False." }, { "code": null, "e": 5598, "s": 5447, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import Nor \n>>> a,b,c=symbols('a b c') \n>>> a,b,c=(True, False, True) \n>>> Nor(a,b,c), Nor(a,c)\n" }, { "code": null, "e": 5650, "s": 5598, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 5880, "s": 5650, "text": "Note that even though SymPy provides ^ operator for Xor, ~ for Not, | for Or and & for And functions as convenience, their normal use in Python is as bitwise operators. Hence, if operands are integers, results would be different." }, { "code": null, "e": 6102, "s": 5880, "text": "This function returns equivalence relation. Equivalent(A, B) is True if and only if A and B are both True or both False. The function returns True if all of the arguments are logically equivalent. Returns False otherwise." }, { "code": null, "e": 6272, "s": 6102, "text": ">>> from sympy import * \n>>> from sympy.logic.boolalg import Equivalent \n>>> a,b,c=symbols('a b c') \n>>> a,b,c=(True, False, True) \n>>> Equivalent(a,b), Equivalent(a,c)\n" }, { "code": null, "e": 6324, "s": 6272, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 6516, "s": 6324, "text": "This function acts as If then else clause in a programming language.ITE(A, B, C) evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans." }, { "code": null, "e": 6666, "s": 6516, "text": ">>> from sympy import * >>> from sympy.logic.boolalg import ITE >>> a,b,c=symbols('a b c') >>> a,b,c=(True, False, True) \n>>> ITE(a,b,c), ITE(a,c,b)\n" }, { "code": null, "e": 6718, "s": 6666, "text": "The above code snippet gives the following output −" }, { "code": null, "e": 6725, "s": 6718, "text": " Print" }, { "code": null, "e": 6736, "s": 6725, "text": " Add Notes" } ]
C program to find the length of linked list
Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. They are defined as a collection of nodes. Here, nodes have two parts, which are data and link. The representation of data, link and linked lists is given below − Linked lists have four types, which are as follows − Single / Singly linked lists Double / Doubly linked lists Circular single linked list Circular double linked list The logic we used to find the length of linked list by using recursion method is − int length(node *temp){ if(temp==NULL) return l; else{ l=l+1; length(temp->next); } } Following is the C program to find the length of linked list − Live Demo #include <stdio.h> #include <stdlib.h> typedef struct linklist{ int data; struct linklist *next; }node; int l=0; int main(){ node *head=NULL,*temp,*temp1; int len,choice,count=0,key; do{ temp=(node *)malloc(sizeof(node)); if(temp!=NULL){ printf("\nenter the elements in a list : "); scanf("%d",&temp->data); temp->next=NULL; if(head==NULL){ head=temp; }else{ temp1=head; while(temp1->next!=NULL){ temp1=temp1->next; } temp1->next=temp; } }else{ printf("\nMemory is full"); } printf("\npress 1 to enter data into list: "); scanf("%d",&choice); }while(choice==1); len=length(head); printf("The list has %d no of nodes",l); return 0; } //recursive function to find length int length(node *temp){ if(temp==NULL) return l; else{ l=l+1; length(temp->next); } } When the above program is executed, it produces the following result − Run 1: enter the elements in a list: 3 press 1 to enter data into list: 1 enter the elements in a list: 56 press 1 to enter data into list: 1 enter the elements in a list: 56 press 1 to enter data into list: 0 The list has 3 no of nodes Run 2: enter the elements in a list: 12 press 1 to enter data into list: 1 enter the elements in a list: 45 press 1 to enter data into list: 0 The list has 2 no of nodes
[ { "code": null, "e": 1307, "s": 1062, "text": "Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. They are defined as a collection of nodes. Here, nodes have two parts, which are data and link. The representation of data, link and linked lists is given below −" }, { "code": null, "e": 1360, "s": 1307, "text": "Linked lists have four types, which are as follows −" }, { "code": null, "e": 1389, "s": 1360, "text": "Single / Singly linked lists" }, { "code": null, "e": 1418, "s": 1389, "text": "Double / Doubly linked lists" }, { "code": null, "e": 1446, "s": 1418, "text": "Circular single linked list" }, { "code": null, "e": 1474, "s": 1446, "text": "Circular double linked list" }, { "code": null, "e": 1557, "s": 1474, "text": "The logic we used to find the length of linked list by using recursion method is −" }, { "code": null, "e": 1670, "s": 1557, "text": "int length(node *temp){\n if(temp==NULL)\n return l;\n else{\n l=l+1;\n length(temp->next);\n }\n}" }, { "code": null, "e": 1733, "s": 1670, "text": "Following is the C program to find the length of linked list −" }, { "code": null, "e": 1744, "s": 1733, "text": " Live Demo" }, { "code": null, "e": 2727, "s": 1744, "text": "#include <stdio.h>\n#include <stdlib.h>\ntypedef struct linklist{\n int data;\n struct linklist *next;\n}node;\nint l=0;\nint main(){\n node *head=NULL,*temp,*temp1;\n int len,choice,count=0,key;\n do{\n temp=(node *)malloc(sizeof(node));\n if(temp!=NULL){\n printf(\"\\nenter the elements in a list : \");\n scanf(\"%d\",&temp->data);\n temp->next=NULL;\n if(head==NULL){\n head=temp;\n }else{\n temp1=head;\n while(temp1->next!=NULL){\n temp1=temp1->next;\n }\n temp1->next=temp;\n }\n }else{\n printf(\"\\nMemory is full\");\n }\n printf(\"\\npress 1 to enter data into list: \");\n scanf(\"%d\",&choice);\n }while(choice==1);\n len=length(head);\n printf(\"The list has %d no of nodes\",l);\n return 0;\n}\n//recursive function to find length\nint length(node *temp){\n if(temp==NULL)\n return l;\n else{\n l=l+1;\n length(temp->next);\n }\n}" }, { "code": null, "e": 2798, "s": 2727, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3205, "s": 2798, "text": "Run 1:\nenter the elements in a list: 3\npress 1 to enter data into list: 1\nenter the elements in a list: 56\npress 1 to enter data into list: 1\nenter the elements in a list: 56\npress 1 to enter data into list: 0\nThe list has 3 no of nodes\nRun 2:\nenter the elements in a list: 12\npress 1 to enter data into list: 1\nenter the elements in a list: 45\npress 1 to enter data into list: 0\nThe list has 2 no of nodes" } ]
A Comprehensive Guide for Classes in Python | by Soner Yıldırım | Towards Data Science
We see a bunch of different clocks in this photo. They have different shapes, colors, and sizes. However, all of them are a type of clock. We can think of classes in Python in a similar way. A class represents a type (clock) and we can create many instances of that type (clocks in the photo above). Object oriented programming (OOP) paradigm is built around the idea of having objects that belong to a particular type. In a sense, the type is what explains us the object. The explanation of an object is of crucial importance for OOP. We need to have a comprehensive understanding of: What an object represents What kind of data the object stores How we can interact with the object How we can implement the object in our code All these points that constitute the explanation of an object are defined with classes. Everything in Python is an object of a type such as integers, lists, dictionaries, functions and so on. We define a type of object using classes. In this article, we will go over what class means, how a class is created and used in Python, and what kind of advantages we obtain by using classes. The outline is as follows: What is a class in Python? Creating a class Defining class methods Class vs instance variables Creating a child class Classes possess the following information: Data attributes: What is needed to create an instance of a class Methods (i.e. procedural attributes): How we interact with instances of a class. There are many advantages of using classes. Instead of listing all at once, I will mention them throughout the article. We use classes in Python all the time. For instance, when we create a list, we create an instance of type list. words = ['data', 'science', 'machine', 'learning'] We are not actually interested in how the list class is created. We just need to know how to interact with lists and use them efficiently in our code. This is the idea of abstraction. For instance, we can remove an item from a list using the remove method. words.remove('data')print(words)['science', 'machine', 'learning'] The following code creates a class called Book. class Book(): def __init__(self, name, writer, word_length): self.name = name self.writer = writer self.word_length = word_length The __init__ is a special function that is automatically executed when an instance of class is created. It is also called class constructor. The parameters of the init function represent the data attributes of a class. Thus, if we need to specify the arguments for name, writer, and length parameters to create an instance of Book. Note: Self refers to the instance itself. You can use any word instead of “self” but it is a highly common practice to use “self”. Let’s create an instance. b1 = Book("Pandas", "John Doe", 100000)print(type(b1))<class '__main__.Book'> b1 is an object that belongs to the Book class. We can confirm it by using the type function which returns the type of an object. We can access or modify the attributes of a class using the following way. print(b1.name)Pandasb1.name = 'NumPy' #updates the name attributeprint(b1.name)NumPy The Book class only have data attributes. We should add methods (i.e. procedural attributes) to make it for useful and functional. For instance, we can implement a method that returns the number of pages given the fontsize. We specify the length of the book in number of words. The method will calculate the number of pages based on the length and fontsize. def number_of_pages(self, fontsize=12): word_length = self.word_length if fontsize == 12: words_in_page = 300 else: words_in_page = 300 - (fontsize - 12) * 10 return round(word_length / words_in_page) We add the number_of_pages in the class definition. It calculates the number of pages of a book based on the number of words and fontsize. If a function we declare inside a class definition needs to access data attributes of an instance, we need to tell the function how to access them. This is what we did in the first line of the number_of_pages function. We can access a method from the class or the instance. Here is a simple example that demonstrates both ways. b1 = Book("Pandas", "John Doe", 100000)b1.number_of_pages()333Book.number_of_pages(b1)333 The number_of_pages function has an additional fontsize parameter. Since a default value (12) is specified, we do not have to explicitly write it. However, we can use a different value for the fontsize parameter. b1.number_of_pages(14)357b1.number_of_pages(fontsize=16)385 As the fontsize increases, the number of pages also increases which makes sense. There are certain methods that we need to define for our class in order to use some built-in functions of Python. Consider the print function. print(b1)<__main__.Book object at 0x7fa4cf9f7588> The print function returns the type and the memory location of the object by default. However, we can customize its behavior by implementing the __str__ method in our class. def __str__(self): return "<" + self.name + ", by " + self.writer + ">" We add the __str__ method in our class definition as above. Here is how the print function works for our class now: print(b1)<Pandas, by John Doe> Class variables are declared inside a class but outside of any function. Instance variables are declared inside the constructor which is the __init__ method. The class variables are more general and likely to apply all of the instances of a class. On the other hand, instance variables are more specific and defined for each instance separately. Having a distinction between class and instance variables is quite useful. Consider the Book class we defined earlier. We run a publishing company and have some standards for the books we publish such as page width and color for the cover. If we define them as class variables, we do not have to explicitly declare for each instance created. class Book(): page_width = 14 cover_color = "blue" def __init__(self, name, writer, word_length): self.name = name self.writer = writer self.word_length = word_length We have implemented the page_width and cover_color as class variables because they are inside the class definition but outside any function definition. Let’s create an instance of the Book class. b2 = Book("Machine Learning", "Jane Doe", 120000) We have not specified the class variables while creating this instance. However, the b2 possesses these variables and we can access them. b2.page_width14b2.cover_color'blue' We have the option to change the class variables for a particular instance. b2.cover_color = 'red'b2.cover_color'red' The changes on a particular instance do not have any effect on the class variable. Book.cover_color'blue' We can create a class based on a different class. Let’s create a class called “ColorBook” based on the “Book” class. class ColorBook(Book): The ColorBook is a child class of the Book class. When we create a class in this way, the child class copies the attributes (both data and procedural) from the parent class. This concept is called inheritance which makes the OOP more efficient and powerful. It is similar to the inheritance in real life. Most of our genome come from our parents or ancestors. We inherit from them. Thus, we have similarities with our parents. A child class can have new attributes in addition to the ones inherited from the parent class. Furthermore, we have the option to modify or override the inherited attributes. Let’s define the __init__ function of the ColorBook class. It will have two additional parameters which are “color” indication the color of pages and “has_image” indicating if there are images in the book. class ColorBook(Book): def __init__(self, name, writer, word_length, color, has_image): Book.__init__(self, name, writer, word_length self.color = color self.has_image = has_image Since the name, writer, and word_length have already been defined in the Book class, we can just copy the __init__ method from it. We just need to define the additional attributes. Note: We are free to define each data attribute manually for the child class. Using the __init__ of parent is optional. Let’s create an instance of the ColorBook class. c1 = ColorBook("Seaborn", "John Doe", 90000, "green", True)c1.name"Seaborn"c1.color"green" The child class also inherits the class variables. c1.cover_color"blue"c1.page_width14 The methods are also copied from the parent class. For the Book class, we defined two methods that can also be used on the instances of the ColorBook class. c1.number_of_pages()300print(c1)<Seaborn, by John Doe> We have the option to override the data and procedural attributes (i.e. methods) inherited from the parent class. This makes the inheritance even more powerful because we are obligated to use everything in the parent class. For instance, we can modify the __str__ method for the ColorBook class. def __str__(self): return "<" + self.name + ", in " + self.color + ">" The print function will return the name of the book and its color. c1 = ColorBook("Seaborn", "John Doe", 90000, "green", True)print(c1)<Seaborn, in green> Here are the class definitions for the Book and ColorBook classes. What we have covered in this article can be considered as a comprehensive introduction to Python classes. We have mentioned the importance of classes for object oriented programming and how classes demonstrates the key concepts such as abstraction and inheritance. For the practical side, we have defined two classes and seen how inheritance works when creating a child class. There is much more to cover about Python classes. Once you are comfortable working with the basics, feel free to move onto the more advance topics. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 472, "s": 172, "text": "We see a bunch of different clocks in this photo. They have different shapes, colors, and sizes. However, all of them are a type of clock. We can think of classes in Python in a similar way. A class represents a type (clock) and we can create many instances of that type (clocks in the photo above)." }, { "code": null, "e": 645, "s": 472, "text": "Object oriented programming (OOP) paradigm is built around the idea of having objects that belong to a particular type. In a sense, the type is what explains us the object." }, { "code": null, "e": 758, "s": 645, "text": "The explanation of an object is of crucial importance for OOP. We need to have a comprehensive understanding of:" }, { "code": null, "e": 784, "s": 758, "text": "What an object represents" }, { "code": null, "e": 820, "s": 784, "text": "What kind of data the object stores" }, { "code": null, "e": 856, "s": 820, "text": "How we can interact with the object" }, { "code": null, "e": 900, "s": 856, "text": "How we can implement the object in our code" }, { "code": null, "e": 1134, "s": 900, "text": "All these points that constitute the explanation of an object are defined with classes. Everything in Python is an object of a type such as integers, lists, dictionaries, functions and so on. We define a type of object using classes." }, { "code": null, "e": 1311, "s": 1134, "text": "In this article, we will go over what class means, how a class is created and used in Python, and what kind of advantages we obtain by using classes. The outline is as follows:" }, { "code": null, "e": 1338, "s": 1311, "text": "What is a class in Python?" }, { "code": null, "e": 1355, "s": 1338, "text": "Creating a class" }, { "code": null, "e": 1378, "s": 1355, "text": "Defining class methods" }, { "code": null, "e": 1406, "s": 1378, "text": "Class vs instance variables" }, { "code": null, "e": 1429, "s": 1406, "text": "Creating a child class" }, { "code": null, "e": 1472, "s": 1429, "text": "Classes possess the following information:" }, { "code": null, "e": 1537, "s": 1472, "text": "Data attributes: What is needed to create an instance of a class" }, { "code": null, "e": 1618, "s": 1537, "text": "Methods (i.e. procedural attributes): How we interact with instances of a class." }, { "code": null, "e": 1738, "s": 1618, "text": "There are many advantages of using classes. Instead of listing all at once, I will mention them throughout the article." }, { "code": null, "e": 1850, "s": 1738, "text": "We use classes in Python all the time. For instance, when we create a list, we create an instance of type list." }, { "code": null, "e": 1901, "s": 1850, "text": "words = ['data', 'science', 'machine', 'learning']" }, { "code": null, "e": 2085, "s": 1901, "text": "We are not actually interested in how the list class is created. We just need to know how to interact with lists and use them efficiently in our code. This is the idea of abstraction." }, { "code": null, "e": 2158, "s": 2085, "text": "For instance, we can remove an item from a list using the remove method." }, { "code": null, "e": 2225, "s": 2158, "text": "words.remove('data')print(words)['science', 'machine', 'learning']" }, { "code": null, "e": 2273, "s": 2225, "text": "The following code creates a class called Book." }, { "code": null, "e": 2413, "s": 2273, "text": "class Book(): def __init__(self, name, writer, word_length): self.name = name self.writer = writer self.word_length = word_length" }, { "code": null, "e": 2554, "s": 2413, "text": "The __init__ is a special function that is automatically executed when an instance of class is created. It is also called class constructor." }, { "code": null, "e": 2745, "s": 2554, "text": "The parameters of the init function represent the data attributes of a class. Thus, if we need to specify the arguments for name, writer, and length parameters to create an instance of Book." }, { "code": null, "e": 2876, "s": 2745, "text": "Note: Self refers to the instance itself. You can use any word instead of “self” but it is a highly common practice to use “self”." }, { "code": null, "e": 2902, "s": 2876, "text": "Let’s create an instance." }, { "code": null, "e": 2980, "s": 2902, "text": "b1 = Book(\"Pandas\", \"John Doe\", 100000)print(type(b1))<class '__main__.Book'>" }, { "code": null, "e": 3110, "s": 2980, "text": "b1 is an object that belongs to the Book class. We can confirm it by using the type function which returns the type of an object." }, { "code": null, "e": 3185, "s": 3110, "text": "We can access or modify the attributes of a class using the following way." }, { "code": null, "e": 3270, "s": 3185, "text": "print(b1.name)Pandasb1.name = 'NumPy' #updates the name attributeprint(b1.name)NumPy" }, { "code": null, "e": 3401, "s": 3270, "text": "The Book class only have data attributes. We should add methods (i.e. procedural attributes) to make it for useful and functional." }, { "code": null, "e": 3628, "s": 3401, "text": "For instance, we can implement a method that returns the number of pages given the fontsize. We specify the length of the book in number of words. The method will calculate the number of pages based on the length and fontsize." }, { "code": null, "e": 3839, "s": 3628, "text": "def number_of_pages(self, fontsize=12): word_length = self.word_length if fontsize == 12: words_in_page = 300 else: words_in_page = 300 - (fontsize - 12) * 10 return round(word_length / words_in_page)" }, { "code": null, "e": 3978, "s": 3839, "text": "We add the number_of_pages in the class definition. It calculates the number of pages of a book based on the number of words and fontsize." }, { "code": null, "e": 4197, "s": 3978, "text": "If a function we declare inside a class definition needs to access data attributes of an instance, we need to tell the function how to access them. This is what we did in the first line of the number_of_pages function." }, { "code": null, "e": 4306, "s": 4197, "text": "We can access a method from the class or the instance. Here is a simple example that demonstrates both ways." }, { "code": null, "e": 4396, "s": 4306, "text": "b1 = Book(\"Pandas\", \"John Doe\", 100000)b1.number_of_pages()333Book.number_of_pages(b1)333" }, { "code": null, "e": 4609, "s": 4396, "text": "The number_of_pages function has an additional fontsize parameter. Since a default value (12) is specified, we do not have to explicitly write it. However, we can use a different value for the fontsize parameter." }, { "code": null, "e": 4669, "s": 4609, "text": "b1.number_of_pages(14)357b1.number_of_pages(fontsize=16)385" }, { "code": null, "e": 4750, "s": 4669, "text": "As the fontsize increases, the number of pages also increases which makes sense." }, { "code": null, "e": 4893, "s": 4750, "text": "There are certain methods that we need to define for our class in order to use some built-in functions of Python. Consider the print function." }, { "code": null, "e": 4943, "s": 4893, "text": "print(b1)<__main__.Book object at 0x7fa4cf9f7588>" }, { "code": null, "e": 5117, "s": 4943, "text": "The print function returns the type and the memory location of the object by default. However, we can customize its behavior by implementing the __str__ method in our class." }, { "code": null, "e": 5190, "s": 5117, "text": "def __str__(self): return \"<\" + self.name + \", by \" + self.writer + \">\"" }, { "code": null, "e": 5306, "s": 5190, "text": "We add the __str__ method in our class definition as above. Here is how the print function works for our class now:" }, { "code": null, "e": 5337, "s": 5306, "text": "print(b1)<Pandas, by John Doe>" }, { "code": null, "e": 5495, "s": 5337, "text": "Class variables are declared inside a class but outside of any function. Instance variables are declared inside the constructor which is the __init__ method." }, { "code": null, "e": 5758, "s": 5495, "text": "The class variables are more general and likely to apply all of the instances of a class. On the other hand, instance variables are more specific and defined for each instance separately. Having a distinction between class and instance variables is quite useful." }, { "code": null, "e": 6025, "s": 5758, "text": "Consider the Book class we defined earlier. We run a publishing company and have some standards for the books we publish such as page width and color for the cover. If we define them as class variables, we do not have to explicitly declare for each instance created." }, { "code": null, "e": 6204, "s": 6025, "text": "class Book(): page_width = 14 cover_color = \"blue\" def __init__(self, name, writer, word_length): self.name = name self.writer = writer self.word_length = word_length" }, { "code": null, "e": 6356, "s": 6204, "text": "We have implemented the page_width and cover_color as class variables because they are inside the class definition but outside any function definition." }, { "code": null, "e": 6400, "s": 6356, "text": "Let’s create an instance of the Book class." }, { "code": null, "e": 6450, "s": 6400, "text": "b2 = Book(\"Machine Learning\", \"Jane Doe\", 120000)" }, { "code": null, "e": 6588, "s": 6450, "text": "We have not specified the class variables while creating this instance. However, the b2 possesses these variables and we can access them." }, { "code": null, "e": 6624, "s": 6588, "text": "b2.page_width14b2.cover_color'blue'" }, { "code": null, "e": 6700, "s": 6624, "text": "We have the option to change the class variables for a particular instance." }, { "code": null, "e": 6742, "s": 6700, "text": "b2.cover_color = 'red'b2.cover_color'red'" }, { "code": null, "e": 6825, "s": 6742, "text": "The changes on a particular instance do not have any effect on the class variable." }, { "code": null, "e": 6848, "s": 6825, "text": "Book.cover_color'blue'" }, { "code": null, "e": 6965, "s": 6848, "text": "We can create a class based on a different class. Let’s create a class called “ColorBook” based on the “Book” class." }, { "code": null, "e": 6988, "s": 6965, "text": "class ColorBook(Book):" }, { "code": null, "e": 7246, "s": 6988, "text": "The ColorBook is a child class of the Book class. When we create a class in this way, the child class copies the attributes (both data and procedural) from the parent class. This concept is called inheritance which makes the OOP more efficient and powerful." }, { "code": null, "e": 7415, "s": 7246, "text": "It is similar to the inheritance in real life. Most of our genome come from our parents or ancestors. We inherit from them. Thus, we have similarities with our parents." }, { "code": null, "e": 7590, "s": 7415, "text": "A child class can have new attributes in addition to the ones inherited from the parent class. Furthermore, we have the option to modify or override the inherited attributes." }, { "code": null, "e": 7796, "s": 7590, "text": "Let’s define the __init__ function of the ColorBook class. It will have two additional parameters which are “color” indication the color of pages and “has_image” indicating if there are images in the book." }, { "code": null, "e": 7986, "s": 7796, "text": "class ColorBook(Book): def __init__(self, name, writer, word_length, color, has_image): Book.__init__(self, name, writer, word_length self.color = color self.has_image = has_image" }, { "code": null, "e": 8167, "s": 7986, "text": "Since the name, writer, and word_length have already been defined in the Book class, we can just copy the __init__ method from it. We just need to define the additional attributes." }, { "code": null, "e": 8287, "s": 8167, "text": "Note: We are free to define each data attribute manually for the child class. Using the __init__ of parent is optional." }, { "code": null, "e": 8336, "s": 8287, "text": "Let’s create an instance of the ColorBook class." }, { "code": null, "e": 8427, "s": 8336, "text": "c1 = ColorBook(\"Seaborn\", \"John Doe\", 90000, \"green\", True)c1.name\"Seaborn\"c1.color\"green\"" }, { "code": null, "e": 8478, "s": 8427, "text": "The child class also inherits the class variables." }, { "code": null, "e": 8514, "s": 8478, "text": "c1.cover_color\"blue\"c1.page_width14" }, { "code": null, "e": 8671, "s": 8514, "text": "The methods are also copied from the parent class. For the Book class, we defined two methods that can also be used on the instances of the ColorBook class." }, { "code": null, "e": 8726, "s": 8671, "text": "c1.number_of_pages()300print(c1)<Seaborn, by John Doe>" }, { "code": null, "e": 8950, "s": 8726, "text": "We have the option to override the data and procedural attributes (i.e. methods) inherited from the parent class. This makes the inheritance even more powerful because we are obligated to use everything in the parent class." }, { "code": null, "e": 9022, "s": 8950, "text": "For instance, we can modify the __str__ method for the ColorBook class." }, { "code": null, "e": 9094, "s": 9022, "text": "def __str__(self): return \"<\" + self.name + \", in \" + self.color + \">\"" }, { "code": null, "e": 9161, "s": 9094, "text": "The print function will return the name of the book and its color." }, { "code": null, "e": 9249, "s": 9161, "text": "c1 = ColorBook(\"Seaborn\", \"John Doe\", 90000, \"green\", True)print(c1)<Seaborn, in green>" }, { "code": null, "e": 9316, "s": 9249, "text": "Here are the class definitions for the Book and ColorBook classes." }, { "code": null, "e": 9581, "s": 9316, "text": "What we have covered in this article can be considered as a comprehensive introduction to Python classes. We have mentioned the importance of classes for object oriented programming and how classes demonstrates the key concepts such as abstraction and inheritance." }, { "code": null, "e": 9693, "s": 9581, "text": "For the practical side, we have defined two classes and seen how inheritance works when creating a child class." }, { "code": null, "e": 9841, "s": 9693, "text": "There is much more to cover about Python classes. Once you are comfortable working with the basics, feel free to move onto the more advance topics." } ]
The Top 5 Data Science Certifications | Towards Data Science
IntroductionTensorFlowSASIBM Data Science — PythonTableauGoogle Machine LearningSummaryReferences Introduction TensorFlow SAS IBM Data Science — Python Tableau Google Machine Learning Summary References While there are countless articles on this particular topic, I wanted to search unique, yet commonly used programs or platforms practiced by a typical data scientist along with their respective certifications. Some of these are free, some will have a small price, but all may be well worth investing. It all ultimately depends on what your focus and path are in data science. There are several reasons for wanting to pursue a certificate in your data science career; some may be more direct, like a data science certificate, or a more indirect certificate like programming in Python. With in-person teaching and learning becoming less popular, even before the current state of the world, online learning is not looked at as a nice-to-have only, but almost a requirement in order to become a successful data scientist or data science applicant. Whereas in the past, online programs and certifications seemed to have a negative cloud around them, they are now becoming expected by employers and show those same employers how willing you are to improve on your skills, no matter where you are in your career. I have had a somewhat formal master's of science in data science education from Southern Methodist University; however, it was online, and employers did not hesitate to think it was any less of a degree. Similarly, several hiring managers enjoyed and were generally impressed when I would bring up certificates in data science, and other forms outside of traditional education like tutorials. In addition to having experience in various forms of learning, I have experience in being a professional data scientist as well and have therefore gained a general sense of which skills employers desire you to have. Additionally, I have become well aware of some of the tools and platforms that could really benefit you in your day-to-day work. Below, I will outline five data scientist certifications that can boost your career in data science. TensorFlow [2] is widely used by both data scientists and machine learning engineers. It serves as an open-sourced platform that includes powerful libraries that drive your machine learning model building process. Typical projects with TensorFlow may go over: neural networks, generative adversarial networks, image classification, text classification, regression, boosted trees, time series forecasting, and much more The title of the TensorFlow certification is: TensorFlow Developer Certificate program [2]. The program entails models over computer vision, convolutional neural networks, and natural language processing (NLP). While the cost of the exam is $100, TensfowFlow recommends obtaining an education stipend from your current employer (suggesting relative success). This certificate is useful if your focus is on either or both machine learning and deep learning. The certificate itself is not a tutorial of course, but only a certified method of confirming your success in TensorFlow. However, they recommend the TensorFlow in Practice Specialization offered through Coursera. The best part of this specialization is that it covers all things TensorFlow for free. Only take the exam if you believe the $100 fee is worth it or if you can get it waived with the stipend program. Some interesting stats from this specialization are that: 40% started a new career after completing 12% pay increase or promotion As you can see, this certificate along with its respective certification is an outstanding way to show off your skills and certify your competency from a widely used and attractive platform. SAS [3] is perhaps, the least commonly used platform for data scientists. However, this statement can be turned into a positive, as you can ensure that your skillset is truly unique and one of a kind. You will be able to offer something that most data scientists can not. While Python and R are the typical programming languages used by both data scientists and machine learning engineers, SAS is another language, almost more similar to SQL that focuses on statistics. When I started my data science master’s degree, this platform was the first method of learning I had with data science. SAS stands for Statistical Analysis System. As a data scientist, you can dangerously slip into black-box machine learning. However, when you learn with SAS, you get pretty granular with statistics. This knowledge will be especially useful in data science interviews when hiring managers will ask you complex statistical questions that cannot be answered with typical Python data science libraries. A lot of the benefit of SAS is testing for normality with methods like Q-Q plots, histograms, and residual plots. and performing tests like ANOVA’s and MANOVA’s (Analysis of Variance, or Multiple Analysis of Variance). The title of the certificate is: SAS Programmer Professional Certificate [3]. This certification is also offered through Coursera. You can enroll for free and get certified at a price. Keep in mind, even though these are certifications and the courses are usually free, the exam or actual tangible certification will usually cost you. However, you may still do most of these courses, if not all, for free, and if your employer or whomever you are showing your certificate to is understanding, you may be able to show them your work and completion of the associated courses without paying the fee. You will learn techniques in the SAS programming language as well as explore different data types. The career outcomes of this certificate and its respective course are quite impressive: 21% started a new career after this specialization 50% got a pay increase or promotion Whereas the previous certificates and their respective courses were focused on specific sub facets of data science, this certification encompasses much of the overall, general data science process. The title of this certificate is: IBM Data Science Professional Certificate [4]. Similar to the above certificate, this one is also offered through Coursera. Since this certificate is more encompassing, I will list out all nine courses for this professional certification. What is Data Science? Tools for Data Science (Jupyter Notebook, RStudio IDE, etc) Data Science Methodology (computing power, deployment, etc) Python for Data Science and AI (types, variables, classes module, etc) Databases and SQL for Data Science (Structured Query Language, etc) Data Analysis with Python (Pandas, Numpy, and Scipy libraries, etc) Data Visualization with Python (Matplotlib, Seaborn, etc) Machine Learning with Python (classification, clustering, etc) Applied Data Science Capstone (RESTful API calls, Folium, etc) As you can see, this certification includes nearly every part of data science and even machine learning. Depending on your goal and where you apply, this course could completely substitute a degree. The evidence to support that statement comes from: 46% started a new career after completing 19% got a pay increase or promotion These stats are incredible — making it one of the most beneficial courses and certifications you can take. I recommend this course if you want a holistic view of data science. To articulate how popular this course is, around 1 million people have viewed the certificate homepage. This certificate could cause some controversy, but it should be something you seriously take into consideration. Perhaps it is more of a data analysis or business intelligence skill, Tableau [5] serves as a visualization tool to describe metrics and statistics. However, there are several other ways that Tableau can be useful for data scientists. Some of those benefits include: visual representation of model ingestion data exploratory data analysis shifts and trend analysis impressive visualizations for your data science model metrics Oftentimes, when you are a data scientist, you will need to present your findings, and Tableau is an easy tool that helps you describe your model stats and metrics so that your stakeholders can see daily, for example, how well the business problem is being solved. There are several different specific certifications, but I will highlight one: Tableau Desktop Specialist [5]. This certificate focuses on the fundamentals of Tableau, which is most likely all you will need. As a data scientist, it is assumed that you have impressive problem-solving skills, so once you know the basics, you will be able to learn the more complex functions as you go. The fee is $100 for this certification. The exam is multiple-choice, multiple responses, and hands-on with 30 questions in 60 minutes, with automatic scoring. Tableau offers several classes as well that will help you in acing this exam. As some of these courses and certificates focus more on data science and machine learning directly, this certificate will separate you in the large pool of data scientists by knowing how to present your data science findings with Tableau. The last certification, perhaps the most difficult, is from Google [6]. It is preferred to achieve this certificate if you are a machine learning engineer, but if you are a data scientist focusing just on models, this certificate will allow you to go further into deployment and engineering. The exam will test these main complex concepts: Frame ML problemsDevelop ML modelsArchitect ML solutionsAutomate & orchestrate ML pipelinesPrepare and process dataMonitor, optimize, and maintain ML solutions You can choose the beta exam which allows becoming Google Cloud Certified, saving you 40% on the cost, and also some swag — exclusive Google-branded apparel. The title of the officiating certification is: Professional Machine Learning EngineerBETA [6]. The key objectives that the exam tests you on are extremely useful concepts that every data scientist or machine learning engineer could eventually benefit from. Some of those key objectives are: framing the ML problem by translating the business challenge into an ML use case ML solution architecture with SDLC best practices data preparation and processing with designing data pipelines ML model development with productionizing ML pipeline automation and orchestration with CI/CD test and deployment ML solution monitoring, optimization, and maintenance with tuning performance and identification of retraining. As you can see, this certification is complex and covers difficult, yet incredibly important characteristics of data science and machine learning. You do not need all of these courses or certificates to become the best data scientist; however, they can all work to make you highly successful in different ways. You have learned about five top certifications. Here are all of them listed out with their respective links: TensorFlow Developer Certificate program [2]SAS Programmer Professional Certificate [3] IBM Data Science Professional Certificate [4]Tableau Desktop Specialist [5]Professional Machine Learning EngineerBETA [6] Of course, there are more courses and endless certificates. But, the most important thing you can do for your career is to jump into either of these certificates (or other similar ones) and work towards bettering yourself as a data scientist. Imagine being certified in TensorFlow, SAS, IBM Data Science, Tableau, and Google Machine Learning. You would certainly impress employers of the current and future. Not only would these certificates make you look better to other data scientists when interviewing, but they will also ultimately help you to become better in your data science career. Learning should never stop, and completing courses and certificates is no exception. I hope you found this article interesting, unique, and useful! Feel free to comment down below and start learning as well. Thank you for reading! [1] Photo by SCREEN POST on Unsplash, (2020) [2] TensorFlow, TensorFlow Developer Certificate program, (2020)[3] Coursera, SAS Programmer Professional Certificate, (2020)[4] Coursera, IBM Data Science Professional Certificate, (2020)[5] Tableau, Tableau Desktop Specialist, (2003–2020)[6] Google, Professional Machine Learning EngineerBETA, (2020) [7] Photo by Remy_Loz on Unsplash, (2020)
[ { "code": null, "e": 270, "s": 172, "text": "IntroductionTensorFlowSASIBM Data Science — PythonTableauGoogle Machine LearningSummaryReferences" }, { "code": null, "e": 283, "s": 270, "text": "Introduction" }, { "code": null, "e": 294, "s": 283, "text": "TensorFlow" }, { "code": null, "e": 298, "s": 294, "text": "SAS" }, { "code": null, "e": 324, "s": 298, "text": "IBM Data Science — Python" }, { "code": null, "e": 332, "s": 324, "text": "Tableau" }, { "code": null, "e": 356, "s": 332, "text": "Google Machine Learning" }, { "code": null, "e": 364, "s": 356, "text": "Summary" }, { "code": null, "e": 375, "s": 364, "text": "References" }, { "code": null, "e": 1481, "s": 375, "text": "While there are countless articles on this particular topic, I wanted to search unique, yet commonly used programs or platforms practiced by a typical data scientist along with their respective certifications. Some of these are free, some will have a small price, but all may be well worth investing. It all ultimately depends on what your focus and path are in data science. There are several reasons for wanting to pursue a certificate in your data science career; some may be more direct, like a data science certificate, or a more indirect certificate like programming in Python. With in-person teaching and learning becoming less popular, even before the current state of the world, online learning is not looked at as a nice-to-have only, but almost a requirement in order to become a successful data scientist or data science applicant. Whereas in the past, online programs and certifications seemed to have a negative cloud around them, they are now becoming expected by employers and show those same employers how willing you are to improve on your skills, no matter where you are in your career." }, { "code": null, "e": 2219, "s": 1481, "text": "I have had a somewhat formal master's of science in data science education from Southern Methodist University; however, it was online, and employers did not hesitate to think it was any less of a degree. Similarly, several hiring managers enjoyed and were generally impressed when I would bring up certificates in data science, and other forms outside of traditional education like tutorials. In addition to having experience in various forms of learning, I have experience in being a professional data scientist as well and have therefore gained a general sense of which skills employers desire you to have. Additionally, I have become well aware of some of the tools and platforms that could really benefit you in your day-to-day work." }, { "code": null, "e": 2320, "s": 2219, "text": "Below, I will outline five data scientist certifications that can boost your career in data science." }, { "code": null, "e": 2580, "s": 2320, "text": "TensorFlow [2] is widely used by both data scientists and machine learning engineers. It serves as an open-sourced platform that includes powerful libraries that drive your machine learning model building process. Typical projects with TensorFlow may go over:" }, { "code": null, "e": 2739, "s": 2580, "text": "neural networks, generative adversarial networks, image classification, text classification, regression, boosted trees, time series forecasting, and much more" }, { "code": null, "e": 2785, "s": 2739, "text": "The title of the TensorFlow certification is:" }, { "code": null, "e": 2831, "s": 2785, "text": "TensorFlow Developer Certificate program [2]." }, { "code": null, "e": 3668, "s": 2831, "text": "The program entails models over computer vision, convolutional neural networks, and natural language processing (NLP). While the cost of the exam is $100, TensfowFlow recommends obtaining an education stipend from your current employer (suggesting relative success). This certificate is useful if your focus is on either or both machine learning and deep learning. The certificate itself is not a tutorial of course, but only a certified method of confirming your success in TensorFlow. However, they recommend the TensorFlow in Practice Specialization offered through Coursera. The best part of this specialization is that it covers all things TensorFlow for free. Only take the exam if you believe the $100 fee is worth it or if you can get it waived with the stipend program. Some interesting stats from this specialization are that:" }, { "code": null, "e": 3710, "s": 3668, "text": "40% started a new career after completing" }, { "code": null, "e": 3740, "s": 3710, "text": "12% pay increase or promotion" }, { "code": null, "e": 3931, "s": 3740, "text": "As you can see, this certificate along with its respective certification is an outstanding way to show off your skills and certify your competency from a widely used and attractive platform." }, { "code": null, "e": 4521, "s": 3931, "text": "SAS [3] is perhaps, the least commonly used platform for data scientists. However, this statement can be turned into a positive, as you can ensure that your skillset is truly unique and one of a kind. You will be able to offer something that most data scientists can not. While Python and R are the typical programming languages used by both data scientists and machine learning engineers, SAS is another language, almost more similar to SQL that focuses on statistics. When I started my data science master’s degree, this platform was the first method of learning I had with data science." }, { "code": null, "e": 5138, "s": 4521, "text": "SAS stands for Statistical Analysis System. As a data scientist, you can dangerously slip into black-box machine learning. However, when you learn with SAS, you get pretty granular with statistics. This knowledge will be especially useful in data science interviews when hiring managers will ask you complex statistical questions that cannot be answered with typical Python data science libraries. A lot of the benefit of SAS is testing for normality with methods like Q-Q plots, histograms, and residual plots. and performing tests like ANOVA’s and MANOVA’s (Analysis of Variance, or Multiple Analysis of Variance)." }, { "code": null, "e": 5171, "s": 5138, "text": "The title of the certificate is:" }, { "code": null, "e": 5216, "s": 5171, "text": "SAS Programmer Professional Certificate [3]." }, { "code": null, "e": 5323, "s": 5216, "text": "This certification is also offered through Coursera. You can enroll for free and get certified at a price." }, { "code": null, "e": 5735, "s": 5323, "text": "Keep in mind, even though these are certifications and the courses are usually free, the exam or actual tangible certification will usually cost you. However, you may still do most of these courses, if not all, for free, and if your employer or whomever you are showing your certificate to is understanding, you may be able to show them your work and completion of the associated courses without paying the fee." }, { "code": null, "e": 5922, "s": 5735, "text": "You will learn techniques in the SAS programming language as well as explore different data types. The career outcomes of this certificate and its respective course are quite impressive:" }, { "code": null, "e": 5973, "s": 5922, "text": "21% started a new career after this specialization" }, { "code": null, "e": 6009, "s": 5973, "text": "50% got a pay increase or promotion" }, { "code": null, "e": 6241, "s": 6009, "text": "Whereas the previous certificates and their respective courses were focused on specific sub facets of data science, this certification encompasses much of the overall, general data science process. The title of this certificate is:" }, { "code": null, "e": 6288, "s": 6241, "text": "IBM Data Science Professional Certificate [4]." }, { "code": null, "e": 6365, "s": 6288, "text": "Similar to the above certificate, this one is also offered through Coursera." }, { "code": null, "e": 6480, "s": 6365, "text": "Since this certificate is more encompassing, I will list out all nine courses for this professional certification." }, { "code": null, "e": 6502, "s": 6480, "text": "What is Data Science?" }, { "code": null, "e": 6562, "s": 6502, "text": "Tools for Data Science (Jupyter Notebook, RStudio IDE, etc)" }, { "code": null, "e": 6622, "s": 6562, "text": "Data Science Methodology (computing power, deployment, etc)" }, { "code": null, "e": 6693, "s": 6622, "text": "Python for Data Science and AI (types, variables, classes module, etc)" }, { "code": null, "e": 6761, "s": 6693, "text": "Databases and SQL for Data Science (Structured Query Language, etc)" }, { "code": null, "e": 6829, "s": 6761, "text": "Data Analysis with Python (Pandas, Numpy, and Scipy libraries, etc)" }, { "code": null, "e": 6887, "s": 6829, "text": "Data Visualization with Python (Matplotlib, Seaborn, etc)" }, { "code": null, "e": 6950, "s": 6887, "text": "Machine Learning with Python (classification, clustering, etc)" }, { "code": null, "e": 7013, "s": 6950, "text": "Applied Data Science Capstone (RESTful API calls, Folium, etc)" }, { "code": null, "e": 7263, "s": 7013, "text": "As you can see, this certification includes nearly every part of data science and even machine learning. Depending on your goal and where you apply, this course could completely substitute a degree. The evidence to support that statement comes from:" }, { "code": null, "e": 7305, "s": 7263, "text": "46% started a new career after completing" }, { "code": null, "e": 7341, "s": 7305, "text": "19% got a pay increase or promotion" }, { "code": null, "e": 7621, "s": 7341, "text": "These stats are incredible — making it one of the most beneficial courses and certifications you can take. I recommend this course if you want a holistic view of data science. To articulate how popular this course is, around 1 million people have viewed the certificate homepage." }, { "code": null, "e": 8001, "s": 7621, "text": "This certificate could cause some controversy, but it should be something you seriously take into consideration. Perhaps it is more of a data analysis or business intelligence skill, Tableau [5] serves as a visualization tool to describe metrics and statistics. However, there are several other ways that Tableau can be useful for data scientists. Some of those benefits include:" }, { "code": null, "e": 8047, "s": 8001, "text": "visual representation of model ingestion data" }, { "code": null, "e": 8073, "s": 8047, "text": "exploratory data analysis" }, { "code": null, "e": 8099, "s": 8073, "text": "shifts and trend analysis" }, { "code": null, "e": 8161, "s": 8099, "text": "impressive visualizations for your data science model metrics" }, { "code": null, "e": 8426, "s": 8161, "text": "Oftentimes, when you are a data scientist, you will need to present your findings, and Tableau is an easy tool that helps you describe your model stats and metrics so that your stakeholders can see daily, for example, how well the business problem is being solved." }, { "code": null, "e": 8505, "s": 8426, "text": "There are several different specific certifications, but I will highlight one:" }, { "code": null, "e": 8537, "s": 8505, "text": "Tableau Desktop Specialist [5]." }, { "code": null, "e": 9048, "s": 8537, "text": "This certificate focuses on the fundamentals of Tableau, which is most likely all you will need. As a data scientist, it is assumed that you have impressive problem-solving skills, so once you know the basics, you will be able to learn the more complex functions as you go. The fee is $100 for this certification. The exam is multiple-choice, multiple responses, and hands-on with 30 questions in 60 minutes, with automatic scoring. Tableau offers several classes as well that will help you in acing this exam." }, { "code": null, "e": 9287, "s": 9048, "text": "As some of these courses and certificates focus more on data science and machine learning directly, this certificate will separate you in the large pool of data scientists by knowing how to present your data science findings with Tableau." }, { "code": null, "e": 9627, "s": 9287, "text": "The last certification, perhaps the most difficult, is from Google [6]. It is preferred to achieve this certificate if you are a machine learning engineer, but if you are a data scientist focusing just on models, this certificate will allow you to go further into deployment and engineering. The exam will test these main complex concepts:" }, { "code": null, "e": 9787, "s": 9627, "text": "Frame ML problemsDevelop ML modelsArchitect ML solutionsAutomate & orchestrate ML pipelinesPrepare and process dataMonitor, optimize, and maintain ML solutions" }, { "code": null, "e": 9992, "s": 9787, "text": "You can choose the beta exam which allows becoming Google Cloud Certified, saving you 40% on the cost, and also some swag — exclusive Google-branded apparel. The title of the officiating certification is:" }, { "code": null, "e": 10040, "s": 9992, "text": "Professional Machine Learning EngineerBETA [6]." }, { "code": null, "e": 10236, "s": 10040, "text": "The key objectives that the exam tests you on are extremely useful concepts that every data scientist or machine learning engineer could eventually benefit from. Some of those key objectives are:" }, { "code": null, "e": 10317, "s": 10236, "text": "framing the ML problem by translating the business challenge into an ML use case" }, { "code": null, "e": 10367, "s": 10317, "text": "ML solution architecture with SDLC best practices" }, { "code": null, "e": 10429, "s": 10367, "text": "data preparation and processing with designing data pipelines" }, { "code": null, "e": 10471, "s": 10429, "text": "ML model development with productionizing" }, { "code": null, "e": 10543, "s": 10471, "text": "ML pipeline automation and orchestration with CI/CD test and deployment" }, { "code": null, "e": 10655, "s": 10543, "text": "ML solution monitoring, optimization, and maintenance with tuning performance and identification of retraining." }, { "code": null, "e": 10802, "s": 10655, "text": "As you can see, this certification is complex and covers difficult, yet incredibly important characteristics of data science and machine learning." }, { "code": null, "e": 11075, "s": 10802, "text": "You do not need all of these courses or certificates to become the best data scientist; however, they can all work to make you highly successful in different ways. You have learned about five top certifications. Here are all of them listed out with their respective links:" }, { "code": null, "e": 11285, "s": 11075, "text": "TensorFlow Developer Certificate program [2]SAS Programmer Professional Certificate [3] IBM Data Science Professional Certificate [4]Tableau Desktop Specialist [5]Professional Machine Learning EngineerBETA [6]" }, { "code": null, "e": 11962, "s": 11285, "text": "Of course, there are more courses and endless certificates. But, the most important thing you can do for your career is to jump into either of these certificates (or other similar ones) and work towards bettering yourself as a data scientist. Imagine being certified in TensorFlow, SAS, IBM Data Science, Tableau, and Google Machine Learning. You would certainly impress employers of the current and future. Not only would these certificates make you look better to other data scientists when interviewing, but they will also ultimately help you to become better in your data science career. Learning should never stop, and completing courses and certificates is no exception." }, { "code": null, "e": 12108, "s": 11962, "text": "I hope you found this article interesting, unique, and useful! Feel free to comment down below and start learning as well. Thank you for reading!" }, { "code": null, "e": 12153, "s": 12108, "text": "[1] Photo by SCREEN POST on Unsplash, (2020)" }, { "code": null, "e": 12456, "s": 12153, "text": "[2] TensorFlow, TensorFlow Developer Certificate program, (2020)[3] Coursera, SAS Programmer Professional Certificate, (2020)[4] Coursera, IBM Data Science Professional Certificate, (2020)[5] Tableau, Tableau Desktop Specialist, (2003–2020)[6] Google, Professional Machine Learning EngineerBETA, (2020)" } ]
How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python? - GeeksforGeeks
23 Dec, 2020 Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the Minimum and Maximum Value of a Column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. Database in use: We are going to use geeks(Database name) database and table describing the salary. Approach: Import module. Make a connection request with the database. Create an object for the database cursor. Execute the following MySQL query: SELECT MIN(Column_name) AS minimum FROM Table_name. SELECT MAX(Column_name) AS minimum FROM Table_name. And print the result. Example 1: Getting the minimum value of a column. Python3 # Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "root", password = "root123", database = "geeks") # Create a cursor objectcursor = mydb.cursor() # Execute the query cursor.execute("SELECT MIN(Value) AS minimum FROM salary") result = cursor.fetchall() for i in result: maximum= float(i[0]) print(maximum) # Close database connectionmydb.close() Output: 200.0 Example 2: Getting the maximum value of a column. Python3 # Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "root", password = "root123", database = "geeks") # Create a cursor objectcursor = mydb.cursor() cursor.execute("SELECT MAX(Value) AS maximum FROM salary") result = cursor.fetchall() for i in result: maximum = float(i[0]) print(maximum) # Close database connectionmydb.close() Output: 350030.0 Python-mySQL 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 Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n23 Dec, 2020" }, { "code": null, "e": 25706, "s": 25665, "text": "Prerequisite: Python: MySQL Create Table" }, { "code": null, "e": 26071, "s": 25706, "text": "In this article, we are going to see how to get the Minimum and Maximum Value of a Column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. " }, { "code": null, "e": 26088, "s": 26071, "text": "Database in use:" }, { "code": null, "e": 26171, "s": 26088, "text": "We are going to use geeks(Database name) database and table describing the salary." }, { "code": null, "e": 26181, "s": 26171, "text": "Approach:" }, { "code": null, "e": 26196, "s": 26181, "text": "Import module." }, { "code": null, "e": 26241, "s": 26196, "text": "Make a connection request with the database." }, { "code": null, "e": 26283, "s": 26241, "text": "Create an object for the database cursor." }, { "code": null, "e": 26318, "s": 26283, "text": "Execute the following MySQL query:" }, { "code": null, "e": 26422, "s": 26318, "text": "SELECT MIN(Column_name) AS minimum FROM Table_name.\nSELECT MAX(Column_name) AS minimum FROM Table_name." }, { "code": null, "e": 26444, "s": 26422, "text": "And print the result." }, { "code": null, "e": 26494, "s": 26444, "text": "Example 1: Getting the minimum value of a column." }, { "code": null, "e": 26502, "s": 26494, "text": "Python3" }, { "code": "# Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"root\", password = \"root123\", database = \"geeks\") # Create a cursor objectcursor = mydb.cursor() # Execute the query cursor.execute(\"SELECT MIN(Value) AS minimum FROM salary\") result = cursor.fetchall() for i in result: maximum= float(i[0]) print(maximum) # Close database connectionmydb.close()", "e": 26936, "s": 26502, "text": null }, { "code": null, "e": 26944, "s": 26936, "text": "Output:" }, { "code": null, "e": 26950, "s": 26944, "text": "200.0" }, { "code": null, "e": 27000, "s": 26950, "text": "Example 2: Getting the maximum value of a column." }, { "code": null, "e": 27008, "s": 27000, "text": "Python3" }, { "code": "# Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"root\", password = \"root123\", database = \"geeks\") # Create a cursor objectcursor = mydb.cursor() cursor.execute(\"SELECT MAX(Value) AS maximum FROM salary\") result = cursor.fetchall() for i in result: maximum = float(i[0]) print(maximum) # Close database connectionmydb.close()", "e": 27423, "s": 27008, "text": null }, { "code": null, "e": 27431, "s": 27423, "text": "Output:" }, { "code": null, "e": 27440, "s": 27431, "text": "350030.0" }, { "code": null, "e": 27453, "s": 27440, "text": "Python-mySQL" }, { "code": null, "e": 27460, "s": 27453, "text": "Python" }, { "code": null, "e": 27558, "s": 27460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27590, "s": 27558, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27632, "s": 27590, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27674, "s": 27632, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27730, "s": 27674, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27757, "s": 27730, "text": "Python Classes and Objects" }, { "code": null, "e": 27788, "s": 27757, "text": "Python | os.path.join() method" }, { "code": null, "e": 27817, "s": 27788, "text": "Create a directory in Python" }, { "code": null, "e": 27839, "s": 27817, "text": "Defaultdict in Python" }, { "code": null, "e": 27878, "s": 27839, "text": "Python | Get unique values from a list" } ]
Python program for removing i-th character from a string - GeeksforGeeks
20 Apr, 2020 Given the string, we have to remove the ith indexed character from the string. In any string, indexing always start from 0. Suppose we have a string geeks then its indexing will be as – g e e k s 0 1 2 3 4 Examples : Input : Geek i = 1 Output : Gek Input : Peter i = 4 Output : Pete Approach 1 : From the given string, i-th indexed element has to be removed. So, Split the string into two halves, before indexed character and after indexed character. Return the merged string. Below is the implementation of above approach : # Python3 program for removing i-th # indexed character from a string # Removes character at index idef remove(string, i): # Characters before the i-th indexed # is stored in a variable a a = string[ : i] # Characters after the nth indexed # is stored in a variable b b = string[i + 1: ] # Returning string after removing # nth indexed character. return a + b # Driver Codeif __name__ == '__main__': string = "geeksFORgeeks" # Remove nth index element i = 5 # Print the new string print(remove(string, i)) geeksORgeeks Approach 2 : The idea is to use string replace in Python # Python3 program for removing i-th # indexed character from a string # Removes character at index idef remove(string, i): for j in range(len(string)): if j == i: string = string.replace(string[i], "", 1) return string # Driver Codeif __name__ == '__main__': string = "geeksFORgeeks" # Remove nth index element i = 5 # Print the new string print(remove(string, i)) geeksORgeeks kunchamaparna509 Python string-programs python-string Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26131, "s": 26103, "text": "\n20 Apr, 2020" }, { "code": null, "e": 26210, "s": 26131, "text": "Given the string, we have to remove the ith indexed character from the string." }, { "code": null, "e": 26317, "s": 26210, "text": "In any string, indexing always start from 0. Suppose we have a string geeks then its indexing will be as –" }, { "code": null, "e": 26338, "s": 26317, "text": "g e e k s\n0 1 2 3 4\n" }, { "code": null, "e": 26349, "s": 26338, "text": "Examples :" }, { "code": null, "e": 26435, "s": 26349, "text": "Input : Geek\n i = 1\nOutput : Gek \n\nInput : Peter \n i = 4\nOutput : Pete\n" }, { "code": null, "e": 26631, "s": 26437, "text": "Approach 1 : From the given string, i-th indexed element has to be removed. So, Split the string into two halves, before indexed character and after indexed character. Return the merged string." }, { "code": null, "e": 26679, "s": 26631, "text": "Below is the implementation of above approach :" }, { "code": "# Python3 program for removing i-th # indexed character from a string # Removes character at index idef remove(string, i): # Characters before the i-th indexed # is stored in a variable a a = string[ : i] # Characters after the nth indexed # is stored in a variable b b = string[i + 1: ] # Returning string after removing # nth indexed character. return a + b # Driver Codeif __name__ == '__main__': string = \"geeksFORgeeks\" # Remove nth index element i = 5 # Print the new string print(remove(string, i))", "e": 27265, "s": 26679, "text": null }, { "code": null, "e": 27279, "s": 27265, "text": "geeksORgeeks\n" }, { "code": null, "e": 27336, "s": 27279, "text": "Approach 2 : The idea is to use string replace in Python" }, { "code": "# Python3 program for removing i-th # indexed character from a string # Removes character at index idef remove(string, i): for j in range(len(string)): if j == i: string = string.replace(string[i], \"\", 1) return string # Driver Codeif __name__ == '__main__': string = \"geeksFORgeeks\" # Remove nth index element i = 5 # Print the new string print(remove(string, i))", "e": 27765, "s": 27336, "text": null }, { "code": null, "e": 27779, "s": 27765, "text": "geeksORgeeks\n" }, { "code": null, "e": 27796, "s": 27779, "text": "kunchamaparna509" }, { "code": null, "e": 27819, "s": 27796, "text": "Python string-programs" }, { "code": null, "e": 27833, "s": 27819, "text": "python-string" }, { "code": null, "e": 27840, "s": 27833, "text": "Python" }, { "code": null, "e": 27856, "s": 27840, "text": "Python Programs" }, { "code": null, "e": 27954, "s": 27856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27972, "s": 27954, "text": "Python Dictionary" }, { "code": null, "e": 28007, "s": 27972, "text": "Read a file line by line in Python" }, { "code": null, "e": 28039, "s": 28007, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28061, "s": 28039, "text": "Enumerate() in Python" }, { "code": null, "e": 28103, "s": 28061, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28146, "s": 28103, "text": "Python program to convert a list to string" }, { "code": null, "e": 28168, "s": 28146, "text": "Defaultdict in Python" }, { "code": null, "e": 28207, "s": 28168, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28245, "s": 28207, "text": "Python | Convert a list to dictionary" } ]
Common Field Calculations using Python in ArcGIS | by Paul Bartsch | Towards Data Science
The ArcGIS field calculator can save a person time and allow for fairly quick data cleanup IF you can remember how to use it. I don’t know about you, but for me the layout of the field calculator, the separation of the formula field and the code block area and the minor changes from standard Python formatting are enough to send me straight to the Google search bar if I haven’t used it in a while. That’s why I started making notes for even the simplest of tasks. I go back to them often saving myself time and frustration. Maybe someday I’ll memorize these, but for now this works. Below you’ll find a list of some simple field calculations that I use often as a starting place. I’ll add to these as I think of them. Maybe you’ll find one useful. Change text to title case. — So simple and used frequently. !note1!.title() Replace one character for another. — Probably the most common reason I use the field calculator. !noteField!.replace("-","_") Concatenate fields together. — Very common when geocoding addresses. !Address! +" "+ !Street! +", "+ !City! +", "+ !State! +" "+ !Zip! Simple mathematic calculations across multiple fields. — You can use the field calculator to extract summary statistics from a list of fields. Chain commands together. In this example I start with a field called TextField with some messy data. Suppose I have Oak Trees listed as oak, Oak, Oak tree, and oak tree but I want to normalize them all to read simply Oak Tree. A few simple commands can be chained together to accomplish this. !TextField!.lower().replace("tree", " ").replace("oak", "Oak Tree") Using the Code Block. The Code Block portion of the Calculate Field tool in ArcGIS allows for the use of any Python function, you can even import modules and define your own functions. The format is not that complicated once you’ve used it a few times. Think of the Code Block area as a place to define functions which you can later call from the Expression box. In the following example I want to create an abbreviated code for each tree species by taking the first two letters of the genus and concatenating them together with the first two letters of the species. I can accomplish that quickly like this: Unit conversion using math. To convert from square footage to acres and round to two decimal places you could do something like this: You could accomplish the same result with a single line as below, but I personally prefer to use the Code Block to make things more repeatable and to allow for more complex functions in the future: round((!Shape_Area! / 43560),2) Another way to convert units. — As detailed here, it’s possible to use the ArcGIS Pro built in geometry unit conversions rather than doing your own calculations. Have a look at the esri link above to see all of the built in unit of measurement conversions. Note that the format of field names is slightly different when referring to geometry columns as compared to other fields: !shape.area@hectares! !shape.length@KILOMETERS! Using Logic — Here’s an overly simplified example using logic to classify a utility pipe as either a Main line or a Lateral line based on pipe diameter. Originally published at geopy.dev
[ { "code": null, "e": 697, "s": 171, "text": "The ArcGIS field calculator can save a person time and allow for fairly quick data cleanup IF you can remember how to use it. I don’t know about you, but for me the layout of the field calculator, the separation of the formula field and the code block area and the minor changes from standard Python formatting are enough to send me straight to the Google search bar if I haven’t used it in a while. That’s why I started making notes for even the simplest of tasks. I go back to them often saving myself time and frustration." }, { "code": null, "e": 756, "s": 697, "text": "Maybe someday I’ll memorize these, but for now this works." }, { "code": null, "e": 921, "s": 756, "text": "Below you’ll find a list of some simple field calculations that I use often as a starting place. I’ll add to these as I think of them. Maybe you’ll find one useful." }, { "code": null, "e": 981, "s": 921, "text": "Change text to title case. — So simple and used frequently." }, { "code": null, "e": 997, "s": 981, "text": "!note1!.title()" }, { "code": null, "e": 1094, "s": 997, "text": "Replace one character for another. — Probably the most common reason I use the field calculator." }, { "code": null, "e": 1123, "s": 1094, "text": "!noteField!.replace(\"-\",\"_\")" }, { "code": null, "e": 1192, "s": 1123, "text": "Concatenate fields together. — Very common when geocoding addresses." }, { "code": null, "e": 1258, "s": 1192, "text": "!Address! +\" \"+ !Street! +\", \"+ !City! +\", \"+ !State! +\" \"+ !Zip!" }, { "code": null, "e": 1401, "s": 1258, "text": "Simple mathematic calculations across multiple fields. — You can use the field calculator to extract summary statistics from a list of fields." }, { "code": null, "e": 1694, "s": 1401, "text": "Chain commands together. In this example I start with a field called TextField with some messy data. Suppose I have Oak Trees listed as oak, Oak, Oak tree, and oak tree but I want to normalize them all to read simply Oak Tree. A few simple commands can be chained together to accomplish this." }, { "code": null, "e": 1762, "s": 1694, "text": "!TextField!.lower().replace(\"tree\", \" \").replace(\"oak\", \"Oak Tree\")" }, { "code": null, "e": 2370, "s": 1762, "text": "Using the Code Block. The Code Block portion of the Calculate Field tool in ArcGIS allows for the use of any Python function, you can even import modules and define your own functions. The format is not that complicated once you’ve used it a few times. Think of the Code Block area as a place to define functions which you can later call from the Expression box. In the following example I want to create an abbreviated code for each tree species by taking the first two letters of the genus and concatenating them together with the first two letters of the species. I can accomplish that quickly like this:" }, { "code": null, "e": 2504, "s": 2370, "text": "Unit conversion using math. To convert from square footage to acres and round to two decimal places you could do something like this:" }, { "code": null, "e": 2702, "s": 2504, "text": "You could accomplish the same result with a single line as below, but I personally prefer to use the Code Block to make things more repeatable and to allow for more complex functions in the future:" }, { "code": null, "e": 2734, "s": 2702, "text": "round((!Shape_Area! / 43560),2)" }, { "code": null, "e": 3113, "s": 2734, "text": "Another way to convert units. — As detailed here, it’s possible to use the ArcGIS Pro built in geometry unit conversions rather than doing your own calculations. Have a look at the esri link above to see all of the built in unit of measurement conversions. Note that the format of field names is slightly different when referring to geometry columns as compared to other fields:" }, { "code": null, "e": 3135, "s": 3113, "text": "!shape.area@hectares!" }, { "code": null, "e": 3161, "s": 3135, "text": "!shape.length@KILOMETERS!" }, { "code": null, "e": 3314, "s": 3161, "text": "Using Logic — Here’s an overly simplified example using logic to classify a utility pipe as either a Main line or a Lateral line based on pipe diameter." } ]
Convert a sentence into its equivalent mobile numeric keypad sequence | Practice | GeeksforGeeks
Given a sentence in the form of a string in uppercase, convert it into its equivalent mobile numeric keypad sequence. Example 1: Input: S = "GFG" Output: 43334 Explanation: For 'G' press '4' one time. For 'F' press '3' three times. Example 2: Input: S = "HEY U" Output: 4433999088 Explanation: For 'H' press '4' two times. ​For 'E' press '3' two times. For 'Y' press '9' three times. For white space press '0' one time. For 'U' press '8' two times. Your Task: You dont need to read input or print anything. Complete the function printSequence() which takes a string as input parameter and returns its equivalent mobile numeric keypad sequence as a string. Expected Time Complexity: O(Length of String) Expected Auxiliary Space: O(Length of String) Constraints: 1 <= Length of String <= 105 Characters of string can be empty space or capital alphabets. 0 pratapshivendrasingh175 days ago C++ Most optimised Solution string printSequence(string S) { unordered_map <char,string> mapping; mapping['A']="2"; mapping['B']="22"; mapping['C']="222"; mapping['D']="3"; mapping['E']="33"; mapping['F']="333"; mapping['G']="4"; mapping['H']="44"; mapping['I']="444"; mapping['J']="5"; mapping['K']="55"; mapping['L']="555"; mapping['M']="6"; mapping['N']="66"; mapping['O']="666"; mapping['P']="7"; mapping['Q']="77"; mapping['R']="777"; mapping['S']="7777"; mapping['T']="8"; mapping['U']="88"; mapping['V']="888"; mapping['W']="9"; mapping['X']="99"; mapping['Y']="999"; mapping['Z']="9999"; mapping[' ']="0"; string ans; for(int i=0;i<S.length();i++) { ans=ans+mapping[S[i]]; } return ans; } 0 aahshis161 week ago time : 0.03s def printSequence(self,S): dic= {'A':2,'B':22,'C':222,'D':3,'E':33,'F':333,'G':4,'H':44,'I':444, 'J':5,'K':55,'L':555,'M':6,'N':66,'O':666,'P':7,'Q':77, 'R':777,'S':7777,'T':8,'U':88,'V':888,'W':9,'Y':999,'Z':9999,'X':99,' ':0} s='' for i in S: s+=str(dic[i]) return s 0 18pa1a04772 weeks ago without hard coding class Solution: def printSequence(self,S): d={} res="" li=["","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"] for l in range(len(li)): for s in range(len(li[l])): d[li[l][s]]=[l,s+1] for l in S: if l==" ": res=res+"0" else: res=res+str(d[l][0])*d[l][1] return res +1 lindan1233 weeks ago string printSequence(string S){ unordered_map<char,string> mp; mp['A'] = "2"; mp['B'] = "22"; mp['C'] = "222"; mp['D'] = "3"; mp['E'] = "33"; mp['F'] = "333"; mp['G'] = "4"; mp['H'] = "44"; mp['I'] = "444"; mp['J'] = "5"; mp['K'] = "55"; mp['L'] = "555"; mp['M'] = "6"; mp['N'] = "66"; mp['O'] = "666"; mp['P'] = "7"; mp['Q'] = "77"; mp['R'] = "777"; mp['S'] = "7777"; mp['T'] = "8"; mp['U'] = "88"; mp['V'] = "888"; mp['W'] = "9"; mp['X'] = "99"; mp['Y'] = "999"; mp['Z'] = "9999"; mp[' '] = "0"; string ans=""; for(int i=0;i<S.length();i++) { ans = ans + mp[S[i]]; } return ans;} Time Taken : 0.03sec Cpp +1 veekshithc1 month ago javascript solution function printSequence(str){ let v=["2","22","222","3","33","333","4","44","444","5","55","555","6","66","666","7","77","777","7777","8","88","888","9","99","999","9999"] let arr = [] var x for(let i=0;i<str.length; i++){ arr.push(v[(str.charCodeAt(i))-65]) } return arr } +1 sudarshanp49121 month ago EASY SOLUTION: string printSequence(string S) { vector<string> v={"2","22","222","3","33","333","4","44","444","5","55","555","6","66","666","7","77","777","7777","8","88","888","9","99","999","9999"}; string ans; for(int i=0;i<S.length();i++) { if(S[i]==' ') ans+="0"; else ans+=v[S[i]-'A']; } return ans; } +1 madhukartemba1 month ago JAVA SOLUTION: class Solution { String printSequence(String S) { HashMap<Character, String> map = new HashMap<>(); map.put('A', "2"); map.put('B', "22"); map.put('C', "222"); map.put('D', "3"); map.put('E', "33"); map.put('F', "333"); map.put('G', "4"); map.put('H', "44"); map.put('I', "444"); map.put('J', "5"); map.put('K', "55"); map.put('L', "555"); map.put('M', "6"); map.put('N', "66"); map.put('O', "666"); map.put('P', "7"); map.put('Q', "77"); map.put('R', "777"); map.put('S', "7777"); map.put('T', "8"); map.put('U', "88"); map.put('V', "888"); map.put('W', "9"); map.put('X', "99"); map.put('Y', "999"); map.put('Z', "9999"); map.put(' ', "0"); StringBuilder ans = new StringBuilder(); for(char ch : S.toCharArray()) { ans.append(map.get(ch)); } return ans.toString(); } } 0 gauravsingh93562 months ago unordered_map<char, string>mp; char t='A'; for(int i=2;i<=6;i++) { mp[t]=to_string(i); mp[t+1]=to_string(i)+to_string(i); mp[t+2]=to_string(i)+to_string(i)+to_string(i); t+=3; } for(int i=7;i<=9;i++) { if(i==8) continue; mp[t]=to_string(i); mp[t+1]=to_string(i)+to_string(i); mp[t+2]=to_string(i)+to_string(i)+to_string(i); mp[t+3]=to_string(i)+to_string(i)+to_string(i)+to_string(i); t+=7; } mp['T']=to_string(8); mp['U']=to_string(8)+to_string(8); mp['V']=to_string(8)+to_string(8)+to_string(8); mp[' ']="0"; string ans=""; for(int i=0;i<S.length();i++) { ans+=mp[S[i]]; } return ans; 0 patelneer4032 months ago unordered_map<char,string> map; int i; string a; string b; map['A']="2"; map['B']="22"; map['C']="222"; map['D']="3"; map['E']="33"; map['F']="333"; map['G']="4"; map['H']="44"; map['I']="444"; map['J']="5"; map['K']="55"; map['L']="555"; map['M']="6"; map['N']="66"; map['O']="666"; map['P']="7"; map['Q']="77"; map['R']="777"; map['S']="7777"; map['T']="8"; map['U']="88"; map['V']="888"; map['W']="9"; map['X']="99"; map['Y']="999"; map['Z']="9999"; map[' ']="0"; for(i=0;S[i]!='\0';i++) { b=map[S[i]]; a.append(b); } return a; 0 vikasnayakmmmut2 months ago string printSequence(string S){ int n=S.length(); unordered_map<char,string>p; string s=""; p['A']="2"; p['B']="22"; p['C']="222"; p['D']="3"; p['E']="33"; p['F']="333"; p['G']="4"; p['H']="44"; p['I']="444"; p['J']="5"; p['K']="55"; p['L']="555"; p['M']="6"; p['N']="66"; p['O']="666"; p['P']="7"; p['Q']="77"; p['R']="777"; p['S']="7777"; p['T']="8"; p['U']="88"; p['V']="888"; p['W']="9"; p['X']="99"; p['Y']="999"; p['Z']="9999"; p[' ']="0"; for(int i=0;i<n;i++) { s=s+p[S[i]]; } 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": 344, "s": 226, "text": "Given a sentence in the form of a string in uppercase, convert it into its equivalent mobile numeric keypad sequence." }, { "code": null, "e": 357, "s": 346, "text": "Example 1:" }, { "code": null, "e": 461, "s": 357, "text": "Input:\nS = \"GFG\"\nOutput: 43334\nExplanation: For 'G' press '4' one time.\nFor 'F' press '3' three times.\n" }, { "code": null, "e": 472, "s": 461, "text": "Example 2:" }, { "code": null, "e": 683, "s": 472, "text": "Input:\nS = \"HEY U\"\nOutput: 4433999088\nExplanation: For 'H' press '4' two times.\n​For 'E' press '3' two times. For 'Y' press '9' \nthree times. For white space press '0' one time.\nFor 'U' press '8' two times.\n" }, { "code": null, "e": 896, "s": 685, "text": "Your Task: \nYou dont need to read input or print anything. Complete the function printSequence() which takes a string as input parameter and returns its equivalent mobile numeric keypad sequence as a string.\n " }, { "code": null, "e": 990, "s": 896, "text": "Expected Time Complexity: O(Length of String)\nExpected Auxiliary Space: O(Length of String)\n " }, { "code": null, "e": 1003, "s": 990, "text": "Constraints:" }, { "code": null, "e": 1094, "s": 1003, "text": "1 <= Length of String <= 105\nCharacters of string can be empty space or capital alphabets." }, { "code": null, "e": 1096, "s": 1094, "text": "0" }, { "code": null, "e": 1129, "s": 1096, "text": "pratapshivendrasingh175 days ago" }, { "code": null, "e": 1976, "s": 1129, "text": "C++ Most optimised Solution\nstring printSequence(string S)\n{\n unordered_map <char,string> mapping;\n mapping['A']=\"2\";\n mapping['B']=\"22\";\n mapping['C']=\"222\";\n mapping['D']=\"3\";\n mapping['E']=\"33\";\n mapping['F']=\"333\";\n mapping['G']=\"4\";\n mapping['H']=\"44\";\n mapping['I']=\"444\";\n mapping['J']=\"5\";\n mapping['K']=\"55\";\n mapping['L']=\"555\";\n mapping['M']=\"6\";\n mapping['N']=\"66\";\n mapping['O']=\"666\";\n mapping['P']=\"7\";\n mapping['Q']=\"77\";\n mapping['R']=\"777\";\n mapping['S']=\"7777\";\n mapping['T']=\"8\";\n mapping['U']=\"88\";\n mapping['V']=\"888\";\n mapping['W']=\"9\";\n mapping['X']=\"99\";\n mapping['Y']=\"999\";\n mapping['Z']=\"9999\";\n mapping[' ']=\"0\";\n \n string ans;\n \n for(int i=0;i<S.length();i++)\n {\n ans=ans+mapping[S[i]];\n }\n return ans;\n}" }, { "code": null, "e": 1978, "s": 1976, "text": "0" }, { "code": null, "e": 1998, "s": 1978, "text": "aahshis161 week ago" }, { "code": null, "e": 2011, "s": 1998, "text": "time : 0.03s" }, { "code": null, "e": 2340, "s": 2011, "text": "def printSequence(self,S): dic= {'A':2,'B':22,'C':222,'D':3,'E':33,'F':333,'G':4,'H':44,'I':444, 'J':5,'K':55,'L':555,'M':6,'N':66,'O':666,'P':7,'Q':77, 'R':777,'S':7777,'T':8,'U':88,'V':888,'W':9,'Y':999,'Z':9999,'X':99,' ':0} s='' for i in S: s+=str(dic[i]) return s" }, { "code": null, "e": 2342, "s": 2340, "text": "0" }, { "code": null, "e": 2364, "s": 2342, "text": "18pa1a04772 weeks ago" }, { "code": null, "e": 2790, "s": 2364, "text": "without hard coding\nclass Solution:\n def printSequence(self,S):\n d={}\n res=\"\"\n li=[\"\",\"\",\"ABC\",\"DEF\",\"GHI\",\"JKL\",\"MNO\",\"PQRS\",\"TUV\",\"WXYZ\"]\n for l in range(len(li)):\n for s in range(len(li[l])):\n d[li[l][s]]=[l,s+1]\n for l in S:\n if l==\" \":\n res=res+\"0\"\n else:\n res=res+str(d[l][0])*d[l][1]\n return res" }, { "code": null, "e": 2793, "s": 2790, "text": "+1" }, { "code": null, "e": 2814, "s": 2793, "text": "lindan1233 weeks ago" }, { "code": null, "e": 3471, "s": 2814, "text": "string printSequence(string S){ unordered_map<char,string> mp; mp['A'] = \"2\"; mp['B'] = \"22\"; mp['C'] = \"222\"; mp['D'] = \"3\"; mp['E'] = \"33\"; mp['F'] = \"333\"; mp['G'] = \"4\"; mp['H'] = \"44\"; mp['I'] = \"444\"; mp['J'] = \"5\"; mp['K'] = \"55\"; mp['L'] = \"555\"; mp['M'] = \"6\"; mp['N'] = \"66\"; mp['O'] = \"666\"; mp['P'] = \"7\"; mp['Q'] = \"77\"; mp['R'] = \"777\"; mp['S'] = \"7777\"; mp['T'] = \"8\"; mp['U'] = \"88\"; mp['V'] = \"888\"; mp['W'] = \"9\"; mp['X'] = \"99\"; mp['Y'] = \"999\"; mp['Z'] = \"9999\"; mp[' '] = \"0\"; string ans=\"\"; for(int i=0;i<S.length();i++) { ans = ans + mp[S[i]]; } return ans;}" }, { "code": null, "e": 3494, "s": 3473, "text": "Time Taken : 0.03sec" }, { "code": null, "e": 3498, "s": 3494, "text": "Cpp" }, { "code": null, "e": 3503, "s": 3500, "text": "+1" }, { "code": null, "e": 3525, "s": 3503, "text": "veekshithc1 month ago" }, { "code": null, "e": 3545, "s": 3525, "text": "javascript solution" }, { "code": null, "e": 3853, "s": 3545, "text": "\nfunction printSequence(str){\n let v=[\"2\",\"22\",\"222\",\"3\",\"33\",\"333\",\"4\",\"44\",\"444\",\"5\",\"55\",\"555\",\"6\",\"66\",\"666\",\"7\",\"77\",\"777\",\"7777\",\"8\",\"88\",\"888\",\"9\",\"99\",\"999\",\"9999\"]\n let arr = [] \n var x \n for(let i=0;i<str.length; i++){\n arr.push(v[(str.charCodeAt(i))-65])\n \n }\n return arr\n}" }, { "code": null, "e": 3856, "s": 3853, "text": "+1" }, { "code": null, "e": 3882, "s": 3856, "text": "sudarshanp49121 month ago" }, { "code": null, "e": 3897, "s": 3882, "text": "EASY SOLUTION:" }, { "code": null, "e": 4232, "s": 3897, "text": "string printSequence(string S)\n{\n vector<string> v={\"2\",\"22\",\"222\",\"3\",\"33\",\"333\",\"4\",\"44\",\"444\",\"5\",\"55\",\"555\",\"6\",\"66\",\"666\",\"7\",\"77\",\"777\",\"7777\",\"8\",\"88\",\"888\",\"9\",\"99\",\"999\",\"9999\"};\n\n string ans;\n for(int i=0;i<S.length();i++)\n {\n if(S[i]==' ') ans+=\"0\";\n else ans+=v[S[i]-'A'];\n }\n return ans;\n}" }, { "code": null, "e": 4235, "s": 4232, "text": "+1" }, { "code": null, "e": 4260, "s": 4235, "text": "madhukartemba1 month ago" }, { "code": null, "e": 4275, "s": 4260, "text": "JAVA SOLUTION:" }, { "code": null, "e": 5383, "s": 4275, "text": "class Solution \n{ \n String printSequence(String S) \n { \n HashMap<Character, String> map = new HashMap<>();\n \n map.put('A', \"2\");\n map.put('B', \"22\");\n map.put('C', \"222\");\n map.put('D', \"3\");\n map.put('E', \"33\");\n map.put('F', \"333\");\n map.put('G', \"4\");\n map.put('H', \"44\");\n map.put('I', \"444\");\n map.put('J', \"5\");\n map.put('K', \"55\");\n map.put('L', \"555\");\n map.put('M', \"6\");\n map.put('N', \"66\");\n map.put('O', \"666\");\n map.put('P', \"7\");\n map.put('Q', \"77\");\n map.put('R', \"777\");\n map.put('S', \"7777\");\n map.put('T', \"8\");\n map.put('U', \"88\");\n map.put('V', \"888\");\n map.put('W', \"9\");\n map.put('X', \"99\");\n map.put('Y', \"999\");\n map.put('Z', \"9999\");\n map.put(' ', \"0\");\n \n StringBuilder ans = new StringBuilder();\n \n for(char ch : S.toCharArray())\n {\n ans.append(map.get(ch));\n }\n \n return ans.toString();\n \n }\n}" }, { "code": null, "e": 5385, "s": 5383, "text": "0" }, { "code": null, "e": 5413, "s": 5385, "text": "gauravsingh93562 months ago" }, { "code": null, "e": 6161, "s": 5413, "text": "\n\nunordered_map<char, string>mp;\n char t='A';\n \n for(int i=2;i<=6;i++)\n {\n mp[t]=to_string(i);\n mp[t+1]=to_string(i)+to_string(i);\n mp[t+2]=to_string(i)+to_string(i)+to_string(i);\n t+=3;\n }\n \n for(int i=7;i<=9;i++)\n {\n if(i==8)\n continue;\n mp[t]=to_string(i);\n mp[t+1]=to_string(i)+to_string(i);\n mp[t+2]=to_string(i)+to_string(i)+to_string(i);\n mp[t+3]=to_string(i)+to_string(i)+to_string(i)+to_string(i);\n t+=7;\n }\n \n mp['T']=to_string(8);\n mp['U']=to_string(8)+to_string(8);\n mp['V']=to_string(8)+to_string(8)+to_string(8);\n \n \n mp[' ']=\"0\";\n \n string ans=\"\";\n for(int i=0;i<S.length();i++)\n {\n ans+=mp[S[i]];\n }\n return ans;" }, { "code": null, "e": 6163, "s": 6161, "text": "0" }, { "code": null, "e": 6188, "s": 6163, "text": "patelneer4032 months ago" }, { "code": null, "e": 6810, "s": 6188, "text": "unordered_map<char,string> map; int i; string a; string b; map['A']=\"2\"; map['B']=\"22\"; map['C']=\"222\"; map['D']=\"3\"; map['E']=\"33\"; map['F']=\"333\"; map['G']=\"4\"; map['H']=\"44\"; map['I']=\"444\"; map['J']=\"5\"; map['K']=\"55\"; map['L']=\"555\"; map['M']=\"6\"; map['N']=\"66\"; map['O']=\"666\"; map['P']=\"7\"; map['Q']=\"77\"; map['R']=\"777\"; map['S']=\"7777\"; map['T']=\"8\"; map['U']=\"88\"; map['V']=\"888\"; map['W']=\"9\"; map['X']=\"99\"; map['Y']=\"999\"; map['Z']=\"9999\"; map[' ']=\"0\"; for(i=0;S[i]!='\\0';i++) { b=map[S[i]]; a.append(b); } return a;" }, { "code": null, "e": 6812, "s": 6810, "text": "0" }, { "code": null, "e": 6840, "s": 6812, "text": "vikasnayakmmmut2 months ago" }, { "code": null, "e": 7900, "s": 6840, "text": "string printSequence(string S){ int n=S.length(); unordered_map<char,string>p; string s=\"\"; p['A']=\"2\"; p['B']=\"22\"; p['C']=\"222\"; p['D']=\"3\"; p['E']=\"33\"; p['F']=\"333\"; p['G']=\"4\"; p['H']=\"44\"; p['I']=\"444\"; p['J']=\"5\"; p['K']=\"55\"; p['L']=\"555\"; p['M']=\"6\"; p['N']=\"66\"; p['O']=\"666\"; p['P']=\"7\"; p['Q']=\"77\"; p['R']=\"777\"; p['S']=\"7777\"; p['T']=\"8\"; p['U']=\"88\"; p['V']=\"888\"; p['W']=\"9\"; p['X']=\"99\"; p['Y']=\"999\"; p['Z']=\"9999\"; p[' ']=\"0\"; for(int i=0;i<n;i++) { s=s+p[S[i]]; } return s;}" }, { "code": null, "e": 8046, "s": 7900, "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": 8082, "s": 8046, "text": " Login to access your submissions. " }, { "code": null, "e": 8092, "s": 8082, "text": "\nProblem\n" }, { "code": null, "e": 8102, "s": 8092, "text": "\nContest\n" }, { "code": null, "e": 8165, "s": 8102, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8313, "s": 8165, "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": 8521, "s": 8313, "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": 8627, "s": 8521, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Intersection() function Python - GeeksforGeeks
05 Oct, 2021 Python intersection() function return a new set with an element that is common to all set The intersection of two given sets is the largest set which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Input: Let set A = {2, 4, 5, 6} and set B = {4, 6, 7, 8} Output: {4,6} Explanation: Taking the common elements in both the sets, we get {4,6} as the intersection of both the sets. set1.intersection(set2, set3, set4....) In parameters, any number of sets can be given The intersection() function returns a set, which has the intersection of all sets(set1, set2, set3...) with set1. It returns a copy of set1 only if no parameter is passed. Python3 # Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {4, 6, 8} # union of two setsprint("set1 intersection set2 : ", set1.intersection(set2)) # union of three setsprint("set1 intersection set2 intersection set3 :", set1.intersection(set2, set3)) Output: set1 intersection set2 : {4, 6} set1 intersection set2 intersection set3 : {4, 6} we can also get intersection using & operator. Python3 # Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {1, 0, 12} print(set1 & set2)print(set1 & set3) print(set1 & set2 & set3) Output: {4, 6} set() set() symmetric_difference() is a opposite to the set.intersection() methods. Python3 # Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {1, 0, 12} print(set1.symmetric_difference(set2))print(set1.symmetric_difference(set3))print(set2.symmetric_difference(set3)) Output: {2, 5, 7, 8} {0, 1, 2, 4, 5, 6, 12} {0, 1, 4, 6, 7, 8, 12} Python3 set1 = {}set2 = {} # union of two setsprint("set1 intersection set2 : ", set(set1).intersection(set(set2))) Output: set1 intersection set2 : set() kumar_satyam Python-Built-in-functions python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 24916, "s": 24888, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25006, "s": 24916, "text": "Python intersection() function return a new set with an element that is common to all set" }, { "code": null, "e": 25244, "s": 25006, "text": "The intersection of two given sets is the largest set which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. " }, { "code": null, "e": 25276, "s": 25244, "text": "Input: Let set A = {2, 4, 5, 6}" }, { "code": null, "e": 25308, "s": 25276, "text": " and set B = {4, 6, 7, 8}" }, { "code": null, "e": 25323, "s": 25308, "text": "Output: {4,6} " }, { "code": null, "e": 25432, "s": 25323, "text": "Explanation: Taking the common elements in both the sets, we get {4,6} as the intersection of both the sets." }, { "code": null, "e": 25519, "s": 25432, "text": "set1.intersection(set2, set3, set4....) In parameters, any number of sets can be given" }, { "code": null, "e": 25692, "s": 25519, "text": "The intersection() function returns a set, which has the intersection of all sets(set1, set2, set3...) with set1. It returns a copy of set1 only if no parameter is passed. " }, { "code": null, "e": 25700, "s": 25692, "text": "Python3" }, { "code": "# Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {4, 6, 8} # union of two setsprint(\"set1 intersection set2 : \", set1.intersection(set2)) # union of three setsprint(\"set1 intersection set2 intersection set3 :\", set1.intersection(set2, set3))", "e": 25993, "s": 25700, "text": null }, { "code": null, "e": 26002, "s": 25993, "text": "Output: " }, { "code": null, "e": 26085, "s": 26002, "text": "set1 intersection set2 : {4, 6}\nset1 intersection set2 intersection set3 : {4, 6}" }, { "code": null, "e": 26132, "s": 26085, "text": "we can also get intersection using & operator." }, { "code": null, "e": 26140, "s": 26132, "text": "Python3" }, { "code": "# Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {1, 0, 12} print(set1 & set2)print(set1 & set3) print(set1 & set2 & set3)", "e": 26304, "s": 26140, "text": null }, { "code": null, "e": 26312, "s": 26304, "text": "Output:" }, { "code": null, "e": 26331, "s": 26312, "text": "{4, 6}\nset()\nset()" }, { "code": null, "e": 26403, "s": 26331, "text": "symmetric_difference() is a opposite to the set.intersection() methods." }, { "code": null, "e": 26411, "s": 26403, "text": "Python3" }, { "code": "# Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {1, 0, 12} print(set1.symmetric_difference(set2))print(set1.symmetric_difference(set3))print(set2.symmetric_difference(set3))", "e": 26627, "s": 26411, "text": null }, { "code": null, "e": 26635, "s": 26627, "text": "Output:" }, { "code": null, "e": 26694, "s": 26635, "text": "{2, 5, 7, 8}\n{0, 1, 2, 4, 5, 6, 12}\n{0, 1, 4, 6, 7, 8, 12}" }, { "code": null, "e": 26702, "s": 26694, "text": "Python3" }, { "code": "set1 = {}set2 = {} # union of two setsprint(\"set1 intersection set2 : \", set(set1).intersection(set(set2)))", "e": 26815, "s": 26702, "text": null }, { "code": null, "e": 26823, "s": 26815, "text": "Output:" }, { "code": null, "e": 26855, "s": 26823, "text": "set1 intersection set2 : set()" }, { "code": null, "e": 26868, "s": 26855, "text": "kumar_satyam" }, { "code": null, "e": 26894, "s": 26868, "text": "Python-Built-in-functions" }, { "code": null, "e": 26905, "s": 26894, "text": "python-set" }, { "code": null, "e": 26912, "s": 26905, "text": "Python" }, { "code": null, "e": 26923, "s": 26912, "text": "python-set" }, { "code": null, "e": 27021, "s": 26923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27049, "s": 27021, "text": "Read JSON file using Python" }, { "code": null, "e": 27099, "s": 27049, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27121, "s": 27099, "text": "Python map() function" }, { "code": null, "e": 27165, "s": 27121, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27183, "s": 27165, "text": "Python Dictionary" }, { "code": null, "e": 27206, "s": 27183, "text": "Taking input in Python" }, { "code": null, "e": 27241, "s": 27206, "text": "Read a file line by line in Python" }, { "code": null, "e": 27273, "s": 27241, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27295, "s": 27273, "text": "Enumerate() in Python" } ]
Python Program to print unique values from a list
Given a list, our task is to print all the unique numbers. Input:A = [1, 2, 3, 4, 2, 1, 9] Unique list is [1, 2, 3, 4, 9] Step 1: Create user input list. Step 2: Create an empty list. Step 3: Traverse all elements in the list. Step 4: Check the unique element is present or not. Step 5: Append unique element one by one into that empty list. Step 6: Display that list. # Python program to print unique values from a list def unique(A): # intilize a null list uniquevalues = [] # traversing the list for i in A: # check unique valueis present or not if i not in uniquevalues: uniquevalues.append(i) # print (A) for i in uniquevalues: print (i), # Driver code A=list() n=int(input("Enter the size of the List ::")) print("Enter the Element of List ::") for i in range(int(n)): k=int(input("")) A.append(k) print("The unique values from the List is ::>") unique(A) Enter the size of the List :: 6 Enter the Element of List :: 1 2 5 2 1 7 The unique values from the List is ::> 1 2 5 7
[ { "code": null, "e": 1121, "s": 1062, "text": "Given a list, our task is to print all the unique numbers." }, { "code": null, "e": 1184, "s": 1121, "text": "Input:A = [1, 2, 3, 4, 2, 1, 9]\nUnique list is [1, 2, 3, 4, 9]" }, { "code": null, "e": 1431, "s": 1184, "text": "Step 1: Create user input list.\nStep 2: Create an empty list.\nStep 3: Traverse all elements in the list.\nStep 4: Check the unique element is present or not.\nStep 5: Append unique element one by one into that empty list.\nStep 6: Display that list." }, { "code": null, "e": 2012, "s": 1431, "text": "# Python program to print unique values from a list\n\ndef unique(A):\n # intilize a null list\n uniquevalues = []\n\n # traversing the list\n for i in A:\n # check unique valueis present or not\n if i not in uniquevalues:\n uniquevalues.append(i)\n # print (A)\n for i in uniquevalues:\n print (i),\n\n # Driver code\n A=list()\n n=int(input(\"Enter the size of the List ::\"))\n print(\"Enter the Element of List ::\")\n for i in range(int(n)):\n k=int(input(\"\"))\n A.append(k)\n\nprint(\"The unique values from the List is ::>\")\nunique(A)" }, { "code": null, "e": 2132, "s": 2012, "text": "Enter the size of the List :: 6\nEnter the Element of List ::\n1\n2\n5\n2\n1\n7\nThe unique values from the List is ::>\n1\n2\n5\n7" } ]
C Program for compound interest?
Here we will see how to get the compound interest by writing one C program. The logic is very easy. Here we need some parameters − P − Principle amount R − Rate of interest T − Time span The compound interest formula is like below #include<stdio.h> #include<math.h> float compoundInterest(float P, float T, float R) { return P*(pow(1+(R/100), T)); } int main() { float p, t, r; printf("Enter Princple amount, rate of interest, and time: "); scanf("%f%f%f", &p, &r, &t); printf("Interest value: %f", compoundInterest(p, t, r)); } Enter Princple amount, rate of interest, and time: 5000 7.5 3 Interest value: 6211.485352
[ { "code": null, "e": 1193, "s": 1062, "text": "Here we will see how to get the compound interest by writing one C program. The logic is very easy. Here we need some parameters −" }, { "code": null, "e": 1214, "s": 1193, "text": "P − Principle amount" }, { "code": null, "e": 1235, "s": 1214, "text": "R − Rate of interest" }, { "code": null, "e": 1249, "s": 1235, "text": "T − Time span" }, { "code": null, "e": 1293, "s": 1249, "text": "The compound interest formula is like below" }, { "code": null, "e": 1606, "s": 1293, "text": "#include<stdio.h>\n#include<math.h>\nfloat compoundInterest(float P, float T, float R) {\n return P*(pow(1+(R/100), T));\n}\nint main() {\n float p, t, r;\n printf(\"Enter Princple amount, rate of interest, and time: \");\n scanf(\"%f%f%f\", &p, &r, &t);\n printf(\"Interest value: %f\", compoundInterest(p, t, r));\n}" }, { "code": null, "e": 1696, "s": 1606, "text": "Enter Princple amount, rate of interest, and time: 5000 7.5 3\nInterest value: 6211.485352" } ]
Difference between List VS Set VS Tuple in Python - GeeksforGeeks
08 Jun, 2021 List: Lists are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. The main characteristics of lists are – The list is a datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. List are mutable .i.e it can be converted into another data type and can store any data element in it. List can store any type of element. Example: Python3 # Python3 program to demonstrate # List # Creating a ListList = []print("Blank List: ")print(List) # Creating a List of numbersList = [10, 20, 14]print("\nList of numbers: ")print(List) # Creating a List of strings and accessing# using indexList = ["Geeks", "For", "Geeks"]print("\nList Items: ")print(List[0]) print(List[2]) Output: Blank List: [] List of numbers: [10, 20, 14] List Items: Geeks Geeks Tuple: Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. The main characteristics of tuples are – Tuple is an immutable sequence in python. It cannot be changed or replaced since it is immutable. It is defined under parenthesis(). Tuples can store any type of element. Example: Python3 # Creating an empty TupleTuple1 = ()print("Initial empty Tuple: ")print (Tuple1) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print("\nTuple using List: ")print(tuple(list1)) #Creating a Tuple #with the use of built-in functionTuple1 = tuple('Geeks')print("\nTuple with the use of function: ")print(Tuple1) Output: Initial empty Tuple: () Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: ('G', 'e', 'e', 'k', 's') Set: In Python, Set is an unordered collection of data type that is iterable, mutable, and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. The main characteristics of set are – Sets are an unordered collection of elements or unintended collection of items In python. Here the order in which the elements are added into the set is not fixed, it can change frequently. It is defined under curly braces{} Sets are mutable, however, only immutable objects can be stored in it. Example: Python3 # Python3 program to demonstrate # Set in Python # Creating a Setset1 = set()print("Initial blank Set: ")print(set1) # Creating a Set with# the use of Constructor# (Using object to Store String)String = 'GeeksForGeeks'set1 = set(String)print("\nSet with the use of an Object: " )print(set1) # Creating a Set with# the use of a Listset1 = set(["Geeks", "For", "Geeks"])print("\nSet with the use of List: ")print(set1) Output: Initial blank Set: set() Set with the use of an Object: {'G', 's', 'e', 'o', 'r', 'F', 'k'} Set with the use of List: {'Geeks', 'For'} ritikchanna sweetyty python-list python-set python-tuple Difference Between Python python-list python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference between Process and Thread Difference Between Method Overloading and Method Overriding in Java Stack vs Heap Memory Allocation Differences between JDK, JRE and JVM Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Taking input in Python
[ { "code": null, "e": 24359, "s": 24331, "text": "\n08 Jun, 2021" }, { "code": null, "e": 24601, "s": 24359, "text": "List: Lists are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. The main characteristics of lists are – " }, { "code": null, "e": 24734, "s": 24601, "text": "The list is a datatype available in Python which can be written as a list of comma-separated values (items) between square brackets." }, { "code": null, "e": 24837, "s": 24734, "text": "List are mutable .i.e it can be converted into another data type and can store any data element in it." }, { "code": null, "e": 24873, "s": 24837, "text": "List can store any type of element." }, { "code": null, "e": 24882, "s": 24873, "text": "Example:" }, { "code": null, "e": 24890, "s": 24882, "text": "Python3" }, { "code": "# Python3 program to demonstrate # List # Creating a ListList = []print(\"Blank List: \")print(List) # Creating a List of numbersList = [10, 20, 14]print(\"\\nList of numbers: \")print(List) # Creating a List of strings and accessing# using indexList = [\"Geeks\", \"For\", \"Geeks\"]print(\"\\nList Items: \")print(List[0]) print(List[2])", "e": 25223, "s": 24890, "text": null }, { "code": null, "e": 25231, "s": 25223, "text": "Output:" }, { "code": null, "e": 25305, "s": 25231, "text": "Blank List: \n[]\n\nList of numbers: \n[10, 20, 14]\n\nList Items: \nGeeks\nGeeks" }, { "code": null, "e": 25682, "s": 25305, "text": "Tuple: Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. The main characteristics of tuples are – " }, { "code": null, "e": 25724, "s": 25682, "text": "Tuple is an immutable sequence in python." }, { "code": null, "e": 25780, "s": 25724, "text": "It cannot be changed or replaced since it is immutable." }, { "code": null, "e": 25815, "s": 25780, "text": "It is defined under parenthesis()." }, { "code": null, "e": 25853, "s": 25815, "text": "Tuples can store any type of element." }, { "code": null, "e": 25862, "s": 25853, "text": "Example:" }, { "code": null, "e": 25870, "s": 25862, "text": "Python3" }, { "code": "# Creating an empty TupleTuple1 = ()print(\"Initial empty Tuple: \")print (Tuple1) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print(\"\\nTuple using List: \")print(tuple(list1)) #Creating a Tuple #with the use of built-in functionTuple1 = tuple('Geeks')print(\"\\nTuple with the use of function: \")print(Tuple1)", "e": 26199, "s": 25870, "text": null }, { "code": null, "e": 26207, "s": 26199, "text": "Output:" }, { "code": null, "e": 26328, "s": 26207, "text": "Initial empty Tuple: \n()\n\nTuple using List: \n(1, 2, 4, 5, 6)\n\nTuple with the use of function: \n('G', 'e', 'e', 'k', 's')" }, { "code": null, "e": 26648, "s": 26328, "text": "Set: In Python, Set is an unordered collection of data type that is iterable, mutable, and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. The main characteristics of set are –" }, { "code": null, "e": 26738, "s": 26648, "text": "Sets are an unordered collection of elements or unintended collection of items In python." }, { "code": null, "e": 26838, "s": 26738, "text": "Here the order in which the elements are added into the set is not fixed, it can change frequently." }, { "code": null, "e": 26873, "s": 26838, "text": "It is defined under curly braces{}" }, { "code": null, "e": 26944, "s": 26873, "text": "Sets are mutable, however, only immutable objects can be stored in it." }, { "code": null, "e": 26953, "s": 26944, "text": "Example:" }, { "code": null, "e": 26961, "s": 26953, "text": "Python3" }, { "code": "# Python3 program to demonstrate # Set in Python # Creating a Setset1 = set()print(\"Initial blank Set: \")print(set1) # Creating a Set with# the use of Constructor# (Using object to Store String)String = 'GeeksForGeeks'set1 = set(String)print(\"\\nSet with the use of an Object: \" )print(set1) # Creating a Set with# the use of a Listset1 = set([\"Geeks\", \"For\", \"Geeks\"])print(\"\\nSet with the use of List: \")print(set1)", "e": 27384, "s": 26961, "text": null }, { "code": null, "e": 27392, "s": 27384, "text": "Output:" }, { "code": null, "e": 27532, "s": 27392, "text": "Initial blank Set: \nset()\n\nSet with the use of an Object: \n{'G', 's', 'e', 'o', 'r', 'F', 'k'}\n\nSet with the use of List: \n{'Geeks', 'For'}" }, { "code": null, "e": 27544, "s": 27532, "text": "ritikchanna" }, { "code": null, "e": 27553, "s": 27544, "text": "sweetyty" }, { "code": null, "e": 27565, "s": 27553, "text": "python-list" }, { "code": null, "e": 27576, "s": 27565, "text": "python-set" }, { "code": null, "e": 27589, "s": 27576, "text": "python-tuple" }, { "code": null, "e": 27608, "s": 27589, "text": "Difference Between" }, { "code": null, "e": 27615, "s": 27608, "text": "Python" }, { "code": null, "e": 27627, "s": 27615, "text": "python-list" }, { "code": null, "e": 27638, "s": 27627, "text": "python-set" }, { "code": null, "e": 27736, "s": 27638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27797, "s": 27736, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27835, "s": 27797, "text": "Difference between Process and Thread" }, { "code": null, "e": 27903, "s": 27835, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27935, "s": 27903, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 27972, "s": 27935, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 28000, "s": 27972, "text": "Read JSON file using Python" }, { "code": null, "e": 28050, "s": 28000, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28072, "s": 28050, "text": "Python map() function" }, { "code": null, "e": 28116, "s": 28072, "text": "How to get column names in Pandas dataframe" } ]
Extracting Keys and Values from Hash in Perl
You can get a list of all of the keys from a hash in Perl by using keys function, which has the following syntax − keys %HASH This function returns an array of all the keys of the named hash. Following is the example − Live Demo #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @names = keys %data; print "$names[0]\n"; print "$names[1]\n"; print "$names[2]\n"; This will produce the following result − Lisa John Paul Kumar Similarly, you can use values function to get a list of all the values. This function has the following syntax − values %HASH This function returns a normal array consisting of all the values of the named hash. Following is the example − Live Demo #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @ages = values %data; print "$ages[0]\n"; print "$ages[1]\n"; print "$ages[2]\n"; This will produce the following result − 30 45 40
[ { "code": null, "e": 1177, "s": 1062, "text": "You can get a list of all of the keys from a hash in Perl by using keys function, which has the following syntax −" }, { "code": null, "e": 1188, "s": 1177, "text": "keys %HASH" }, { "code": null, "e": 1281, "s": 1188, "text": "This function returns an array of all the keys of the named hash. Following is the example −" }, { "code": null, "e": 1292, "s": 1281, "text": " Live Demo" }, { "code": null, "e": 1450, "s": 1292, "text": "#!/usr/bin/perl\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n@names = keys %data;\nprint \"$names[0]\\n\";\nprint \"$names[1]\\n\";\nprint \"$names[2]\\n\";" }, { "code": null, "e": 1491, "s": 1450, "text": "This will produce the following result −" }, { "code": null, "e": 1512, "s": 1491, "text": "Lisa\nJohn Paul\nKumar" }, { "code": null, "e": 1625, "s": 1512, "text": "Similarly, you can use values function to get a list of all the values. This function has the following syntax −" }, { "code": null, "e": 1638, "s": 1625, "text": "values %HASH" }, { "code": null, "e": 1750, "s": 1638, "text": "This function returns a normal array consisting of all the values of the named hash. Following is the example −" }, { "code": null, "e": 1761, "s": 1750, "text": " Live Demo" }, { "code": null, "e": 1917, "s": 1761, "text": "#!/usr/bin/perl\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n@ages = values %data;\nprint \"$ages[0]\\n\";\nprint \"$ages[1]\\n\";\nprint \"$ages[2]\\n\";" }, { "code": null, "e": 1958, "s": 1917, "text": "This will produce the following result −" }, { "code": null, "e": 1967, "s": 1958, "text": "30\n45\n40" } ]
Brewing up custom ML models on AWS SageMaker | by Thushan Ganegedara | Towards Data Science
I recently fell in love with SageMaker. Simply because it is so convenient! I really love their approach hiding all the infrastructural needs from the customer and letting them focus on the more important ML aspects of their solutions. Few clicks and typing here and there, voilà, you’ve got a production ready model ready to take on 1000s (if not millions) of requests a day. If you need a good introduction to SageMaker see the following video by non-other than Amazon! But trouble can strike you when you’re trying to setup and create your own models in your own docker container to perform custom operations! It’s not as straightforward and smooth-flowing as building everything with SageMaker from the beginning. There can be many reasons why you need your own custom model. You might be: Using some specific python library versions instead of the latest (e.g. TensorFlow) Using libraries unavailable on SageMaker Before going forward, make sure you have the following. Docker installed and running in your OS Basic knowledge of how Docker works Now with a good context behind us, let us plough through the details of getting things set up for SageMaker. The tutorial is going to have three different sections. Create a docker image with your code Testing the docker container locally Deploying the image on Amazon ECR (Elastic Container Repository) Let me make flesh these points out here. First you create a docker image with the libraries and code and other requirements (e.g. access to ports). Then you create a contain from that image and run a container. Then you test the code/models with a small chunk of data in the container. After successfully testing, you upload the docker image to the ECR. Then you can specify this image as the ML model and the use it for training/prediction through Amazon SageMaker. Also, I’ll be using this tutorial/guide as the frame of reference for this blog. It’s a really good tutorial. There are few reasons I thought of reinventing that blog post: It’s a good tutorial if you’re relying only on scikit-learn. I thought of creating a container with XGBoost, so we’ll have to do some tinkering around our Docker container. I want Python 3 not Python 2 for obvious reasons. I also feel like some details are missing here and there (especially when it comes to testing locally). And to demonstrate this process, I’ll be training a XGBoost classifier on the iris dataset. You can find the Github repository with all the code here. You know what else is amazing than SageMaker? Docker. Docker is extremely powerful, portable and fast. But this is not the place to discuss why. So let’s straight dive into setting things up. When working with Docker you have a clear set of steps you take: Create a folder with code/models and a special file called Dockerfile that has the recipe to create the docker image Create a docker image by running docker build -t <image-tag> Run the image by running docker run <image> Push the docker image to some store that will store the image (e.g. dockerhub or a AWS ECR repository) using docker push <image-tag> Note that, SageMaker requires the image to have a specific folder structure. The folder structure SageMaker looking for is as follows. Mainly there are two parent folders /opt/program where the code is, and /opt/ml, where the artefacts are. And note that I’ve blurred out some file that you probably won’t need to edit (at least for this exercise), and are outside the scope of this tutorial. Let’s now discuss what each of these entities in detail. First, opt/ml is where all the artefacts are going to be stored. Let’s talk about each of the subdirectories now. input/data is the directory where the data for your model is stored. It can be any data related file (given that your python code can read the data and the container has the required libraries to do so). Here <channel_name> is the name of some consumable input source that will be used by the model. model is where the model will reside. You can either have the model in the container it self, you can specify a URL (S3 bucket location) where the model artefacts reside as a tar.gz file. For example, if you have the model artefacts in a Amazon S3 bucket, you can point to that S3 bucket during model setup on SageMaker. Then these model artefacts will be copied to the model directory, when your model is up and running. Finally, output is the director which will store the reasons for failure of a request/task, if it fails. Let’s now dive into the cream of our model; the algorithm. This should be available in the /opt/program directory of our Docker container. There are three main files that we need to be careful about train , serve and predictor.py . train holds the logic for training the model and storing the trained model. If the train file runs without failures, it will save a model (i.e. pickle file) to /opt/ml/model directory. serve essential runs the logic written in predictor.py as a web service using Flask, that will listen to any incoming requests, invoke the model, make the predictions, and return a response with the predictions. This is the file that underpins what’s going to be available in your Docker container. This means that this file is of uttermost importance. So let’s take a peek inside. It’s quite straight forward if you’re already familiar about how to write a Dockerfile. But let me give you a brief tour anyway. The FROM instruction specifies a base image. So here we are using an already built Ubuntu image as our base image. Next using RUN command, we install several packages (including Python 3.5) using apt-get install Then again using RUN command, we install pip and following that, numpy, scipy, scikit-learn, pandas, flask, etc. Subsequently we set several environment variables within the Docker container using the ENV command. We need to append our /opt/program directory to the path variable so that, when we invoke the container it will know where our algorithm related files are. Last but not least, we COPY the folder containing the algorithm related files to the /opt/program directory and then set that to be the WORKDIR First, I’m going to use a modified version (link here) of the amazing package provided at awslabs Github repository. This original repository has all the files we need to run our SageMaker model, so it’s a matter of editing the files to get it to fit our requirements. Download the content found in the original link to a folder called xgboost-aws-container if you want to start from scratch, othewise, you can fiddle around with my version of the repository. Note: If you’re a Windows user, and you’re one of those unfortunates to run the outdated Docker toolbox, make sure you use some directory in the C:\Users directory as your project home folder. Otherwise, you’ll run into a very ugly experience of mounting the folder to the container. Rename the decision-trees folder to xgboostEdit the train file as provided in the repository. What I’ve essentially done is, I’ve imported xgboost and replaced the decision tree model to a XGBClassifier model. Note that, when ever there is an exception, that will be written to the failure file in the /opt/ml/output folder. So you are free to include as many descriptive exceptions as you want, to make sure you know what went wrong if the program fails.Edit the predictor.py file as provided in the repository. Essentially, what I’ve done is similar to the changes did on train. I imported xgboost and changed the classifier to a XGBClassifier.Open up your Dockerfile do the following edits. Rename the decision-trees folder to xgboost Edit the train file as provided in the repository. What I’ve essentially done is, I’ve imported xgboost and replaced the decision tree model to a XGBClassifier model. Note that, when ever there is an exception, that will be written to the failure file in the /opt/ml/output folder. So you are free to include as many descriptive exceptions as you want, to make sure you know what went wrong if the program fails. Edit the predictor.py file as provided in the repository. Essentially, what I’ve done is similar to the changes did on train. I imported xgboost and changed the classifier to a XGBClassifier. Open up your Dockerfile do the following edits. Instead of python we use python3.5 and also add libgcc-5-dev as it is required by xgboost. RUN apt-get -y update && apt-get install -y — no-install-recommends \ wget \ python3.5 \ nginx \ ca-certificates \ libgcc-5-dev \ && rm -rf /var/lib/apt/lists/* We are going to ask for specific versions of numpy, scikit-learn, pandas, xgboost to make sure they are compatible with each other. The other best thing with specifying the versions of the libraries you want to use is that, you know it won’t break just because a new version of some library is not compatible with your code. RUN wget https://bootstrap.pypa.io/3.3/get-pip.py && python3.5 get-pip.py && \ pip3 install numpy==1.14.3 scipy scikit-learn==0.19.1 xgboost==0.72.1 pandas==0.22.0 flask gevent gunicorn && \ (cd /usr/local/lib/python3.5/dist-packages/scipy/.libs; rm *; ln ../../numpy/.libs/* .) && \ rm -rf /root/.cache Then we’re going to change the COPY command to the following COPY xgboost /opt/program Now open your Docker terminal (if on Windows, otherwise, the OS terminal) and head to the parent directory of the package. Then run the following command. docker build -t xgboost-tut . This should build the image with everything we need. Make sure the image is built by running, docker images You should see something like the following. Now it’s time to run the container, and fire away the following command. docker run --rm -v $(pwd)/local_test/test_dir:/opt/ml xgboost-tut train Let’s break this command down. --rm : Means the container will be destroyed when you exit it -v <host location>:<container location>: Mounts a volume to a desired location in the container. Warning: Windows users, you’ll run into trouble if you choose anything other than C:\Users. xgboost-tut: Name of the image train: With the start of the container, it will automatically start running the train file from the /opt/program directory. This is why specifying /opt/program as a part of the PATH variable is important. Things should run fine and you should see an output similar to the following. Starting the training.Training complete. You should also see the xgboost-model.pkl file in your <project_home>/local_test/test_dir/model directory. This is because we mounted the local_test/test_dir directory to the container’s /opt/ml, so whatever happens to /opt/ml will be reflected in test_dir. Next, we’re going to see if the serving (inference) logic is functioning properly. Now let me warn here again, if you missed it above! If you’re a Windows user, be careful about mounting the volume correctly. To avoid any unnecessary issues, make sure you choose a folder within the C:\Users folder, as your project home directory. docker run --rm --network=host -v $(pwd)/local_test/test_dir:/opt/ml xgboost-tut serve Let me point to a special option that we specify in the Docker run command. --network=host : Means the network stack of the host will be copied to the container. So it will be like running something on the local machine. This is needed to check whether the API calls are working fine. Note: I’m using--network=host, because -p <host_ip>:<host_port>:<container_port> did not work (at least on Windows). I recommend using -p option (if it works), as shown below. Warning: Use only one of these commands, not both. But I’m going to assume the --network=host option to continue forward. docker run --rm -p 127.0.0.1:8080:8080 -v $(pwd)/local_test/test_dir:/opt/ml xgboost-tut serve serve : This is the file which calls the inference logic This should show you an output similar to below. Now to test if we can successfully ping to the service run the following command (in a separate terminal window). curl http://<docker_ip>:8080/ping You can find out the Docker machine’s IP by docker-machine ip default This ping command should spawn two messages, on both host side and the server side. Something like below. If all of this went smoothly (I dearly hope so) until this point. Congratulations! you’ve almost set-up a SageMaker compatible Docker image. Just one more thing we need to do before taking it live. Now let’s try something more exciting. Let’s try to make a prediction through our web service. For this we’re going to use the predict.sh file located in the local_test folder. Note that I’ve adapted it to suit my requirements, meaning that it’s different from the one provided in the original awslabs repository. Precisely, I introduced a new user-prompt argument that takes in the IP address and the port in addition to the ones taken in the original file. We make a call to that modified predict.sh file using the following command. ./predict.sh <container_ip>:<port> payload.csv text/csv Here we are making a call to the inference web service using the data in payload.csv and saying it’s a csv file. It should return you the following. Which says it identified the data point in it as belonging to the class setosa. * timeout on name lookup is not supported* Trying <container_ip>...* TCP_NODELAY set* Connected to <container_ip> (<container_ip>) port <port> (#0)> POST /invocations HTTP/1.1> Host: <container_ip>:<port>> User-Agent: curl/7.55.0> Accept: */*> Content-Type: text/csv> Content-Length: 23>* upload completely sent off: 23 out of 23 bytes< HTTP/1.1 200 OK< Server: nginx/1.10.3 (Ubuntu)< Date: <date and time> GMT< Content-Type: text/csv; charset=utf-8< Content-Length: 7< Connection: keep-alive<setosa* Connection #0 to host <container_ip> left intact Okey! so the hard work has finally paid off. It’s time to push our image to the Amazon Elastic Container Repository (ECR). Before that make sure you have a repository created in the ECR to push the images to. It’s quite straight forward if you have a AWS account. Go to the ECR service from the AWS dashboard and click “Create repository” Once you create the repository, within the repository, you should be able to see the instruction to complete the push to ECR. Note: You can also use the build_and_push.sh provided in the repository. But I personally feel more comfortable doing things myself. And it’s not really that many steps to push the repository. First you need to get the credentials to login to the ECR aws ecr get-login — no-include-email — region <region> which should return an output like, docker login ... copy paste that command and now you should be logged into the ECR. Next you need to re-tag your image to be able to correctly push to the ECR. docker tag xgboost-tut:latest <account>.dkr.ecr.<region>.amazonaws.com/xgboost-tut:latest Now it’s time to push the image to your repository. docker push <account>.dkr.ecr.<region>.amazonaws.com/xgboost-tut:latest Now the image should appear in your ECR repository with the tag latest. So the hard part is done, next you need to create a SageMaker model and point to the image, which is straightforward as creating a model with SageMaker itself. So I won’t stretch the blog post with those details. You can find the Github repository with all the code here. It was a long journey, but a fruitful one (in my opinion). So we did the following in this tutorial. First we understood why we might need to make our own custom models Then we examined the structure of the Docker container required by SageMaker for it to be able to run the container. We then discussed how to create a Docker image of the container This was followed by how to build the image and run the container Next we discussed how to test the container on the local computer, before pushing out Finally we discussed how to push the image to ECR to be available for consumption through SageMaker. Special thanks to the contributors who made the original Github repository giving me an awesome starting point! Last but importantly, If you enjoyed this article make sure you leave a few claps :) Checkout my work on the subject. [1] (Book) TensorFlow 2 in Action — Manning [2] (Video Course) Machine Translation in Python — DataCamp [3] (Book) Natural Language processing in TensorFlow 1 — Packt If you are keen to see my videos on various machine learning/deep learning topics make sure to join DeepLearningHero.
[ { "code": null, "e": 645, "s": 172, "text": "I recently fell in love with SageMaker. Simply because it is so convenient! I really love their approach hiding all the infrastructural needs from the customer and letting them focus on the more important ML aspects of their solutions. Few clicks and typing here and there, voilà, you’ve got a production ready model ready to take on 1000s (if not millions) of requests a day. If you need a good introduction to SageMaker see the following video by non-other than Amazon!" }, { "code": null, "e": 891, "s": 645, "text": "But trouble can strike you when you’re trying to setup and create your own models in your own docker container to perform custom operations! It’s not as straightforward and smooth-flowing as building everything with SageMaker from the beginning." }, { "code": null, "e": 967, "s": 891, "text": "There can be many reasons why you need your own custom model. You might be:" }, { "code": null, "e": 1051, "s": 967, "text": "Using some specific python library versions instead of the latest (e.g. TensorFlow)" }, { "code": null, "e": 1092, "s": 1051, "text": "Using libraries unavailable on SageMaker" }, { "code": null, "e": 1148, "s": 1092, "text": "Before going forward, make sure you have the following." }, { "code": null, "e": 1188, "s": 1148, "text": "Docker installed and running in your OS" }, { "code": null, "e": 1224, "s": 1188, "text": "Basic knowledge of how Docker works" }, { "code": null, "e": 1389, "s": 1224, "text": "Now with a good context behind us, let us plough through the details of getting things set up for SageMaker. The tutorial is going to have three different sections." }, { "code": null, "e": 1426, "s": 1389, "text": "Create a docker image with your code" }, { "code": null, "e": 1463, "s": 1426, "text": "Testing the docker container locally" }, { "code": null, "e": 1528, "s": 1463, "text": "Deploying the image on Amazon ECR (Elastic Container Repository)" }, { "code": null, "e": 1995, "s": 1528, "text": "Let me make flesh these points out here. First you create a docker image with the libraries and code and other requirements (e.g. access to ports). Then you create a contain from that image and run a container. Then you test the code/models with a small chunk of data in the container. After successfully testing, you upload the docker image to the ECR. Then you can specify this image as the ML model and the use it for training/prediction through Amazon SageMaker." }, { "code": null, "e": 2168, "s": 1995, "text": "Also, I’ll be using this tutorial/guide as the frame of reference for this blog. It’s a really good tutorial. There are few reasons I thought of reinventing that blog post:" }, { "code": null, "e": 2341, "s": 2168, "text": "It’s a good tutorial if you’re relying only on scikit-learn. I thought of creating a container with XGBoost, so we’ll have to do some tinkering around our Docker container." }, { "code": null, "e": 2391, "s": 2341, "text": "I want Python 3 not Python 2 for obvious reasons." }, { "code": null, "e": 2495, "s": 2391, "text": "I also feel like some details are missing here and there (especially when it comes to testing locally)." }, { "code": null, "e": 2646, "s": 2495, "text": "And to demonstrate this process, I’ll be training a XGBoost classifier on the iris dataset. You can find the Github repository with all the code here." }, { "code": null, "e": 2903, "s": 2646, "text": "You know what else is amazing than SageMaker? Docker. Docker is extremely powerful, portable and fast. But this is not the place to discuss why. So let’s straight dive into setting things up. When working with Docker you have a clear set of steps you take:" }, { "code": null, "e": 3020, "s": 2903, "text": "Create a folder with code/models and a special file called Dockerfile that has the recipe to create the docker image" }, { "code": null, "e": 3081, "s": 3020, "text": "Create a docker image by running docker build -t <image-tag>" }, { "code": null, "e": 3125, "s": 3081, "text": "Run the image by running docker run <image>" }, { "code": null, "e": 3258, "s": 3125, "text": "Push the docker image to some store that will store the image (e.g. dockerhub or a AWS ECR repository) using docker push <image-tag>" }, { "code": null, "e": 3651, "s": 3258, "text": "Note that, SageMaker requires the image to have a specific folder structure. The folder structure SageMaker looking for is as follows. Mainly there are two parent folders /opt/program where the code is, and /opt/ml, where the artefacts are. And note that I’ve blurred out some file that you probably won’t need to edit (at least for this exercise), and are outside the scope of this tutorial." }, { "code": null, "e": 3822, "s": 3651, "text": "Let’s now discuss what each of these entities in detail. First, opt/ml is where all the artefacts are going to be stored. Let’s talk about each of the subdirectories now." }, { "code": null, "e": 4122, "s": 3822, "text": "input/data is the directory where the data for your model is stored. It can be any data related file (given that your python code can read the data and the container has the required libraries to do so). Here <channel_name> is the name of some consumable input source that will be used by the model." }, { "code": null, "e": 4544, "s": 4122, "text": "model is where the model will reside. You can either have the model in the container it self, you can specify a URL (S3 bucket location) where the model artefacts reside as a tar.gz file. For example, if you have the model artefacts in a Amazon S3 bucket, you can point to that S3 bucket during model setup on SageMaker. Then these model artefacts will be copied to the model directory, when your model is up and running." }, { "code": null, "e": 4649, "s": 4544, "text": "Finally, output is the director which will store the reasons for failure of a request/task, if it fails." }, { "code": null, "e": 4881, "s": 4649, "text": "Let’s now dive into the cream of our model; the algorithm. This should be available in the /opt/program directory of our Docker container. There are three main files that we need to be careful about train , serve and predictor.py ." }, { "code": null, "e": 5066, "s": 4881, "text": "train holds the logic for training the model and storing the trained model. If the train file runs without failures, it will save a model (i.e. pickle file) to /opt/ml/model directory." }, { "code": null, "e": 5278, "s": 5066, "text": "serve essential runs the logic written in predictor.py as a web service using Flask, that will listen to any incoming requests, invoke the model, make the predictions, and return a response with the predictions." }, { "code": null, "e": 5577, "s": 5278, "text": "This is the file that underpins what’s going to be available in your Docker container. This means that this file is of uttermost importance. So let’s take a peek inside. It’s quite straight forward if you’re already familiar about how to write a Dockerfile. But let me give you a brief tour anyway." }, { "code": null, "e": 5692, "s": 5577, "text": "The FROM instruction specifies a base image. So here we are using an already built Ubuntu image as our base image." }, { "code": null, "e": 5789, "s": 5692, "text": "Next using RUN command, we install several packages (including Python 3.5) using apt-get install" }, { "code": null, "e": 5902, "s": 5789, "text": "Then again using RUN command, we install pip and following that, numpy, scipy, scikit-learn, pandas, flask, etc." }, { "code": null, "e": 6159, "s": 5902, "text": "Subsequently we set several environment variables within the Docker container using the ENV command. We need to append our /opt/program directory to the path variable so that, when we invoke the container it will know where our algorithm related files are." }, { "code": null, "e": 6303, "s": 6159, "text": "Last but not least, we COPY the folder containing the algorithm related files to the /opt/program directory and then set that to be the WORKDIR" }, { "code": null, "e": 6763, "s": 6303, "text": "First, I’m going to use a modified version (link here) of the amazing package provided at awslabs Github repository. This original repository has all the files we need to run our SageMaker model, so it’s a matter of editing the files to get it to fit our requirements. Download the content found in the original link to a folder called xgboost-aws-container if you want to start from scratch, othewise, you can fiddle around with my version of the repository." }, { "code": null, "e": 7047, "s": 6763, "text": "Note: If you’re a Windows user, and you’re one of those unfortunates to run the outdated Docker toolbox, make sure you use some directory in the C:\\Users directory as your project home folder. Otherwise, you’ll run into a very ugly experience of mounting the folder to the container." }, { "code": null, "e": 7741, "s": 7047, "text": "Rename the decision-trees folder to xgboostEdit the train file as provided in the repository. What I’ve essentially done is, I’ve imported xgboost and replaced the decision tree model to a XGBClassifier model. Note that, when ever there is an exception, that will be written to the failure file in the /opt/ml/output folder. So you are free to include as many descriptive exceptions as you want, to make sure you know what went wrong if the program fails.Edit the predictor.py file as provided in the repository. Essentially, what I’ve done is similar to the changes did on train. I imported xgboost and changed the classifier to a XGBClassifier.Open up your Dockerfile do the following edits." }, { "code": null, "e": 7785, "s": 7741, "text": "Rename the decision-trees folder to xgboost" }, { "code": null, "e": 8198, "s": 7785, "text": "Edit the train file as provided in the repository. What I’ve essentially done is, I’ve imported xgboost and replaced the decision tree model to a XGBClassifier model. Note that, when ever there is an exception, that will be written to the failure file in the /opt/ml/output folder. So you are free to include as many descriptive exceptions as you want, to make sure you know what went wrong if the program fails." }, { "code": null, "e": 8390, "s": 8198, "text": "Edit the predictor.py file as provided in the repository. Essentially, what I’ve done is similar to the changes did on train. I imported xgboost and changed the classifier to a XGBClassifier." }, { "code": null, "e": 8438, "s": 8390, "text": "Open up your Dockerfile do the following edits." }, { "code": null, "e": 8529, "s": 8438, "text": "Instead of python we use python3.5 and also add libgcc-5-dev as it is required by xgboost." }, { "code": null, "e": 8690, "s": 8529, "text": "RUN apt-get -y update && apt-get install -y — no-install-recommends \\ wget \\ python3.5 \\ nginx \\ ca-certificates \\ libgcc-5-dev \\ && rm -rf /var/lib/apt/lists/*" }, { "code": null, "e": 9015, "s": 8690, "text": "We are going to ask for specific versions of numpy, scikit-learn, pandas, xgboost to make sure they are compatible with each other. The other best thing with specifying the versions of the libraries you want to use is that, you know it won’t break just because a new version of some library is not compatible with your code." }, { "code": null, "e": 9319, "s": 9015, "text": "RUN wget https://bootstrap.pypa.io/3.3/get-pip.py && python3.5 get-pip.py && \\ pip3 install numpy==1.14.3 scipy scikit-learn==0.19.1 xgboost==0.72.1 pandas==0.22.0 flask gevent gunicorn && \\ (cd /usr/local/lib/python3.5/dist-packages/scipy/.libs; rm *; ln ../../numpy/.libs/* .) && \\ rm -rf /root/.cache" }, { "code": null, "e": 9380, "s": 9319, "text": "Then we’re going to change the COPY command to the following" }, { "code": null, "e": 9406, "s": 9380, "text": "COPY xgboost /opt/program" }, { "code": null, "e": 9561, "s": 9406, "text": "Now open your Docker terminal (if on Windows, otherwise, the OS terminal) and head to the parent directory of the package. Then run the following command." }, { "code": null, "e": 9591, "s": 9561, "text": "docker build -t xgboost-tut ." }, { "code": null, "e": 9685, "s": 9591, "text": "This should build the image with everything we need. Make sure the image is built by running," }, { "code": null, "e": 9699, "s": 9685, "text": "docker images" }, { "code": null, "e": 9744, "s": 9699, "text": "You should see something like the following." }, { "code": null, "e": 9817, "s": 9744, "text": "Now it’s time to run the container, and fire away the following command." }, { "code": null, "e": 9889, "s": 9817, "text": "docker run --rm -v $(pwd)/local_test/test_dir:/opt/ml xgboost-tut train" }, { "code": null, "e": 9920, "s": 9889, "text": "Let’s break this command down." }, { "code": null, "e": 9982, "s": 9920, "text": "--rm : Means the container will be destroyed when you exit it" }, { "code": null, "e": 10171, "s": 9982, "text": "-v <host location>:<container location>: Mounts a volume to a desired location in the container. Warning: Windows users, you’ll run into trouble if you choose anything other than C:\\Users." }, { "code": null, "e": 10202, "s": 10171, "text": "xgboost-tut: Name of the image" }, { "code": null, "e": 10407, "s": 10202, "text": "train: With the start of the container, it will automatically start running the train file from the /opt/program directory. This is why specifying /opt/program as a part of the PATH variable is important." }, { "code": null, "e": 10485, "s": 10407, "text": "Things should run fine and you should see an output similar to the following." }, { "code": null, "e": 10526, "s": 10485, "text": "Starting the training.Training complete." }, { "code": null, "e": 10784, "s": 10526, "text": "You should also see the xgboost-model.pkl file in your <project_home>/local_test/test_dir/model directory. This is because we mounted the local_test/test_dir directory to the container’s /opt/ml, so whatever happens to /opt/ml will be reflected in test_dir." }, { "code": null, "e": 11116, "s": 10784, "text": "Next, we’re going to see if the serving (inference) logic is functioning properly. Now let me warn here again, if you missed it above! If you’re a Windows user, be careful about mounting the volume correctly. To avoid any unnecessary issues, make sure you choose a folder within the C:\\Users folder, as your project home directory." }, { "code": null, "e": 11203, "s": 11116, "text": "docker run --rm --network=host -v $(pwd)/local_test/test_dir:/opt/ml xgboost-tut serve" }, { "code": null, "e": 11279, "s": 11203, "text": "Let me point to a special option that we specify in the Docker run command." }, { "code": null, "e": 11488, "s": 11279, "text": "--network=host : Means the network stack of the host will be copied to the container. So it will be like running something on the local machine. This is needed to check whether the API calls are working fine." }, { "code": null, "e": 11786, "s": 11488, "text": "Note: I’m using--network=host, because -p <host_ip>:<host_port>:<container_port> did not work (at least on Windows). I recommend using -p option (if it works), as shown below. Warning: Use only one of these commands, not both. But I’m going to assume the --network=host option to continue forward." }, { "code": null, "e": 11881, "s": 11786, "text": "docker run --rm -p 127.0.0.1:8080:8080 -v $(pwd)/local_test/test_dir:/opt/ml xgboost-tut serve" }, { "code": null, "e": 11938, "s": 11881, "text": "serve : This is the file which calls the inference logic" }, { "code": null, "e": 11987, "s": 11938, "text": "This should show you an output similar to below." }, { "code": null, "e": 12101, "s": 11987, "text": "Now to test if we can successfully ping to the service run the following command (in a separate terminal window)." }, { "code": null, "e": 12135, "s": 12101, "text": "curl http://<docker_ip>:8080/ping" }, { "code": null, "e": 12179, "s": 12135, "text": "You can find out the Docker machine’s IP by" }, { "code": null, "e": 12205, "s": 12179, "text": "docker-machine ip default" }, { "code": null, "e": 12311, "s": 12205, "text": "This ping command should spawn two messages, on both host side and the server side. Something like below." }, { "code": null, "e": 12509, "s": 12311, "text": "If all of this went smoothly (I dearly hope so) until this point. Congratulations! you’ve almost set-up a SageMaker compatible Docker image. Just one more thing we need to do before taking it live." }, { "code": null, "e": 13045, "s": 12509, "text": "Now let’s try something more exciting. Let’s try to make a prediction through our web service. For this we’re going to use the predict.sh file located in the local_test folder. Note that I’ve adapted it to suit my requirements, meaning that it’s different from the one provided in the original awslabs repository. Precisely, I introduced a new user-prompt argument that takes in the IP address and the port in addition to the ones taken in the original file. We make a call to that modified predict.sh file using the following command." }, { "code": null, "e": 13101, "s": 13045, "text": "./predict.sh <container_ip>:<port> payload.csv text/csv" }, { "code": null, "e": 13330, "s": 13101, "text": "Here we are making a call to the inference web service using the data in payload.csv and saying it’s a csv file. It should return you the following. Which says it identified the data point in it as belonging to the class setosa." }, { "code": null, "e": 13880, "s": 13330, "text": "* timeout on name lookup is not supported* Trying <container_ip>...* TCP_NODELAY set* Connected to <container_ip> (<container_ip>) port <port> (#0)> POST /invocations HTTP/1.1> Host: <container_ip>:<port>> User-Agent: curl/7.55.0> Accept: */*> Content-Type: text/csv> Content-Length: 23>* upload completely sent off: 23 out of 23 bytes< HTTP/1.1 200 OK< Server: nginx/1.10.3 (Ubuntu)< Date: <date and time> GMT< Content-Type: text/csv; charset=utf-8< Content-Length: 7< Connection: keep-alive<setosa* Connection #0 to host <container_ip> left intact" }, { "code": null, "e": 14144, "s": 13880, "text": "Okey! so the hard work has finally paid off. It’s time to push our image to the Amazon Elastic Container Repository (ECR). Before that make sure you have a repository created in the ECR to push the images to. It’s quite straight forward if you have a AWS account." }, { "code": null, "e": 14219, "s": 14144, "text": "Go to the ECR service from the AWS dashboard and click “Create repository”" }, { "code": null, "e": 14345, "s": 14219, "text": "Once you create the repository, within the repository, you should be able to see the instruction to complete the push to ECR." }, { "code": null, "e": 14538, "s": 14345, "text": "Note: You can also use the build_and_push.sh provided in the repository. But I personally feel more comfortable doing things myself. And it’s not really that many steps to push the repository." }, { "code": null, "e": 14596, "s": 14538, "text": "First you need to get the credentials to login to the ECR" }, { "code": null, "e": 14651, "s": 14596, "text": "aws ecr get-login — no-include-email — region <region>" }, { "code": null, "e": 14687, "s": 14651, "text": "which should return an output like," }, { "code": null, "e": 14704, "s": 14687, "text": "docker login ..." }, { "code": null, "e": 14847, "s": 14704, "text": "copy paste that command and now you should be logged into the ECR. Next you need to re-tag your image to be able to correctly push to the ECR." }, { "code": null, "e": 14937, "s": 14847, "text": "docker tag xgboost-tut:latest <account>.dkr.ecr.<region>.amazonaws.com/xgboost-tut:latest" }, { "code": null, "e": 14989, "s": 14937, "text": "Now it’s time to push the image to your repository." }, { "code": null, "e": 15061, "s": 14989, "text": "docker push <account>.dkr.ecr.<region>.amazonaws.com/xgboost-tut:latest" }, { "code": null, "e": 15346, "s": 15061, "text": "Now the image should appear in your ECR repository with the tag latest. So the hard part is done, next you need to create a SageMaker model and point to the image, which is straightforward as creating a model with SageMaker itself. So I won’t stretch the blog post with those details." }, { "code": null, "e": 15405, "s": 15346, "text": "You can find the Github repository with all the code here." }, { "code": null, "e": 15506, "s": 15405, "text": "It was a long journey, but a fruitful one (in my opinion). So we did the following in this tutorial." }, { "code": null, "e": 15574, "s": 15506, "text": "First we understood why we might need to make our own custom models" }, { "code": null, "e": 15691, "s": 15574, "text": "Then we examined the structure of the Docker container required by SageMaker for it to be able to run the container." }, { "code": null, "e": 15755, "s": 15691, "text": "We then discussed how to create a Docker image of the container" }, { "code": null, "e": 15821, "s": 15755, "text": "This was followed by how to build the image and run the container" }, { "code": null, "e": 15907, "s": 15821, "text": "Next we discussed how to test the container on the local computer, before pushing out" }, { "code": null, "e": 16008, "s": 15907, "text": "Finally we discussed how to push the image to ECR to be available for consumption through SageMaker." }, { "code": null, "e": 16205, "s": 16008, "text": "Special thanks to the contributors who made the original Github repository giving me an awesome starting point! Last but importantly, If you enjoyed this article make sure you leave a few claps :)" }, { "code": null, "e": 16238, "s": 16205, "text": "Checkout my work on the subject." }, { "code": null, "e": 16282, "s": 16238, "text": "[1] (Book) TensorFlow 2 in Action — Manning" }, { "code": null, "e": 16342, "s": 16282, "text": "[2] (Video Course) Machine Translation in Python — DataCamp" }, { "code": null, "e": 16405, "s": 16342, "text": "[3] (Book) Natural Language processing in TensorFlow 1 — Packt" } ]
Mockito - Behavior Driven Development
Behavior Driven Development is a style of writing tests uses given, when and then format as test methods. Mockito provides special methods to do so. Take a look at the following code snippet. //Given given(calcService.add(20.0,10.0)).willReturn(30.0); //when double result = calcService.add(20.0,10.0); //then Assert.assertEquals(result,30.0,0); Here we're using given method of BDDMockito class instead of when method of . Step 1 − Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2 − Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3 − Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito. File: MathApplicationTester.java package com.tutorialspoint.mock; import static org.mockito.BDDMockito.*; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = mock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAdd(){ //Given given(calcService.add(20.0,10.0)).willReturn(30.0); //when double result = calcService.add(20.0,10.0); //then Assert.assertEquals(result,30.0,0); } } Step 4 − Execute test cases Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5 − Verify the Result Compile the classes using javac compiler as follows − C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java Now run the Test Runner to see the result − C:\Mockito_WORKSPACE>java TestRunner Verify the output. true 31 Lectures 43 mins Abhinav Manchanda Print Add Notes Bookmark this page
[ { "code": null, "e": 2172, "s": 1980, "text": "Behavior Driven Development is a style of writing tests uses given, when and then format as test methods. Mockito provides special methods to do so. Take a look at the following code snippet." }, { "code": null, "e": 2335, "s": 2172, "text": "//Given\ngiven(calcService.add(20.0,10.0)).willReturn(30.0);\n\n//when\ndouble result = calcService.add(20.0,10.0);\n\n//then\nAssert.assertEquals(result,30.0,0);\t \n" }, { "code": null, "e": 2413, "s": 2335, "text": "Here we're using given method of BDDMockito class instead of when method of ." }, { "code": null, "e": 2501, "s": 2413, "text": "Step 1 − Create an interface called CalculatorService to provide mathematical functions" }, { "code": null, "e": 2530, "s": 2501, "text": "File: CalculatorService.java" }, { "code": null, "e": 2790, "s": 2530, "text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}" }, { "code": null, "e": 2848, "s": 2790, "text": "Step 2 − Create a JAVA class to represent MathApplication" }, { "code": null, "e": 2875, "s": 2848, "text": "File: MathApplication.java" }, { "code": null, "e": 3518, "s": 2875, "text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n return calcService.add(input1, input2);\t\t\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}" }, { "code": null, "e": 3558, "s": 3518, "text": "Step 3 − Test the MathApplication class" }, { "code": null, "e": 3677, "s": 3558, "text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito." }, { "code": null, "e": 3710, "s": 3677, "text": "File: MathApplicationTester.java" }, { "code": null, "e": 4612, "s": 3710, "text": "package com.tutorialspoint.mock;\n\nimport static org.mockito.BDDMockito.*;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoJUnitRunner.class)\npublic class MathApplicationTester {\n\t\n private MathApplication mathApplication;\n private CalculatorService calcService;\n\n @Before\n public void setUp(){\n mathApplication = new MathApplication();\n calcService = mock(CalculatorService.class);\n mathApplication.setCalculatorService(calcService);\n }\n\n @Test\n public void testAdd(){\n\n //Given\n given(calcService.add(20.0,10.0)).willReturn(30.0);\n\n //when\n double result = calcService.add(20.0,10.0);\n\n //then\n Assert.assertEquals(result,30.0,0); \n }\n}" }, { "code": null, "e": 4640, "s": 4612, "text": "Step 4 − Execute test cases" }, { "code": null, "e": 4733, "s": 4640, "text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)." }, { "code": null, "e": 4755, "s": 4733, "text": "File: TestRunner.java" }, { "code": null, "e": 5196, "s": 4755, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 5223, "s": 5196, "text": "Step 5 − Verify the Result" }, { "code": null, "e": 5277, "s": 5223, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 5396, "s": 5277, "text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n" }, { "code": null, "e": 5440, "s": 5396, "text": "Now run the Test Runner to see the result −" }, { "code": null, "e": 5478, "s": 5440, "text": "C:\\Mockito_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 5497, "s": 5478, "text": "Verify the output." }, { "code": null, "e": 5503, "s": 5497, "text": "true\n" }, { "code": null, "e": 5535, "s": 5503, "text": "\n 31 Lectures \n 43 mins\n" }, { "code": null, "e": 5554, "s": 5535, "text": " Abhinav Manchanda" }, { "code": null, "e": 5561, "s": 5554, "text": " Print" }, { "code": null, "e": 5572, "s": 5561, "text": " Add Notes" } ]
JavaTuples - Create Tuples
A tuple using JavaTuple classes can be created using multiple options. Following are the examples − Each tuple class has a with() method with corresponding parameters. For example − Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); Triplet<String, Integer, Double> triplet = Triplet.with("Test", Integer.valueOf(5), Double.valueOf(32.1)); Each tuple class has a constructor with corresponding parameters. For example − Pair<String, Integer> pair = new Pair("Test", Integer.valueOf(5)); Triplet<String, Integer, Double> triplet = new Triplet("Test", Integer.valueOf(5), Double.valueOf(32.1)); Each tuple class has a fromCollection() method with corresponding parameters. For example − Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements); Each tuple class has a fromIterable() method to get elements in generic fashion. For example − // Retrieve three values from an iterable starting at index 5 Triplet<Integer,Integer,Integer> triplet = Triplet.fromIterable(listOfInts, 5); Let's see JavaTuples in action. Here we'll see how to create tupels using various ways. Create a java class file named TupleTester in C:\>JavaTuples. File: TupleTester.java package com.tutorialspoint; import java.util.ArrayList; import java.util.List; import org.javatuples.Pair; public class TupleTester { public static void main(String args[]){ //Create using with() method Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); //Create using constructor() Pair<String, Integer> pair1 = new Pair("Test", Integer.valueOf(5)); List<Integer> listOfInts = new ArrayList<Integer>(); listOfInts.add(1); listOfInts.add(2); //Create using fromCollection() method Pair<Integer, Integer> pair2 = Pair.fromCollection(listOfInts); listOfInts.add(3); listOfInts.add(4); listOfInts.add(5); listOfInts.add(6); listOfInts.add(8); listOfInts.add(9); listOfInts.add(10); listOfInts.add(11); //Create using fromIterable() method // Retrieve three values from an iterable starting at index 5 Pair<Integer,Integer> pair3 = Pair.fromIterable(listOfInts, 5); //print all tuples System.out.println(pair); System.out.println(pair1); System.out.println(pair2); System.out.println(pair3); } } Verify the result Compile the classes using javac compiler as follows − C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java Now run the TupleTester to see the result − C:\JavaTuples>java -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester Verify the Output [Test, 5] [Test, 5] [1, 2] [6, 8] Print Add Notes Bookmark this page
[ { "code": null, "e": 2639, "s": 2539, "text": "A tuple using JavaTuple classes can be created using multiple options. Following are the examples −" }, { "code": null, "e": 2721, "s": 2639, "text": "Each tuple class has a with() method with corresponding parameters. For example −" }, { "code": null, "e": 2902, "s": 2721, "text": "Pair<String, Integer> pair = Pair.with(\"Test\", Integer.valueOf(5));\nTriplet<String, Integer, Double> triplet = Triplet.with(\"Test\", Integer.valueOf(5), \n Double.valueOf(32.1));\t\n" }, { "code": null, "e": 2982, "s": 2902, "text": "Each tuple class has a constructor with corresponding parameters. For example −" }, { "code": null, "e": 3161, "s": 2982, "text": "Pair<String, Integer> pair = new Pair(\"Test\", Integer.valueOf(5));\nTriplet<String, Integer, Double> triplet = new Triplet(\"Test\", Integer.valueOf(5), \n Double.valueOf(32.1));\t\n" }, { "code": null, "e": 3253, "s": 3161, "text": "Each tuple class has a fromCollection() method with corresponding parameters. For example −" }, { "code": null, "e": 3324, "s": 3253, "text": "Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements);\t\n" }, { "code": null, "e": 3419, "s": 3324, "text": "Each tuple class has a fromIterable() method to get elements in generic fashion. For example −" }, { "code": null, "e": 3562, "s": 3419, "text": "// Retrieve three values from an iterable starting at index 5\nTriplet<Integer,Integer,Integer> triplet = Triplet.fromIterable(listOfInts, 5);\n" }, { "code": null, "e": 3650, "s": 3562, "text": "Let's see JavaTuples in action. Here we'll see how to create tupels using various ways." }, { "code": null, "e": 3712, "s": 3650, "text": "Create a java class file named TupleTester in C:\\>JavaTuples." }, { "code": null, "e": 3735, "s": 3712, "text": "File: TupleTester.java" }, { "code": null, "e": 4908, "s": 3735, "text": "package com.tutorialspoint;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.javatuples.Pair;\n\npublic class TupleTester {\n public static void main(String args[]){\n //Create using with() method\n Pair<String, Integer> pair = Pair.with(\"Test\", Integer.valueOf(5)); \n //Create using constructor()\n Pair<String, Integer> pair1 = new Pair(\"Test\", Integer.valueOf(5)); \n List<Integer> listOfInts = new ArrayList<Integer>();\n listOfInts.add(1);\n listOfInts.add(2);\n //Create using fromCollection() method\n Pair<Integer, Integer> pair2 = Pair.fromCollection(listOfInts);\t \n listOfInts.add(3);\n listOfInts.add(4);\n listOfInts.add(5);\n listOfInts.add(6);\n listOfInts.add(8);\n listOfInts.add(9);\n listOfInts.add(10);\n listOfInts.add(11);\n //Create using fromIterable() method\n // Retrieve three values from an iterable starting at index 5\n Pair<Integer,Integer> pair3 = Pair.fromIterable(listOfInts, 5);\n //print all tuples\n System.out.println(pair);\n System.out.println(pair1);\n System.out.println(pair2);\n System.out.println(pair3);\n }\n}" }, { "code": null, "e": 4926, "s": 4908, "text": "Verify the result" }, { "code": null, "e": 4980, "s": 4926, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 5062, "s": 4980, "text": "C:\\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java\n" }, { "code": null, "e": 5106, "s": 5062, "text": "Now run the TupleTester to see the result −" }, { "code": null, "e": 5183, "s": 5106, "text": "C:\\JavaTuples>java -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester\n" }, { "code": null, "e": 5201, "s": 5183, "text": "Verify the Output" }, { "code": null, "e": 5236, "s": 5201, "text": "[Test, 5]\n[Test, 5]\n[1, 2]\n[6, 8]\n" }, { "code": null, "e": 5243, "s": 5236, "text": " Print" }, { "code": null, "e": 5254, "s": 5243, "text": " Add Notes" } ]
Ratios - Solved Examples
Q 1 - On the off chance that a:b=2:3 and b:c=5:7, discover a:c. A - 10:11 B - 10:21 C - 21:10 D - 11:10 Answer - B Explanation We have a/b = 2/3 and b/c = 5/7 So a/c = (a/b*b/c) = (2/3*5/7) = 10/21 So its demonstrate that a:c = 10:21 Q 2 - On the off chance that a:b=2:3 and b:c=5:7, discover a:b:c. A - 10:15:21 B - 10:21:15 C - 15:10:21 D - 11:10:21 Answer - A Explanation Here a/b = 2/3 and b/c = 5:7 = 3/5*5:3/5*7 = 3:21/5. So a:b=2:3 and b:c=3:21/5 So a:b:c = 2:3:21/5 = 10:15:21. Q 3 - On the off chance that 4a = 5b and 8b = 9c, find a:b:c. A - 45:36:32 B - 45:32:36 C - 32:45:36 D - 32:36:45 Answer - A Explanation 4a = 5b => a/b=5/4 and 8b = 9c => b/c=9/8 So a:b = 5:4 and b:c = 9:8 = (4/9)(9):(4/9)(8) = 4:32/9 => a:b:c = 5:4:32/9 = 45:36:32. Hence,a:b:c = 45:36:32. Q 4 - On the off chance that a/8 = b/9 = c/12, find a:b:c. A - 8:12:9 B - 8:9:12 C - 12:8:12 D - 9:8:12 Answer - B Explanation Let a/8 = b/9 =c/12 =k. Then a=8k ,b=9k and c=12k. So a:b:c = 8k:9k:12k =8:9:12. Hence,a:b:c = 8:9:12. Q 5 - In the event that a:b =1:3, b:c = 5:7 and c:d = 9:8 ,find a:b:c:d. A - 45:15:63:56 B - 63:45:15:56 C - 15:45:63:56 D - 15:63:45:56 Answer - C Explanation We have a:b = 1:3, b:c = 5:7 and c:d = 9:8 => a:b = 5:15, b:c = 15:21, c:d =(21/9)*9 : (21/9)*8 => a:b = 5:15, b:c = 15:21, c:d = 21:56/3 => a:b:c:d =5:15:21:56/3 = 15:45:63:56 Consequently, a:b:c:d = 15:45:63:56 Q 6 - In the event that (5x+3y): (5x-3y) =3:1, then x:y=? A - 6:5 B - 7:8 C - 8:9 D - 9:11 Answer - A Explanation Here (5x+3y)/(5x-3y) = 3/1 => 5x+3y = 15x-9y => 10x = 12y => x/y = 12/10 = 6/5 So x:y =6:5 Q 7 - In the event that x:y= 5:3 ,then ( 8x-5y) : (8x+5y) = ? A - 6:11 B - 7:11 C - 8:11 D - 5:11 Answer - D Explanation Given x/y = 5/3 Dividing numerator and denominator by y. (8x-5y)/(8x+5y) = {8(x/y) - 5}/{8(x/y) + 5} = {8*(5/3)-5}/{8*(5/3)+5} = (40-15)/(40+15) = 25/55 = 5/11 So (8x-5y):(8x+5y)= 5:11 Q 8 - locate the fourth corresponding to 4,5 and 12. A - 18 B - 16 C - 14 D - 15 Answer - D Explanation Let 4:5::12:x. => 4*x = (5*12) => x = 5*12/4 = 15 So the fourth relative to 4,5,12 is 15. Q 9 - locate the third proportinal corresponding to 9 and 12. A - 18 B - 16 C - 14 D - 15 Answer - B Explanation Third relative to 9 and 12 is equivalent to fourth corresponding to 9,12 and 12. Give it a chance to be x at that point => 9:12::12:x => 9x = 12*12 => x = 12*12/9 =16 So the third relative is 16. Q 10 - Locate the mean relative somewhere around 49 and 64. A - 58 B - 56 C - 54 D - 55 Answer - B Explanation Mean relative somewhere around 49 and 64 is 49*64 = (7*8) = 56. Q 11 - An aggregate of rs. 391 has been divided between a,b,c in the proportion 1/2 :2/3:3/4 , discover the offer of each. A - 102,136,153 B - 112,114,123 C - 114,117,129 D - 122,134,123 Answer - A Explanation We have a:b:c=1/2:2/3:3/4= 6:8:9. A share = (391*6/23) = 102 rs. B offer = (391*8/23) = 136 rs. C offer = (391*9/23) = 153 rs. Q 12 - A sack contain one rupee, fifty paisa and 25 paisa in the proportion of 8:9:11, if the aggregate cash of the pack is 122, discover the no. of coins of every sorts. A - 8,64,72,88 B - 16,32,72,88 C - 8,64,128,88 D - 32,64,128,88 Answer - A Explanation Let the quantity of one rupee, 50-p and 25-p coins be 8x, 9x and 11x individually. At that point, 8x + 9x/2 + 11x/4 =122 => 32x + 18x + 11x = 488 => 61x =488 => x = 8 No. of one rupee coins = 8*8= 64 No. of 50-p coins =9*8= 72 No. of 25-p coins =11*8 =88 Q 13 - A blend contains liquor and water in the proportion 4:3, if 7 liter of water is added to the blend, the proportion of liquor and water gets to be 3:4. Discover the amount of liquor in the blend. A - 12 liters B - 13 liters C - 14 liters D - 15 liters Answer - B Explanation Let the amount of liquor and water be 4x liter and 3x liter separately. At that point , 4x/3x + 7 = 3/4 => 16x = 9x+21 => 7x = 21 so estimation of x is 3 Amount of liquor in the blend is = 4*3 =12 liters. Q 14 - In a collection, the no. of understudy considering expressions, trade and science in the proportion of 4:7:9. On the off chance that the no. of understudy in expressions of the human experience, business and science be expanded by 30%, 20% and 40%. What will be the new proportion? A - 26:42:63 B - 36:42:63 C - 46:42:63 D - 56:42:63 Answer - A Explanation Let the no. of understudy in expressions, business and science be 4x,7x and 9x individually. Presently they are 130% of 4x, 120 % of 7x and 140 % of 9x. Required proportion = (130/100*4x): (120/100*7x) (140/100*9x) =26x/5:42x/5:63x/5 =26:42:63. Q 15 - The expense of assembling an auto is comprised of three items: cost of material, work and overheads. In a year, the expense of these things were in the proportion 4:3:2.Next year, the expense of material rose by 10%,cost of work expanded by 8% however the overheads lessened by 5%.Find the increment for every penny in the auto's cost. A - 44/9 % B - 54/9 % C - 64/9 % D - 74/9 % Answer - A Explanation Let the expense of material, work and over head be rs. 4x, 3x and 2x separately. At that point aggregate expense =9x rs . New cost= {(110% of 4x) + (108% of 3x) +(90% of 2x)} ={(110/100*4x)+(108/100*3x)+(90/100*2x)} = (22x/5 + 81x/25 + 9x/5) = (110x+81x+45x)/25= 236x/25 Increment = {(236x/25)-9x} = 11x/25 Increase%= (11x/25)*(1/9x)*100 % = 44/9 % Q 16 - The proportion of no. of young men to that of the young ladies in a school is 3:2 .if 20% of young men and 25% of young ladies are grant holders, discover the % of the individuals who are not grant holders. A - 64 % B - 78 % C - 84 % D - 76 % Answer - B Explanation Let the no. of young men be 3x and the no. of young ladies 2x. Aggregate no. = 5x No. of the individuals who are not grant holders = (80% of 3x)+(75% of 2x) = (80/100 * 3x) + ( 75/100 * 2x) = (12x/5 + 3x/2) = 39x/10 Required % = (39x/10)*(1/5x)*100 % = 78% Q 17 - An and B together have rs.1210 with them. In the event that 4/15 of A sum is equivalent to 2/5 of B sum, what amount of sum does B have? A - 484 B - 284 C - 384 D - 584 Answer - A Explanation Let (4/15)a = (2/5)b = x then a = 15x/4 and b = 5x/2 So. 15x/4 + 5x/2 =1210 => 15x + 10x = 4840 => 25x = 4840 => x=193.6 So. B = (5/2*193.6) = 484 Henceforth B has Rs. 484. Q 18 - In the event that (x+y): (x-y)= 4:1,then (x2+y2): (x2-y2)=? A - 17/8 B - 19/8 C - 15/8 D - 13/8 Answer - A Explanation (x + y)/(x - y)= 4/1 => x + y = 4x-4y => 3x = 5y => x/y = 5/3 Now (x2+y2)/ (x2-y2)= {(x/y)2+1}/ { (x/y )2-1 } = {(5/3)2+1} / {(5/2)2 -1} = 34/16 = 17/8 Q 19 - In the event that (4x2-3y2) :( 2x2+5y2)= 12:19 , then x:y=? A - 2:1 B - 3:2 C - 4:1 D - 5:2 Answer - B Explanation (4x2 -3y2)/ (2x2 +5y2) = 12/19 =>76x2-57y2 = 24x2+60y2 => 52x2 = 117y2 => x2/y2 = 117/52 = 9/4 => (x/y)2=(3/2)2 => x/y = 3/2. => x:y = 3:2 Q 20 - if x2+y2 = 4xy,then x:y = ? A - 2:1 B - 3:2 C - 4:1 D - 5:2 Answer - A Explanation As x2+4y2 = 4xy => x2 + 4y2 - 4xy = 0 => (x-2y)2 = 0 => x-2y=0 => x = 2y => x/y = 2/1. => x:y = 2:1. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3956, "s": 3892, "text": "Q 1 - On the off chance that a:b=2:3 and b:c=5:7, discover a:c." }, { "code": null, "e": 3966, "s": 3956, "text": "A - 10:11" }, { "code": null, "e": 3976, "s": 3966, "text": "B - 10:21" }, { "code": null, "e": 3986, "s": 3976, "text": "C - 21:10" }, { "code": null, "e": 3996, "s": 3986, "text": "D - 11:10" }, { "code": null, "e": 4007, "s": 3996, "text": "Answer - B" }, { "code": null, "e": 4019, "s": 4007, "text": "Explanation" }, { "code": null, "e": 4129, "s": 4019, "text": "We have a/b = 2/3 and b/c = 5/7 \nSo a/c = (a/b*b/c) = (2/3*5/7) = 10/21 \nSo its demonstrate that a:c = 10:21\n" }, { "code": null, "e": 4195, "s": 4129, "text": "Q 2 - On the off chance that a:b=2:3 and b:c=5:7, discover a:b:c." }, { "code": null, "e": 4208, "s": 4195, "text": "A - 10:15:21" }, { "code": null, "e": 4221, "s": 4208, "text": "B - 10:21:15" }, { "code": null, "e": 4234, "s": 4221, "text": "C - 15:10:21" }, { "code": null, "e": 4247, "s": 4234, "text": "D - 11:10:21" }, { "code": null, "e": 4258, "s": 4247, "text": "Answer - A" }, { "code": null, "e": 4270, "s": 4258, "text": "Explanation" }, { "code": null, "e": 4385, "s": 4270, "text": "Here a/b = 2/3 and b/c = 5:7 = 3/5*5:3/5*7 = 3:21/5. \nSo a:b=2:3 and b:c=3:21/5 \nSo a:b:c = 2:3:21/5 = 10:15:21. \n" }, { "code": null, "e": 4447, "s": 4385, "text": "Q 3 - On the off chance that 4a = 5b and 8b = 9c, find a:b:c." }, { "code": null, "e": 4460, "s": 4447, "text": "A - 45:36:32" }, { "code": null, "e": 4473, "s": 4460, "text": "B - 45:32:36" }, { "code": null, "e": 4486, "s": 4473, "text": "C - 32:45:36" }, { "code": null, "e": 4499, "s": 4486, "text": "D - 32:36:45" }, { "code": null, "e": 4510, "s": 4499, "text": "Answer - A" }, { "code": null, "e": 4522, "s": 4510, "text": "Explanation" }, { "code": null, "e": 4681, "s": 4522, "text": "4a = 5b\n=> a/b=5/4\nand 8b = 9c\n=> b/c=9/8 \nSo a:b = 5:4 and b:c = 9:8 = (4/9)(9):(4/9)(8) = 4:32/9 \n=> a:b:c = 5:4:32/9 = 45:36:32. \nHence,a:b:c = 45:36:32. \n" }, { "code": null, "e": 4740, "s": 4681, "text": "Q 4 - On the off chance that a/8 = b/9 = c/12, find a:b:c." }, { "code": null, "e": 4751, "s": 4740, "text": "A - 8:12:9" }, { "code": null, "e": 4762, "s": 4751, "text": "B - 8:9:12" }, { "code": null, "e": 4774, "s": 4762, "text": "C - 12:8:12" }, { "code": null, "e": 4785, "s": 4774, "text": "D - 9:8:12" }, { "code": null, "e": 4796, "s": 4785, "text": "Answer - B" }, { "code": null, "e": 4808, "s": 4796, "text": "Explanation" }, { "code": null, "e": 4915, "s": 4808, "text": "Let a/8 = b/9 =c/12 =k. \nThen a=8k ,b=9k and c=12k. \nSo a:b:c = 8k:9k:12k =8:9:12. \nHence,a:b:c = 8:9:12.\n" }, { "code": null, "e": 4988, "s": 4915, "text": "Q 5 - In the event that a:b =1:3, b:c = 5:7 and c:d = 9:8 ,find a:b:c:d." }, { "code": null, "e": 5005, "s": 4988, "text": "A - 45:15:63:56 " }, { "code": null, "e": 5022, "s": 5005, "text": "B - 63:45:15:56 " }, { "code": null, "e": 5039, "s": 5022, "text": "C - 15:45:63:56 " }, { "code": null, "e": 5056, "s": 5039, "text": "D - 15:63:45:56 " }, { "code": null, "e": 5067, "s": 5056, "text": "Answer - C" }, { "code": null, "e": 5079, "s": 5067, "text": "Explanation" }, { "code": null, "e": 5299, "s": 5079, "text": "We have a:b = 1:3, b:c = 5:7 and c:d = 9:8 \n=> a:b = 5:15, b:c = 15:21, c:d =(21/9)*9 : (21/9)*8 \n=> a:b = 5:15, b:c = 15:21, c:d = 21:56/3 \n=> a:b:c:d =5:15:21:56/3 = 15:45:63:56 \nConsequently, a:b:c:d = 15:45:63:56 \n" }, { "code": null, "e": 5357, "s": 5299, "text": "Q 6 - In the event that (5x+3y): (5x-3y) =3:1, then x:y=?" }, { "code": null, "e": 5366, "s": 5357, "text": "A - 6:5 " }, { "code": null, "e": 5375, "s": 5366, "text": "B - 7:8 " }, { "code": null, "e": 5384, "s": 5375, "text": "C - 8:9 " }, { "code": null, "e": 5394, "s": 5384, "text": "D - 9:11 " }, { "code": null, "e": 5405, "s": 5394, "text": "Answer - A" }, { "code": null, "e": 5417, "s": 5405, "text": "Explanation" }, { "code": null, "e": 5513, "s": 5417, "text": "Here (5x+3y)/(5x-3y) = 3/1 \n=> 5x+3y = 15x-9y\n=> 10x = 12y\n=> x/y = 12/10 = 6/5 \nSo x:y =6:5 \n" }, { "code": null, "e": 5575, "s": 5513, "text": "Q 7 - In the event that x:y= 5:3 ,then ( 8x-5y) : (8x+5y) = ?" }, { "code": null, "e": 5585, "s": 5575, "text": "A - 6:11 " }, { "code": null, "e": 5595, "s": 5585, "text": "B - 7:11 " }, { "code": null, "e": 5605, "s": 5595, "text": "C - 8:11 " }, { "code": null, "e": 5615, "s": 5605, "text": "D - 5:11 " }, { "code": null, "e": 5626, "s": 5615, "text": "Answer - D" }, { "code": null, "e": 5638, "s": 5626, "text": "Explanation" }, { "code": null, "e": 5826, "s": 5638, "text": "Given x/y = 5/3 \nDividing numerator and denominator by y.\n(8x-5y)/(8x+5y) = {8(x/y) - 5}/{8(x/y) + 5}\n= {8*(5/3)-5}/{8*(5/3)+5}\n= (40-15)/(40+15)\n= 25/55\n= 5/11 \nSo (8x-5y):(8x+5y)= 5:11\n" }, { "code": null, "e": 5879, "s": 5826, "text": "Q 8 - locate the fourth corresponding to 4,5 and 12." }, { "code": null, "e": 5887, "s": 5879, "text": "A - 18 " }, { "code": null, "e": 5895, "s": 5887, "text": "B - 16 " }, { "code": null, "e": 5903, "s": 5895, "text": "C - 14 " }, { "code": null, "e": 5911, "s": 5903, "text": "D - 15 " }, { "code": null, "e": 5922, "s": 5911, "text": "Answer - D" }, { "code": null, "e": 5934, "s": 5922, "text": "Explanation" }, { "code": null, "e": 6029, "s": 5934, "text": "Let 4:5::12:x. \n=> 4*x = (5*12) \n=> x = 5*12/4\n= 15 \nSo the fourth relative to 4,5,12 is 15. \n" }, { "code": null, "e": 6091, "s": 6029, "text": "Q 9 - locate the third proportinal corresponding to 9 and 12." }, { "code": null, "e": 6099, "s": 6091, "text": "A - 18 " }, { "code": null, "e": 6107, "s": 6099, "text": "B - 16 " }, { "code": null, "e": 6115, "s": 6107, "text": "C - 14 " }, { "code": null, "e": 6123, "s": 6115, "text": "D - 15 " }, { "code": null, "e": 6134, "s": 6123, "text": "Answer - B" }, { "code": null, "e": 6146, "s": 6134, "text": "Explanation" }, { "code": null, "e": 6349, "s": 6146, "text": "Third relative to 9 and 12 is equivalent to fourth corresponding to 9,12 and 12. \nGive it a chance to be x at that point \n=> 9:12::12:x \n=> 9x = 12*12 \n=> x = 12*12/9\n=16 \nSo the third relative is 16. \n" }, { "code": null, "e": 6409, "s": 6349, "text": "Q 10 - Locate the mean relative somewhere around 49 and 64." }, { "code": null, "e": 6417, "s": 6409, "text": "A - 58 " }, { "code": null, "e": 6425, "s": 6417, "text": "B - 56 " }, { "code": null, "e": 6433, "s": 6425, "text": "C - 54 " }, { "code": null, "e": 6441, "s": 6433, "text": "D - 55 " }, { "code": null, "e": 6452, "s": 6441, "text": "Answer - B" }, { "code": null, "e": 6464, "s": 6452, "text": "Explanation" }, { "code": null, "e": 6530, "s": 6464, "text": "Mean relative somewhere around 49 and 64 is 49*64 = (7*8) = 56. \n" }, { "code": null, "e": 6653, "s": 6530, "text": "Q 11 - An aggregate of rs. 391 has been divided between a,b,c in the proportion 1/2 :2/3:3/4 , discover the offer of each." }, { "code": null, "e": 6670, "s": 6653, "text": "A - 102,136,153 " }, { "code": null, "e": 6687, "s": 6670, "text": "B - 112,114,123 " }, { "code": null, "e": 6704, "s": 6687, "text": "C - 114,117,129 " }, { "code": null, "e": 6721, "s": 6704, "text": "D - 122,134,123 " }, { "code": null, "e": 6732, "s": 6721, "text": "Answer - A" }, { "code": null, "e": 6744, "s": 6732, "text": "Explanation" }, { "code": null, "e": 6875, "s": 6744, "text": "We have a:b:c=1/2:2/3:3/4= 6:8:9. \nA share = (391*6/23) = 102 rs. \nB offer = (391*8/23) = 136 rs. \nC offer = (391*9/23) = 153 rs.\n" }, { "code": null, "e": 7046, "s": 6875, "text": "Q 12 - A sack contain one rupee, fifty paisa and 25 paisa in the proportion of 8:9:11, if the aggregate cash of the pack is 122, discover the no. of coins of every sorts." }, { "code": null, "e": 7062, "s": 7046, "text": "A - 8,64,72,88 " }, { "code": null, "e": 7079, "s": 7062, "text": "B - 16,32,72,88 " }, { "code": null, "e": 7096, "s": 7079, "text": "C - 8,64,128,88 " }, { "code": null, "e": 7114, "s": 7096, "text": "D - 32,64,128,88 " }, { "code": null, "e": 7125, "s": 7114, "text": "Answer - A" }, { "code": null, "e": 7137, "s": 7125, "text": "Explanation" }, { "code": null, "e": 7400, "s": 7137, "text": "Let the quantity of one rupee, 50-p and 25-p coins be 8x, 9x and 11x individually. \nAt that point, 8x + 9x/2 + 11x/4 =122 \n=> 32x + 18x + 11x = 488\n=> 61x =488 \n=> x = 8 \nNo. of one rupee coins = 8*8= 64 \nNo. of 50-p coins =9*8= 72 \nNo. of 25-p coins =11*8 =88 \n" }, { "code": null, "e": 7603, "s": 7400, "text": "Q 13 - A blend contains liquor and water in the proportion 4:3, if 7 liter of water is added to the blend, the proportion of liquor and water gets to be 3:4. Discover the amount of liquor in the blend. " }, { "code": null, "e": 7618, "s": 7603, "text": "A - 12 liters " }, { "code": null, "e": 7633, "s": 7618, "text": "B - 13 liters " }, { "code": null, "e": 7648, "s": 7633, "text": "C - 14 liters " }, { "code": null, "e": 7663, "s": 7648, "text": "D - 15 liters " }, { "code": null, "e": 7674, "s": 7663, "text": "Answer - B" }, { "code": null, "e": 7686, "s": 7674, "text": "Explanation" }, { "code": null, "e": 7897, "s": 7686, "text": "Let the amount of liquor and water be 4x liter and 3x liter separately.\nAt that point , 4x/3x + 7 = 3/4 \n=> 16x = 9x+21 \n=> 7x = 21 \nso estimation of x is 3 \nAmount of liquor in the blend is = 4*3 =12 liters. \n" }, { "code": null, "e": 8187, "s": 7897, "text": "Q 14 - In a collection, the no. of understudy considering expressions, trade and science in the proportion of 4:7:9. On the off chance that the no. of understudy in expressions of the human experience, business and science be expanded by 30%, 20% and 40%. What will be the new proportion? " }, { "code": null, "e": 8201, "s": 8187, "text": "A - 26:42:63 " }, { "code": null, "e": 8214, "s": 8201, "text": "B - 36:42:63" }, { "code": null, "e": 8228, "s": 8214, "text": "C - 46:42:63 " }, { "code": null, "e": 8242, "s": 8228, "text": "D - 56:42:63 " }, { "code": null, "e": 8253, "s": 8242, "text": "Answer - A" }, { "code": null, "e": 8265, "s": 8253, "text": "Explanation" }, { "code": null, "e": 8514, "s": 8265, "text": "Let the no. of understudy in expressions, business and science be 4x,7x and 9x individually. \nPresently they are 130% of 4x, 120 % of 7x and 140 % of 9x. \nRequired proportion = (130/100*4x): (120/100*7x) (140/100*9x) \n=26x/5:42x/5:63x/5\n=26:42:63.\n" }, { "code": null, "e": 8857, "s": 8514, "text": "Q 15 - The expense of assembling an auto is comprised of three items: cost of material, work and overheads. In a year, the expense of these things were in the proportion 4:3:2.Next year, the expense of material rose by 10%,cost of work expanded by 8% however the overheads lessened by 5%.Find the increment for every penny in the auto's cost." }, { "code": null, "e": 8870, "s": 8857, "text": "A - 44/9 % " }, { "code": null, "e": 8882, "s": 8870, "text": "B - 54/9 % " }, { "code": null, "e": 8894, "s": 8882, "text": "C - 64/9 % " }, { "code": null, "e": 8907, "s": 8894, "text": "D - 74/9 % " }, { "code": null, "e": 8918, "s": 8907, "text": "Answer - A" }, { "code": null, "e": 8930, "s": 8918, "text": "Explanation" }, { "code": null, "e": 9288, "s": 8930, "text": "Let the expense of material, work and over head be rs. 4x, 3x and 2x separately. \nAt that point aggregate expense =9x rs . \nNew cost= {(110% of 4x) + (108% of 3x) +(90% of 2x)} \n={(110/100*4x)+(108/100*3x)+(90/100*2x)} \n= (22x/5 + 81x/25 + 9x/5)\n= (110x+81x+45x)/25= 236x/25 \nIncrement = {(236x/25)-9x} = 11x/25 \nIncrease%= (11x/25)*(1/9x)*100 % \n= 44/9 % \n" }, { "code": null, "e": 9502, "s": 9288, "text": "Q 16 - The proportion of no. of young men to that of the young ladies in a school is 3:2 .if 20% of young men and 25% of young ladies are grant holders, discover the % of the individuals who are not grant holders." }, { "code": null, "e": 9513, "s": 9502, "text": "A - 64 % " }, { "code": null, "e": 9523, "s": 9513, "text": "B - 78 % " }, { "code": null, "e": 9533, "s": 9523, "text": "C - 84 % " }, { "code": null, "e": 9544, "s": 9533, "text": "D - 76 % " }, { "code": null, "e": 9555, "s": 9544, "text": "Answer - B" }, { "code": null, "e": 9567, "s": 9555, "text": "Explanation" }, { "code": null, "e": 9832, "s": 9567, "text": "Let the no. of young men be 3x and the no. of young ladies 2x. \nAggregate no. = 5x \nNo. of the individuals who are not grant holders \n= (80% of 3x)+(75% of 2x) \n= (80/100 * 3x) + ( 75/100 * 2x) \n= (12x/5 + 3x/2)\n= 39x/10 \nRequired % = (39x/10)*(1/5x)*100 %\n= 78% \n" }, { "code": null, "e": 9977, "s": 9832, "text": "Q 17 - An and B together have rs.1210 with them. In the event that 4/15 of A sum is equivalent to 2/5 of B sum, what amount of sum does B have? " }, { "code": null, "e": 9987, "s": 9977, "text": "A - 484 " }, { "code": null, "e": 9996, "s": 9987, "text": "B - 284 " }, { "code": null, "e": 10005, "s": 9996, "text": "C - 384 " }, { "code": null, "e": 10015, "s": 10005, "text": "D - 584 " }, { "code": null, "e": 10026, "s": 10015, "text": "Answer - A" }, { "code": null, "e": 10038, "s": 10026, "text": "Explanation" }, { "code": null, "e": 10219, "s": 10038, "text": "Let (4/15)a = (2/5)b = x \nthen a = 15x/4 and b = 5x/2 \nSo. 15x/4 + 5x/2 =1210 \n=> 15x + 10x = 4840 \n=> 25x = 4840 \n=> x=193.6 \nSo. B = (5/2*193.6) = 484 \nHenceforth B has Rs. 484.\n" }, { "code": null, "e": 10287, "s": 10219, "text": "Q 18 - In the event that (x+y): (x-y)= 4:1,then (x2+y2): (x2-y2)=? " }, { "code": null, "e": 10298, "s": 10287, "text": "A - 17/8 " }, { "code": null, "e": 10308, "s": 10298, "text": "B - 19/8 " }, { "code": null, "e": 10318, "s": 10308, "text": "C - 15/8 " }, { "code": null, "e": 10329, "s": 10318, "text": "D - 13/8 " }, { "code": null, "e": 10340, "s": 10329, "text": "Answer - A" }, { "code": null, "e": 10352, "s": 10340, "text": "Explanation" }, { "code": null, "e": 10508, "s": 10352, "text": "(x + y)/(x - y)= 4/1\n=> x + y = 4x-4y\n=> 3x = 5y\n=> x/y = 5/3\nNow (x2+y2)/ (x2-y2)= {(x/y)2+1}/ { (x/y )2-1 }\n= {(5/3)2+1} / {(5/2)2 -1} \n= 34/16 = 17/8 \n" }, { "code": null, "e": 10576, "s": 10508, "text": "Q 19 - In the event that (4x2-3y2) :( 2x2+5y2)= 12:19 , then x:y=? " }, { "code": null, "e": 10586, "s": 10576, "text": "A - 2:1 " }, { "code": null, "e": 10595, "s": 10586, "text": "B - 3:2 " }, { "code": null, "e": 10604, "s": 10595, "text": "C - 4:1 " }, { "code": null, "e": 10614, "s": 10604, "text": "D - 5:2 " }, { "code": null, "e": 10625, "s": 10614, "text": "Answer - B" }, { "code": null, "e": 10637, "s": 10625, "text": "Explanation" }, { "code": null, "e": 10777, "s": 10637, "text": "(4x2 -3y2)/ (2x2 +5y2) = 12/19\n=>76x2-57y2 = 24x2+60y2\n=> 52x2 = 117y2\n=> x2/y2 = 117/52 = 9/4\n=> (x/y)2=(3/2)2\n=> x/y = 3/2.\n=> x:y = 3:2\n" }, { "code": null, "e": 10813, "s": 10777, "text": "Q 20 - if x2+y2 = 4xy,then x:y = ? " }, { "code": null, "e": 10823, "s": 10813, "text": "A - 2:1 " }, { "code": null, "e": 10832, "s": 10823, "text": "B - 3:2 " }, { "code": null, "e": 10841, "s": 10832, "text": "C - 4:1 " }, { "code": null, "e": 10851, "s": 10841, "text": "D - 5:2 " }, { "code": null, "e": 10862, "s": 10851, "text": "Answer - A" }, { "code": null, "e": 10874, "s": 10862, "text": "Explanation" }, { "code": null, "e": 10980, "s": 10874, "text": "As x2+4y2 = 4xy \n=> x2 + 4y2 - 4xy = 0 \n=> (x-2y)2 = 0\n=> x-2y=0 \n=> x = 2y \n=> x/y = 2/1.\n=> x:y = 2:1.\n" }, { "code": null, "e": 11016, "s": 10980, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 11034, "s": 11016, "text": " Programming Line" }, { "code": null, "e": 11041, "s": 11034, "text": " Print" }, { "code": null, "e": 11052, "s": 11041, "text": " Add Notes" } ]
Scala String trim() method with example - GeeksforGeeks
29 Oct, 2019 The trim() method is utilized to omit the leading and trailing spaces in the stated string. Method Definition: String trim() Return Type: It returns the stated string after removing all the white spaces. Example: 1# // Scala program of trim()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying trim method val result = " Nidhi Singh ".trim() // Displays output println(result) }} Nidhi Singh Example: 2# // Scala program of trim()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying trim method val result = " Nidhi Singh GfG ".trim() // Displays output println(result) }} Nidhi Singh GfG Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Tutorial – Learn Scala with Step By Step Guide Scala List filter() method with example Scala Map Type Casting in Scala Scala Lists Class and Object in Scala Scala List contains() method with example Break statement in Scala Operators in Scala Scala | Arrays
[ { "code": null, "e": 23707, "s": 23679, "text": "\n29 Oct, 2019" }, { "code": null, "e": 23799, "s": 23707, "text": "The trim() method is utilized to omit the leading and trailing spaces in the stated string." }, { "code": null, "e": 23832, "s": 23799, "text": "Method Definition: String trim()" }, { "code": null, "e": 23911, "s": 23832, "text": "Return Type: It returns the stated string after removing all the white spaces." }, { "code": null, "e": 23923, "s": 23911, "text": "Example: 1#" }, { "code": "// Scala program of trim()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying trim method val result = \" Nidhi Singh \".trim() // Displays output println(result) }} ", "e": 24204, "s": 23923, "text": null }, { "code": null, "e": 24217, "s": 24204, "text": "Nidhi Singh\n" }, { "code": null, "e": 24229, "s": 24217, "text": "Example: 2#" }, { "code": "// Scala program of trim()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying trim method val result = \" Nidhi Singh GfG \".trim() // Displays output println(result) }} ", "e": 24514, "s": 24229, "text": null }, { "code": null, "e": 24531, "s": 24514, "text": "Nidhi Singh GfG\n" }, { "code": null, "e": 24537, "s": 24531, "text": "Scala" }, { "code": null, "e": 24550, "s": 24537, "text": "Scala-Method" }, { "code": null, "e": 24564, "s": 24550, "text": "Scala-Strings" }, { "code": null, "e": 24570, "s": 24564, "text": "Scala" }, { "code": null, "e": 24668, "s": 24570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24677, "s": 24668, "text": "Comments" }, { "code": null, "e": 24690, "s": 24677, "text": "Old Comments" }, { "code": null, "e": 24743, "s": 24690, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 24783, "s": 24743, "text": "Scala List filter() method with example" }, { "code": null, "e": 24793, "s": 24783, "text": "Scala Map" }, { "code": null, "e": 24815, "s": 24793, "text": "Type Casting in Scala" }, { "code": null, "e": 24827, "s": 24815, "text": "Scala Lists" }, { "code": null, "e": 24853, "s": 24827, "text": "Class and Object in Scala" }, { "code": null, "e": 24895, "s": 24853, "text": "Scala List contains() method with example" }, { "code": null, "e": 24920, "s": 24895, "text": "Break statement in Scala" }, { "code": null, "e": 24939, "s": 24920, "text": "Operators in Scala" } ]
Display month by name and number in Java
Use the ‘b’ conversion character for month name in Java. Use the ‘m’ conversion character for month number in Java. Here, we are using Formatter and Calendar class, therefore import the following packages. import java.util.Calendar; import java.util.Formatter; The following is an example to display month name and number − Live Demo import java.util.Calendar; import java.util.Formatter; public class Demo { public static void main(String args[]) { Formatter f = new Formatter(); Calendar cal = Calendar.getInstance(); System.out.println("Current date and time: "+cal.getTime()); f = new Formatter(); System.out.println(f.format("Month = %tb \nMonth Number = %tm", cal, cal)); } } Current date and time: Mon Nov 26 07:07:31 UTC 2018 Month = Nov Month Number = 11
[ { "code": null, "e": 1119, "s": 1062, "text": "Use the ‘b’ conversion character for month name in Java." }, { "code": null, "e": 1178, "s": 1119, "text": "Use the ‘m’ conversion character for month number in Java." }, { "code": null, "e": 1268, "s": 1178, "text": "Here, we are using Formatter and Calendar class, therefore import the following packages." }, { "code": null, "e": 1323, "s": 1268, "text": "import java.util.Calendar;\nimport java.util.Formatter;" }, { "code": null, "e": 1386, "s": 1323, "text": "The following is an example to display month name and number −" }, { "code": null, "e": 1397, "s": 1386, "text": " Live Demo" }, { "code": null, "e": 1781, "s": 1397, "text": "import java.util.Calendar;\nimport java.util.Formatter;\npublic class Demo {\n public static void main(String args[]) {\n Formatter f = new Formatter();\n Calendar cal = Calendar.getInstance();\n System.out.println(\"Current date and time: \"+cal.getTime());\n f = new Formatter();\n System.out.println(f.format(\"Month = %tb \\nMonth Number = %tm\", cal, cal));\n }\n}" }, { "code": null, "e": 1863, "s": 1781, "text": "Current date and time: Mon Nov 26 07:07:31 UTC 2018\nMonth = Nov\nMonth Number = 11" } ]
PyQt5 QSpinBox - Making text bold - GeeksforGeeks
19 May, 2020 In this article we will see how we can make the text of the spin box bold, in order to set the font use setFont method which takes QFont object as argument. In order to make the the text i.e font bold we have to get the QFont object of the spin box then make it bold then reassign it to the spin box. In order to do this we use setBold method with the QFont object of the spin box Syntax : font.setBold(True) Argument : It takes bool as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix("Prefix ") # setting suffix to spin self.spin.setSuffix(" Suffix") # getting font of the spin box font = self.spin.font() # making font bold font.setBold(True) # setting back this font to the spin box self.spin.setFont(font) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24501, "s": 24473, "text": "\n19 May, 2020" }, { "code": null, "e": 24802, "s": 24501, "text": "In this article we will see how we can make the text of the spin box bold, in order to set the font use setFont method which takes QFont object as argument. In order to make the the text i.e font bold we have to get the QFont object of the spin box then make it bold then reassign it to the spin box." }, { "code": null, "e": 24882, "s": 24802, "text": "In order to do this we use setBold method with the QFont object of the spin box" }, { "code": null, "e": 24910, "s": 24882, "text": "Syntax : font.setBold(True)" }, { "code": null, "e": 24947, "s": 24910, "text": "Argument : It takes bool as argument" }, { "code": null, "e": 24972, "s": 24947, "text": "Return : It returns None" }, { "code": null, "e": 25000, "s": 24972, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix(\"Prefix \") # setting suffix to spin self.spin.setSuffix(\" Suffix\") # getting font of the spin box font = self.spin.font() # making font bold font.setBold(True) # setting back this font to the spin box self.spin.setFont(font) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26244, "s": 25000, "text": null }, { "code": null, "e": 26253, "s": 26244, "text": "Output :" }, { "code": null, "e": 26273, "s": 26253, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 26284, "s": 26273, "text": "Python-gui" }, { "code": null, "e": 26296, "s": 26284, "text": "Python-PyQt" }, { "code": null, "e": 26303, "s": 26296, "text": "Python" }, { "code": null, "e": 26401, "s": 26303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26410, "s": 26401, "text": "Comments" }, { "code": null, "e": 26423, "s": 26410, "text": "Old Comments" }, { "code": null, "e": 26441, "s": 26423, "text": "Python Dictionary" }, { "code": null, "e": 26476, "s": 26441, "text": "Read a file line by line in Python" }, { "code": null, "e": 26498, "s": 26476, "text": "Enumerate() in Python" }, { "code": null, "e": 26530, "s": 26498, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26572, "s": 26530, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26598, "s": 26572, "text": "Python String | replace()" }, { "code": null, "e": 26642, "s": 26598, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26667, "s": 26642, "text": "sum() function in Python" }, { "code": null, "e": 26704, "s": 26667, "text": "Create a Pandas DataFrame from Lists" } ]
How to update the value of a key in a dictionary in Python?
Python dictionary object is an unordered collection of key:value pairs. Ina dictionary object d, the value associated to any key can be obtained by d[k]. >>> d={'one':1, 'two':2,'three':3,'four':4} >>> d['two'] 2 The assignment d[k]=v will update the dictionary object. If existing key is used in the expression, its associated value will be updated. If the key has not been used, a new key-value pair will be added in the dictionary object. >>> d={'one':1, 'two':2,'three':3,'four':4} >>> d['two']=22 >>> d {'one': 1, 'two': 22, 'three': 3, 'four': 4} >>> d['five']=5 >>> d {'one': 1, 'two': 22, 'three': 3, 'four': 4, 'five': 5}
[ { "code": null, "e": 1216, "s": 1062, "text": "Python dictionary object is an unordered collection of key:value pairs. Ina dictionary object d, the value associated to any key can be obtained by d[k]." }, { "code": null, "e": 1275, "s": 1216, "text": ">>> d={'one':1, 'two':2,'three':3,'four':4}\n>>> d['two']\n2" }, { "code": null, "e": 1504, "s": 1275, "text": "The assignment d[k]=v will update the dictionary object. If existing key is used in the expression, its associated value will be updated. If the key has not been used, a new key-value pair will be added in the dictionary object." }, { "code": null, "e": 1695, "s": 1504, "text": ">>> d={'one':1, 'two':2,'three':3,'four':4}\n>>> d['two']=22\n>>> d\n{'one': 1, 'two': 22, 'three': 3, 'four': 4}\n>>> d['five']=5\n>>> d\n{'one': 1, 'two': 22, 'three': 3, 'four': 4, 'five': 5}\n\n" } ]
Check Power BI usage metrics on Report Server | by Nikola Ilic | Towards Data Science
Building Power BI reports is a cool thing, I won’t argue about it! And I am pretty sure that each time we build a report, we firmly believe that this report is a “real deal” and that it will be consumed by a large majority of our users. However, reality is often completely opposite! There are many reports that are being regularly run in the beginning, but after a while, they are starting to become a “dead wood”. Of course, there are some “evergreen” reports, that are being used frequently for years, but I would argue that that’s more an exception than the rule. The point here is that you need to have a possibility to check the usage metrics of your Power BI reports — which reports are most frequently run, which users are the most active, or to simply identify rarely used reports, so you can consider removing or adjusting them. If you’re using Power BI Service — you’re the lucky one! Just go to Admin portal, and click on Usage metrics: And you will get a nice overview of the various figures related to your reports, dashboards, datasets... Good news! There is also a possibility to check the metrics, even to visualize them similar to the Service version. Magic happens within two special DMVs (Data Management Views) that reside in the ReportServer database on your reporting server. These two specially created views are ExecutionLog and ExecutionLog3, which retrieve data from the underlying table ExecutionlogStorage. Here is the basic example of how you can check the execution log for the report called Sales by Year, and walk through all executions from the beginning of this year until the moment of the query run. Results are displayed sorted in descending order, starting from the latest execution. USE [ReportServer] SELECT c.[name] as reportName ,e.username as userExec ,e.TimeStart ,e.TimeEnd ,DATEDIFF(ss,e.TimeStart,e.TimeEnd) as TimeInSeconds ,e.Parameters ,c.ModifiedDate as ReportLastModified ,u.username as userCreated FROM catalog c INNER JOIN executionlogstorage e on c.itemid = e.reportid INNER JOIN users u on c.modifiedbyid = u.userid WHERE e.TimeStart >= '2020-01-01' AND e.TimeEnd < getdate() AND c.[name] = 'SalesByYear' ORDER BY timestart DESC Simply said, when you run the query, you should be able to see the report name, a user that created the report, when the report was last modified, a user that performed specific execution, and, most important, the time that report needed for rendering and parameters which were used. This should give you a brief overview of things happening in the background. In case you need to check the execution log in more depth, you can run the following query: USE [ReportServer] SELECT c.[Name] as reportname ,e.InstanceName ,e.ItemPath ,e.UserName as userExec ,e.RequestType --Interactive or Subscription ,e.Parameters ,e.ItemAction --Render or Sort ,e.TimeStart ,e.TimeEnd ,e.TimeDataRetrieval ,e.TimeProcessing ,e.TimeRendering ,e.Source ,e.Status ,e.ByteCount ,e.RowCount FROM Catalog c INNER JOIN ExecutionLog3 e ON e.ItemPath = c.Path WHERE c.name = 'SalesByYear' AND e.TimeStart >= '2020-01-01' AND e.TimeEnd < getdate() ORDER BY e.TimeStart DESC I also like to have an overview of which reports are being used and which can be considered as “dead wood”. Therefore, I created a simple Power BI report, which imports data from the following query in the background: USE [ReportServer] SELECT distinct a.* ,l.UserName FROM( SELECT c.[name] as reportName ,SUBSTRING(SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)),0,CHARINDEX('/',SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)))) Folder ,CASE(RequestType) WHEN 0 THEN 'Interactive' WHEN 1 THEN 'Subscription' WHEN 2 THEN 'Refresh Cache' ELSE 'Unknown' END AS RequestType ,MAX(l.TimeStart) lastRunDate FROM Catalog c INNER JOIN ExecutionLogStorage l ON l.ReportID = c.ItemID WHERE c.Type NOT IN (1,3,5,8) AND l.ReportAction IN(1,13) GROUP BY c.[name] ,SUBSTRING(SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)),0,CHARINDEX('/',SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)))) ,CASE(RequestType) WHEN 0 THEN 'Interactive' WHEN 1 THEN 'Subscription' WHEN 2 THEN 'Refresh Cache' ELSE 'Unknown' END HAVING MAX(l.TimeStart) < getdate() - 90 ) a INNER JOIN ExecutionLogStorage l ON l.TimeStart = a.lastRunDate This query returns a list of reports that were not run in the last 90 days. Of course, you can adjust the date range according to your needs. In any case, you can refer to this article and check all the different information you can obtain using these DMVs. So, here is what I’ve created in Power BI to visualize this data: This page shows me the total number of executions for the specific report in the selected time period, and also some additional info on the right. The next page gives me an overview per user, but also per folders on the Report Server: Finally, the most useful for me is to check which reports are rarely used. The following report page helps me to identify those items: Even though Power BI Service gives you ready-made solution for examining usage metrics, there are still lot of us working with Power BI Report Server. Therefore, I believe that having report similar to this one can help you better understand who, when and how, running your reports! Thanks for reading! Become a member and read every story on Medium! Subscribe here to get more insightful data articles!
[ { "code": null, "e": 408, "s": 171, "text": "Building Power BI reports is a cool thing, I won’t argue about it! And I am pretty sure that each time we build a report, we firmly believe that this report is a “real deal” and that it will be consumed by a large majority of our users." }, { "code": null, "e": 739, "s": 408, "text": "However, reality is often completely opposite! There are many reports that are being regularly run in the beginning, but after a while, they are starting to become a “dead wood”. Of course, there are some “evergreen” reports, that are being used frequently for years, but I would argue that that’s more an exception than the rule." }, { "code": null, "e": 1010, "s": 739, "text": "The point here is that you need to have a possibility to check the usage metrics of your Power BI reports — which reports are most frequently run, which users are the most active, or to simply identify rarely used reports, so you can consider removing or adjusting them." }, { "code": null, "e": 1120, "s": 1010, "text": "If you’re using Power BI Service — you’re the lucky one! Just go to Admin portal, and click on Usage metrics:" }, { "code": null, "e": 1225, "s": 1120, "text": "And you will get a nice overview of the various figures related to your reports, dashboards, datasets..." }, { "code": null, "e": 1341, "s": 1225, "text": "Good news! There is also a possibility to check the metrics, even to visualize them similar to the Service version." }, { "code": null, "e": 1607, "s": 1341, "text": "Magic happens within two special DMVs (Data Management Views) that reside in the ReportServer database on your reporting server. These two specially created views are ExecutionLog and ExecutionLog3, which retrieve data from the underlying table ExecutionlogStorage." }, { "code": null, "e": 1894, "s": 1607, "text": "Here is the basic example of how you can check the execution log for the report called Sales by Year, and walk through all executions from the beginning of this year until the moment of the query run. Results are displayed sorted in descending order, starting from the latest execution." }, { "code": null, "e": 2434, "s": 1894, "text": "USE [ReportServer] SELECT c.[name] as reportName ,e.username as userExec ,e.TimeStart ,e.TimeEnd ,DATEDIFF(ss,e.TimeStart,e.TimeEnd) as TimeInSeconds ,e.Parameters ,c.ModifiedDate as ReportLastModified ,u.username as userCreated FROM catalog c INNER JOIN executionlogstorage e on c.itemid = e.reportid INNER JOIN users u on c.modifiedbyid = u.userid WHERE e.TimeStart >= '2020-01-01' AND e.TimeEnd < getdate() AND c.[name] = 'SalesByYear' ORDER BY timestart DESC" }, { "code": null, "e": 2795, "s": 2434, "text": "Simply said, when you run the query, you should be able to see the report name, a user that created the report, when the report was last modified, a user that performed specific execution, and, most important, the time that report needed for rendering and parameters which were used. This should give you a brief overview of things happening in the background." }, { "code": null, "e": 2887, "s": 2795, "text": "In case you need to check the execution log in more depth, you can run the following query:" }, { "code": null, "e": 3489, "s": 2887, "text": "USE [ReportServer] SELECT c.[Name] as reportname ,e.InstanceName ,e.ItemPath ,e.UserName as userExec ,e.RequestType --Interactive or Subscription ,e.Parameters ,e.ItemAction --Render or Sort ,e.TimeStart ,e.TimeEnd ,e.TimeDataRetrieval ,e.TimeProcessing ,e.TimeRendering ,e.Source ,e.Status ,e.ByteCount ,e.RowCount FROM Catalog c INNER JOIN ExecutionLog3 e ON e.ItemPath = c.Path WHERE c.name = 'SalesByYear' AND e.TimeStart >= '2020-01-01' AND e.TimeEnd < getdate() ORDER BY e.TimeStart DESC" }, { "code": null, "e": 3707, "s": 3489, "text": "I also like to have an overview of which reports are being used and which can be considered as “dead wood”. Therefore, I created a simple Power BI report, which imports data from the following query in the background:" }, { "code": null, "e": 4718, "s": 3707, "text": "USE [ReportServer] SELECT distinct a.* ,l.UserName FROM( SELECT c.[name] as reportName ,SUBSTRING(SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)),0,CHARINDEX('/',SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)))) Folder ,CASE(RequestType) WHEN 0 THEN 'Interactive' WHEN 1 THEN 'Subscription' WHEN 2 THEN 'Refresh Cache' ELSE 'Unknown' END AS RequestType ,MAX(l.TimeStart) lastRunDate FROM Catalog c INNER JOIN ExecutionLogStorage l ON l.ReportID = c.ItemID WHERE c.Type NOT IN (1,3,5,8) AND l.ReportAction IN(1,13) GROUP BY c.[name] ,SUBSTRING(SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)),0,CHARINDEX('/',SUBSTRING(path, CHARINDEX('/', path) + 1, LEN(path)))) ,CASE(RequestType) WHEN 0 THEN 'Interactive' WHEN 1 THEN 'Subscription' WHEN 2 THEN 'Refresh Cache' ELSE 'Unknown' END HAVING MAX(l.TimeStart) < getdate() - 90 ) a INNER JOIN ExecutionLogStorage l ON l.TimeStart = a.lastRunDate" }, { "code": null, "e": 4976, "s": 4718, "text": "This query returns a list of reports that were not run in the last 90 days. Of course, you can adjust the date range according to your needs. In any case, you can refer to this article and check all the different information you can obtain using these DMVs." }, { "code": null, "e": 5042, "s": 4976, "text": "So, here is what I’ve created in Power BI to visualize this data:" }, { "code": null, "e": 5189, "s": 5042, "text": "This page shows me the total number of executions for the specific report in the selected time period, and also some additional info on the right." }, { "code": null, "e": 5277, "s": 5189, "text": "The next page gives me an overview per user, but also per folders on the Report Server:" }, { "code": null, "e": 5412, "s": 5277, "text": "Finally, the most useful for me is to check which reports are rarely used. The following report page helps me to identify those items:" }, { "code": null, "e": 5695, "s": 5412, "text": "Even though Power BI Service gives you ready-made solution for examining usage metrics, there are still lot of us working with Power BI Report Server. Therefore, I believe that having report similar to this one can help you better understand who, when and how, running your reports!" }, { "code": null, "e": 5715, "s": 5695, "text": "Thanks for reading!" }, { "code": null, "e": 5763, "s": 5715, "text": "Become a member and read every story on Medium!" } ]
TypeScript - String slice()
This method extracts a section of a string and returns a new string. string.slice( beginslice [, endSlice] ); beginSlice − The zero-based index at which to begin extraction. beginSlice − The zero-based index at which to begin extraction. endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string. endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string. If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1. var str = "Apples are round, and apples are juicy."; var sliced = str.slice(3, -2); console.log(sliced); On compiling, it will generate the same code in JavaScript. Its output is as follows − les are round, and apples are juic 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2117, "s": 2048, "text": "This method extracts a section of a string and returns a new string." }, { "code": null, "e": 2159, "s": 2117, "text": "string.slice( beginslice [, endSlice] );\n" }, { "code": null, "e": 2223, "s": 2159, "text": "beginSlice − The zero-based index at which to begin extraction." }, { "code": null, "e": 2287, "s": 2223, "text": "beginSlice − The zero-based index at which to begin extraction." }, { "code": null, "e": 2400, "s": 2287, "text": "endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string." }, { "code": null, "e": 2513, "s": 2400, "text": "endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string." }, { "code": null, "e": 2623, "s": 2513, "text": "If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1." }, { "code": null, "e": 2731, "s": 2623, "text": "var str = \"Apples are round, and apples are juicy.\"; \nvar sliced = str.slice(3, -2); \nconsole.log(sliced);\n" }, { "code": null, "e": 2791, "s": 2731, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2818, "s": 2791, "text": "Its output is as follows −" }, { "code": null, "e": 2854, "s": 2818, "text": "les are round, and apples are juic\n" }, { "code": null, "e": 2887, "s": 2854, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2901, "s": 2887, "text": " Antonio Papa" }, { "code": null, "e": 2934, "s": 2901, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2948, "s": 2934, "text": " Haider Malik" }, { "code": null, "e": 2983, "s": 2948, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3003, "s": 2983, "text": " Skillbakerystudios" }, { "code": null, "e": 3036, "s": 3003, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 3050, "s": 3036, "text": " Sean Bradley" }, { "code": null, "e": 3085, "s": 3050, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3101, "s": 3085, "text": " TELCOMA Global" }, { "code": null, "e": 3134, "s": 3101, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 3154, "s": 3134, "text": " Christopher Frewin" }, { "code": null, "e": 3161, "s": 3154, "text": " Print" }, { "code": null, "e": 3172, "s": 3161, "text": " Add Notes" } ]
PyGTK - Quick Guide
PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available. PyQt is a Python port of QT library. Our PyQt tutorial can be found here. Similarly, wxPython toolkit is Python binding for wxWidgets, another popular cross-platform GUI library. Our wxPython tutorial is available here. GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating graphical user interfaces. Offering a complete set of widgets, GTK+ is suitable for projects ranging from small one-off tools to complete application suites. GTK+ has been designed from the ground up to support a wide range of languages. PyGTK is a Python wrapper for GTK+. GTK+ is built around the following four libraries − Glib − A low-level core library that forms the basis of GTK+. It provides data structure handling for C. Glib − A low-level core library that forms the basis of GTK+. It provides data structure handling for C. Pango − A library for layout and rendering of text with an emphasis on internationalization. Pango − A library for layout and rendering of text with an emphasis on internationalization. Cairo − A library for 2D graphics with support for multiple output devices (including the X Window System, Win32) Cairo − A library for 2D graphics with support for multiple output devices (including the X Window System, Win32) ATK − A library for a set of interfaces providing accessibility tools such as screen readers, magnifiers, and alternative input devices. ATK − A library for a set of interfaces providing accessibility tools such as screen readers, magnifiers, and alternative input devices. PyGTK eases the process and helps you create programs with a graphical user interface using the Python programming language. The underlying GTK+ library provides all kinds of visual elements and utilities for it to develop full-featured applications for the GNOME Desktop. PyGTK is a cross-platform library. It is a free software distributed under the LGPL license. PyGTK is built around GTK + 2.x. In order to build applications for GTK +3, PyGObject bindings are also available. The installation of PyGTK for Microsoft Windows involves the following steps − Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution) Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution) Step 2 − Download and install GTK+ runtime. Step 2 − Download and install GTK+ runtime. Step 3 − Download and install GTK+ runtime −https://ftp.gnome.org Step 3 − Download and install GTK+ runtime −https://ftp.gnome.org Step 4 − It is also recommended that you download PyCairo and PyGobject modules from the following URLs − https://ftp.gnome.org https://ftp.gnome.org/pub Step 4 − It is also recommended that you download PyCairo and PyGobject modules from the following URLs − https://ftp.gnome.org https://ftp.gnome.org/pub Step 5 − For convenience, all-in-one installer which handles all of the PyGTK dependencies is also available. Download and install the latest all-in-one installer for Windows from the following URL − https://ftp.gnome.org/pub/GNOME Step 5 − For convenience, all-in-one installer which handles all of the PyGTK dependencies is also available. Download and install the latest all-in-one installer for Windows from the following URL − https://ftp.gnome.org/pub/GNOME PyGTK is included in most Linux distributions (including Debian, Fedora, Ubuntu,RedHat etc); the source code can also be downloaded and compiled from the following URL https://ftp.gnome.org/pub/GNOME/sources/pygtk/2.24/ Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code. import gtk The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window. class PyApp(gtk.Window): Define the constructor and call the show_all() method of the gtk.window class. def __init__(self): super(PyApp, self).__init__() self.show_all() We now have to declare the object of this class and start an event loop by calling its main() method. PyApp() gtk.main() It is recommended we add a label “Hello World” in the parent window. label = gtk.Label("Hello World") self.add(label) The following is a complete code to display “Hello World”− import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_default_size(300,200) self.set_title("Hello World in PyGTK") label = gtk.Label("Hello World") self.add(label) self.show_all() PyApp() gtk.main() The implementation of the above code will yield the following output − The PyGTK module contains various widgets. gtk.Object class acts as the base class for most of the widgets as well as for some non-widget classes. The toplevel window for desktop applications using PyGTK is provided by gtk.Window class. The following table lists the important widgets and their functions − gtk.Widget This is a gtk.base class for all PyGTK widgets. gtk.Widget provides a common set of methods and signals for the widgets. gtk.Window This is a toplevel window that holds one child widget. gtk.Window is a display area decorated with a title bar, and items to allow the user to close, resize and move the window. gtk.Button This is a pushbutton widget that issues a signal when clicked. gtk.Button is usually displayed as a pushbutton with a text label and is generally used to attach a callback function. gtk.Entry This is a single line text entry widget. gtk.Label This widget displays a limited amount of read-only text. gtk.ButtonBox This is a base class for widgets that contains multiple buttons. gtk.HBox This is a container that organizes its child widgets into a single horizontal row. gtk.VBox This is a container that organizes its child widgets into a single column. gtk.Fixed This is a container that can place child widgets at fixed positions and with fixed sizes, given in pixels. gtk.Layout This provides infinite scrollable area containing child widgets and custom drawing. gtk.MenuItem This widget implements the appearance and behavior of menu items. The derived widget subclasses of the gtk.MenuItem are the only valid children of menus. When selected by a user, they can display a popup menu or invoke an associated function or method gtk.Menu This is a dropdown menu consisting of a list of MenuItem objects which can be navigated and activated by the user to perform application functions. gtk.MenuBar This displays the menu items horizontally in an application window or dialog. gtk.ComboBox This widget is used to choose from a list of items. gtk.Scale This is a horizontal or vertical slider control to select a numeric value. gtk.Scrollbar This displays a horizontal or vertical scrollbar. gtk.ProgressBar This is used to display the progress of a long running operation. gtk.Dialog This displays a popup window for user information and action. gtk.Notebook This widget is a container whose children are overlapping pages that can be switched between using tab labels. gtk.Paned This is a base class for widgets with two panes, arranged either horizontally or vertically. Child widgets are added to the panes of the widget. The division between the two children can be adjusted by the user. gtk.TextView This widget displays the contents of a TextBuffer object. gtk.Toolbar This container holds and manages a set of buttons and widgets in a horizontal or vertical bar. gtk.TreeView This widget displays the contents of standard TreeModel (ListStore, TreeStore, TreeModelSort) gtk.DrawingArea This widget helps in creating custom user interface elements. gtk.DrawingArea is essentially a blank widget containing a window that you can draw on. gtk.Calendar This widget displays a calendar and allows the user to select a date. gtk.Viewport This widget displays a portion of a larger widget. An object of the gtk.Window class provides a widget that users commonly think of as a Wwindow. This widget is a container hence, it can hold one child widget. It provides a displayable area decorated with title bar and resizing controls. gtk.Window class has the following constructor − gtk.Window(type) Type paramter takes one of the following values − Some of the important methods of the gtk.Window class are listed below − set_title(string) This sets the "title" property of the gtk.window to the value specified by the title. The title of a window will be displayed in its title bar. get_title() This returns the title of a window if set. set_position() This sets the position of window. The predefined position constants are − gtk.WIN_POS_NONE gtk.WIN_POS_NONE gtk.WIN_POS_CENTER gtk.WIN_POS_CENTER gtk.WIN_POS_MOUSE gtk.WIN_POS_MOUSE gtk.WIN_POS_CENTER_ALWAYS gtk.WIN_POS_CENTER_ALWAYS gtk.WIN_POS_CENTER_ON_PARENT gtk.WIN_POS_CENTER_ON_PARENT set_focus() This sets the widget specified to be the focus widget for the window. set_resizable() This is true by default. set_resizable() helps the user to set the size of a window. set_decorated() This is true by default. If false, the title bar and the resizing controls of window will be disabled. set_modal() If true, window becomes modal and the interaction with other windows is prevented. This is used for the Dialog widgets. set_default_size() This sets the default size of the window to the specified width and height in pixels. The gtk.Window widget emits the following signals − The gtk.Button widget is usually displayed as a pushbutton with a text label. It is generally used to attach a callback function or method that is called when the button is clicked. The gtk.Button class has the following constructor − gtk.Button(label = None, stock = None, use_underline = True) Wherein, Label − The text to be displayed by the button label Label − The text to be displayed by the button label Stock − The stock id identifying the stock image and text to be used in the button. Default is None. Stock − The stock id identifying the stock image and text to be used in the button. Default is None. Underline − If True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator. Underline − If True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator. Some of the predefined constants for stock parameter are − STOCK_OK STOCK_STOP STOCK_YES STOCK_NO STOCK_QUIT STOCK_CANCEL STOCK_CLOSE The Button class has the following important methods − set_label() This sets the text of the button label to label. This string is also used to select the stock item if the "use_stock" property is True. get_label() This retrieves the text from the label of the button set_focus_on_click() If True, the button grabs focus when clicked with the mouse. set_alignment() This is the horizontal and vertical alignment of the child widget. The value ranges from 0.0 to 1.0. set_image() This sets the image property to the value of image. The "gtkbutton-images" property should be set to True. The following signals are emitted by the Button widget − A Label widget is useful to display non-editable text. Label is used by many other widgets internally. For example, Button has a label to show text on the face. Similarly, MenuItem objects have a label. A label is a windowless object, so it cannot receive events directly. Label class has a simple constructor − gtk.Label(str = None) The following useful methods can be used with Label object − set_text() This sets new text as label get_text() This returns text from label set_use_underline() If true, an underscore in the text indicates the next character should be used for the mnemonic accelerator key. set_justify This sets the alignment of the lines in the text of the label relative to each other. Possible values are – gtk.JUSTIFY_LEFT, gtk.JUSTIFY_RIGHT, gtk.JUSTIFY_CENTER, and gtk.JUSTIFY_FILL. Set_line_wrap() If true, the line will be wrapped set_selectable() If true, the text in the label can be selected for copy-paste set_width_chars() This sets the width of a label The following signals are emitted by label widget − Entry widget is a single-line text entry widget. If the entered text is longer than the allocation of the widget, the widget will scroll so that the cursor position is visible. Entry field can be converted in password mode using set_visibility() method of this class. Entered text is substituted by character chosen by invisible_char() method, default being '*'. The Entry class has the following constructor − gtk.Entry(max = 0) Here, max stands for maximum length of entry field in characters. The parameter takes a numeric value (0-65536). The following table shows the important methods of an Entry class − set_visibility(visible) If false, the contents are obscured by replacing the characters with the default invisible character — '*' set_invisible_char(char) The default '*' characters in the entry field are replaced by char set_max_length(x) This sets the "max-length" property to the value of x. (0-65536) set_text(str) This sets the "text" property to the value of str. The string in str replaces the current contents of the entry. get_text() This returns the value of the "text" property which is a string containing the contents of the entry. set_alignment() This sets the "xalign" property to the value of xalign. set_alignment() controls the horizontal positioning of the contents in the Entry field. The following signals are emitted by entry widget − Unlike a console mode application, which is executed in a sequential manner, a GUI-based application is event driven. The gtk.main() function starts an infinite loop. Events occurring on the GUI are transferred to appropriate callback functions. Each PyGTK widget, which is derived from the GObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a callback function. Some signals are inherited by the widget, whereas some signals are widget specific. For example, "toggled" signal is emitted by the toggleButton widget. A signal handler is set up by invoking the connect() method of the gtk.widget class. handler_id = object.connect(name, func, func_data) The first argument, name, is a string containing the name of the signal you wish to catch. The first argument, name, is a string containing the name of the signal you wish to catch. The second argument, func, is the call back function you wish to be called when it is caught. The second argument, func, is the call back function you wish to be called when it is caught. The third argument, func_data, the data you wish to pass to this function. The third argument, func_data, the data you wish to pass to this function. The handler id, which is used to uniquely identify the callback method. The handler id, which is used to uniquely identify the callback method. For example, to invoke onClicked() function when a button is clicked, use the following syntax − btn.connect("clicked",onClicked,None) The onClicked() function is defined as − def onClicked(widget, data=None): If the callback method is an object method, it receives self as an additional argument − def onClicked(self, widget, data=None): In the following example, a Button is added to gtk.Window. “Hello World” message is printed when the button is clicked. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Hello World in PyGTK") self.set_default_size(400,300) self.set_position(gtk.WIN_POS_CENTER) self.label = gtk.Label("Enter name") self.entry = gtk.Entry() self.btn = gtk.Button("Say Hello") self.btn.connect("clicked",self.hello) fixed = gtk.Fixed() fixed.put(self.label, 100,100) fixed.put(self.entry, 100,125) fixed.put(self.btn,100,150) self.add(fixed) self.show_all() def hello(self,widget): print "hello",self.entry.get_text() PyApp() gtk.main() Run the above code from Python prompt. The following output will be displayed − When the button is pressed, the following output is displayed on the console − Hello TutorialsPoint In addition to the signal mechanism, window system events can also be connected to callback functions. Window resizing, key press, scroll event etc. are some of common window system events. These events are reported to application's main loop. From there, they are passed along via signals to the callback functions. Some of the system events are listed below − button_press_event button_release_event scroll_event motion_notify_event delete_event destroy_event expose_event key_press_event key_release_event The connect() method is used to associate the event with callback function following the syntax − Object.connect(name, function, data) Here, name stands for the string corresponding to the name of event which is to be captured. And, function is name of the callback function that is to be called when an event occurs. Data is the argument to be passed on to the callback function. Hence, the following code connects a Button widget and captures the button_press event − self.btn.connect("button_press_event", self.hello) The following will be the Prototype of hello() function − def hello(self,widget,event): The following is the code for button event handler − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Hello World in PyGTK") self.set_default_size(400,300) self.set_position(gtk.WIN_POS_CENTER) self.label = gtk.Label("Enter name") self.entry = gtk.Entry() self.btn = gtk.Button("Say Hello") self.btn.connect("button_press_event", self.hello) fixed = gtk.Fixed() fixed.put(self.label, 100,100) fixed.put(self.entry, 100,125) fixed.put(self.btn,100,150) self.add(fixed) self.show_all() def hello(self,widget,event): print "hello",self.entry.get_text() PyApp() gtk.main() When you run the above code, it displays the following output on the console − Hello TutorialsPoint PyGTK library provides different container classes to control the placement of widgets inside a window. The easiest way is to use a fixed container class and place a widget inside it by specifying its absolute coordinates measured in pixels. Let us now follow these steps − Step 1 − Declare an object of the fixed class fixed = gtk.Fixed() Step 2 − Create a button widget and add it to the fixed container by using put() method which needs x and y coordinates. Here, the button will be placed at (100,100) position. btn = gtk.Button("Hello") fixed.put(btn, 100,100) Step 3 − You can place multiple controls in the fixed container. And, add it to the top-level window and invoke the show_all() method self.add(fixed) self.show_all() This Absolute Layout, however, is not suitable because of the following reasons − The position of the widget does not change even if the window is resized. The appearance may not be uniform on different display devices with different resolutions. Modification in the layout is difficult as it may need redesigning of the entire form. The following is the original window − The following is the resized window − The position of the button is unchanged here. PyGTK API provides container classes for enhanced management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are − Widgets inside the window are automatically resized. Ensures uniform appearance on display devices with different resolutions. Adding or removing widget dynamically is possible without having to redesign. gtk.Container acts as the base class for the following classes − gtk.ButtonBox gtk.Box gtk.Alignment gtk.EventBox gtk.Table The gtk.Box class is an abstract class defining the functionality of a container in which widgets are placed in a rectangular area. gtk.HBox and gtk.VBox widgets are derived from it. Child widgets in gtk.Hbox are arranged horizontally in the same row. On the other hand, child widgets of gtk.VBox are arranged vertically in the same column. gtk.Box class uses the following constructor − gtk.Box(homogenous = True, spacing = 0) The homogenous property is set to True by default. As a result, all child widgets are given equal allocation. gtk.Box uses the packing mechanism to place child widgets in it with reference to a particular position, either with reference to start or end. pack_start() method places widgets from start to end. On the contrary, the pack_end() method puts widgets from end to start. Alternatively, you can use the add() method which is similar to pack_start(). The following methods are available for gtk.HBox as well as gtk.VBox − gtk_box_pack_start () gtk_box_pack_start () gtk_box_pack_end () gtk_box_pack_end () This method adds child to the box, packed with reference to the start of box − pack_start(child, expand = True, fill = True, padding = 0) The following are the parameters − child − This is the widget object to be added to box child − This is the widget object to be added to box expand − This is set to True if child is to be given extra space in the box. Extra space is divided between all child widgets. expand − This is set to True if child is to be given extra space in the box. Extra space is divided between all child widgets. fill − If True, extra space will be allocated to child. Otherwise, this parameter is used as padding. fill − If True, extra space will be allocated to child. Otherwise, this parameter is used as padding. padding − This is the space in pixels between widgets in the box. padding − This is the space in pixels between widgets in the box. This adds child to the box, packed with reference to the end of the box. pack_end (child, expand = True, fill = True, padding = 0) The following are the parameters − child − This is the widget object to be added child − This is the widget object to be added expand − This is set to True if child is to be given extra space in the box. This extra space is divided between all child widgets. expand − This is set to True if child is to be given extra space in the box. This extra space is divided between all child widgets. fill − If True, extra space will be allocated to child otherwise used as padding. fill − If True, extra space will be allocated to child otherwise used as padding. padding − This is the space in pixels between the widgets in the box. padding − This is the space in pixels between the widgets in the box. set_spacing (spacing) is the function that sets the number of pixels to place between the children of the box. The method add (widget) is inherited from the gtk.Container class. It adds widget to the container. This method can be used instead of the pack_start() method. In the example given below, the toplevel window contains a vertical box (gtk.VBox object box). It in turn has a VBox object vb and HBox object hb. In the upper box, a label, an entry widget and a button are placed vertically. In the lower box, another set of label, entry and button are placed vertically. Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Box demo") box = gtk.VBox() vb = gtk.VBox() lbl = gtk.Label("Enter name") vb.pack_start(lbl, expand = True, fill = True, padding = 10) text = gtk.Entry() vb.pack_start(text, expand = True, fill = True, padding = 10) btn = gtk.Button(stock = gtk.STOCK_OK) vb.pack_start(btn, expand = True, fill = True, padding = 10) hb = gtk.HBox() lbl1 = gtk.Label("Enter marks") hb.pack_start(lbl1, expand = True, fill = True, padding = 5) text1 = gtk.Entry() hb.pack_start(text1, expand = True, fill = True, padding = 5) btn1 = gtk.Button(stock = gtk.STOCK_SAVE) hb.pack_start(btn1, expand = True, fill = True, padding = 5) box.add(vb) box.add(hb) self.add(box) self.show_all() PyApp() gtk.main() The above code will produce the following output − The ButtonBox class in gtk API serves as a base class for containers to hold multiple buttons either horizontally or vertically. Two subclasses HButtonBox and VButtonBox are derived from the ButtonBox class, which itself is a subclass of gtk.Box class. A button box is used to provide a consistent layout of buttons throughout an application. It provides one default layout and a default spacing value that are persistent across all widgets. The set_spacing() method of the gtk.Box class can be used to change the default spacing between buttons in the button box. The default layout of buttons can be changed by the set_default() method. The possible values of the button layout are − gtk.BUTTONBOX_SPREAD gtk.BUTTONBOX_SPREAD gtk.BUTTONBOX_EDGE gtk.BUTTONBOX_EDGE gtk.BUTTONBOX_START gtk.BUTTONBOX_START gtk.BUTTONBOX_END. gtk.BUTTONBOX_END. In the following example, a VBox object inside the toplevel window internally contains one VButtonBox object and one HButtonBox object, each containing two buttons, arranged vertically and horizontally respectively. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Button Box demo") self.set_size_request(200,100) self.set_position(gtk.WIN_POS_CENTER) vb = gtk.VBox() box1 = gtk.VButtonBox() btn1 = gtk.Button(stock = gtk.STOCK_OK) btn2 = gtk.Button(stock = gtk.STOCK_CANCEL) box1.pack_start(btn1, True, True, 0) box1.pack_start(btn2, True, True, 0) box1.set_border_width(5) vb.add(box1) box2 = gtk.HButtonBox() btn3 = gtk.Button(stock = gtk.STOCK_OK) btn4 = gtk.Button(stock = gtk.STOCK_CANCEL) ent = gtk.Entry() box2.pack_start(btn3, True, True, 0) box2.pack_start(btn4, True, True, 0) box1.set_border_width(5) vb.add(box2) self.add(vb) self.show_all() PyApp() gtk.main() The above code generates the following output − This widget proves useful in controlling alignment and size of its child widgets. It has four properties called xalign, yalign, xscale and yscale. The scale properties specify how much of free space will be used by the child widgets. The align properties areused to place the child widget within available area. All four properties take up a float value between 0 and 1.0. If xscale and yscale property is set to 0, it means that widget absorbs none of free space and if set to 1, widget absorbs maximum free space horizontally or vertically respectively. The xalign and yalign property if set to 0, means that there will be no free space to the left or above widget. If set to 1, there will be maximum free space to left or above the widget. The gtk.alignment class has the following constructor − gtk.alignment(xalign = 0.0, yalign = 0.0, xscale = 0.0, yscale = 0.0) Where, xalign − Is the fraction of the horizontal free space to the left of the child widget. xalign − Is the fraction of the horizontal free space to the left of the child widget. yalign − Is the fraction of vertical free space above the child widget. yalign − Is the fraction of vertical free space above the child widget. xscale − Is is the fraction of horizontal free space that the child widget absorbs. xscale − Is is the fraction of horizontal free space that the child widget absorbs. yscale − Is is the fraction of vertical free space that the child widget absorbs. yscale − Is is the fraction of vertical free space that the child widget absorbs. The following code demonstrates the use of gtk.alignment widget. A Vbox in the toplevel window has an upper Vbox and lower Hbox placed in it. In the upper vertical box, a label and an Entry widget are placed such that towards the left, 50% of space is kept free and more than 25% of this is occupied by assigning 0.5 xalign and 0.25 to yalign properties. In the lower HBox, all the available free space is on the left side. This is achieved by assigning 1 to xalign property. Hence, two buttons in the horizontal box appear right aligned. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Alignment demo") self.set_size_request(400,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) vb = gtk.VBox() hbox = gtk.HBox(True, 3) valign = gtk.Alignment(0.5,0.25, 0, 0) lbl = gtk.Label("Name of student") vb.pack_start(lbl, True, True, 10) text = gtk.Entry() vb.pack_start(text, True, True, 10) valign.add(vb) vbox.pack_start(valign) ok = gtk.Button("OK") ok.set_size_request(70, 30) close = gtk.Button("Close") hbox.add(ok) hbox.add(close) halign = gtk.Alignment(1, 0, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, False, 3) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The above code produces the following output − Some widgets in PyGTK tool kit do not have their own window. Such windowless widgets cannot receive event signals. Such widgets, for example a label, if put inside an eventbox can receive signals. EventBox is an invisible container that provides window to windowless widgets. It has a simple constructor without any argument − gtk.EventBox() In the following example, two widgets of the gtk.EventBox are placed in the toplevel window. Inside each eventbox, a label is added. The eventbox is now connected to a callback function to process the button_press_event on it. As the eventbox itself is invisible, effectively the event occurs on the embedded label. Hence, as and when we click on any label, the corresponding callback function is invoked. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("EventBox demo") self.set_size_request(200,100) self.set_position(gtk.WIN_POS_CENTER) fixed = gtk.Fixed() event1 = gtk.EventBox() label1 = gtk.Label("Label 1") event1.add(label1) fixed.put(event1, 80,20) event1.connect("button_press_event",self.hello1) event2 = gtk.EventBox() label2 = gtk.Label("Label 2") event2.add(label2) event2.connect("button_press_event",self.hello2) fixed.put(event2, 80,70) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() def hello1(self, widget, event): print "clicked label 1" def hello2(self, widget, event): print "clicked label 2" PyApp() gtk.main() The above code generates the following output − When Label 1 is clicked on the console, the message "clicked label 1" gets printed. Similarly, when Label 2 is clicked on, "clicked label 2" message is printed. The gtk.Layout is a container widget similar to gtk.Fixed. Widgets are placed in Layout widget by specifying absolute coordinates. However, the Layout differs from fixed widget in the following ways − The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer. The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer. A gtk.DrawingArea widget can be enclosed in a layout container. The DrawingArea is a canvas on which 2D elements like line, rectangle etc. can be drawn. A gtk.DrawingArea widget can be enclosed in a layout container. The DrawingArea is a canvas on which 2D elements like line, rectangle etc. can be drawn. In order to put the Layout container in the toplevel window of lesser dimensions, it can be associated with the scrollbars or can be placed in a ScrolledWindow. In order to put the Layout container in the toplevel window of lesser dimensions, it can be associated with the scrollbars or can be placed in a ScrolledWindow. The gtk.Layout class has the following constructor − gtk.Layout(hadjustment = None, vadjustment = None) The hadjustment and vadjustment properties represent an object having an adjustable bounded value. The following table lists out the frequently used methods of the layout − The Layout object emits the set_scroll_adjustment signal when the adjustments associated with it are changed. In the following example, a Label is paced at the centre of a Layout container, which in turn is to be placed in a toplevel window of smaller size. Hence, it is first added to a ScrolledWindow and the ScrolledWindow is then added to the main window. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("layout") self.set_size_request(300,200) self.set_position(gtk.WIN_POS_CENTER) sc = gtk.ScrolledWindow() lo = gtk.Layout() lo.set_size(400,400) button = gtk.Button("Press Me") lo.put(button, 125,200) sc.add(lo) self.add(sc) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − ComboBox is a powerful and popular widget in any GUI toolkit. It provides a dropdown list of items from which a user can choose. The gtk.ComboBox widget implements the CellLayout interface and provides a number of methods to manage the display of items. The object of gtk.ComboBox class is associated with a ListSore, which is a list model that can be used with widgets that display collection of items. Items are added to ListStore with the append() method. Further, a CellRendererText object is created and packed into the combobox. Follow these steps to set up a combobox. combobox = gtk.ComboBox() store = gtk.ListStore(gobject.TYPE_STRING) cell = gtk.CellRendererText() combobox.pack_start(cell) combobox.add_attribute(cell, 'text', 0) PyGTK offers a convenience method — gtk.combo_box_new_text() to create a combo box instead of using a list store. Associated convenience methods append_text(), prepend_text(), insert_text() and remove_text() are used to manage the combo boxcontents. gtk.ComboBox class has the following methods − set_wrap_width() Sets the number of columns to be displayed in the popup table layout get_active() Returns the value of the "active" property which is the index in the model of the currently active item set_active() Sets the active item of the combo_box to the item with the model index specified set_model() Sets the model used by the combo box append_text() Appends the string specified by text to the list of strings stored in the combo box list store Insert_text() Inserts the string specified by text in the combo box gtk.ListStore at the index specified by position prepend_text() Prepends the string specified by text to the list of strings stored in the list store remove_text() Removes the string at the index specified by position in the associated liststore get_active_text() Returns the currently active string The ComboBox widget emits the following signals − Two example codes for the demonstration of ComboBox are given below. In this example, a ListStore is populated with the names of popular Python GUI toolkits and it is associated with a ComboBox widget. As a user makes a choice, the changed signal is emitted. It is connected to a callback function to display the user's choice. import pygtk pygtk.require('2.0') import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("ComboBox with ListStore") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) combobox = gtk.ComboBox() store = gtk.ListStore(str) cell = gtk.CellRendererText() combobox.pack_start(cell) combobox.add_attribute(cell, 'text', 0) fixed = gtk.Fixed() lbl = gtk.Label("select a GUI toolkit") fixed.put(lbl, 25,75) fixed.put(combobox, 125,75) lbl2 = gtk.Label("Your choice is:") fixed.put(lbl2, 25,125) self.label = gtk.Label("") fixed.put(self.label, 125,125) self.add(fixed) store.append (["PyQt"]) store.append (["Tkinter"]) store.append (["WxPython"]) store.append (["PyGTK"]) store.append (["PySide"]) combobox.set_model(store) combobox.connect('changed', self.on_changed) combobox.set_active(0) self.connect("destroy", gtk.main_quit) self.show_all() return def on_changed(self, widget): self.label.set_label(widget.get_active_text()) return if __name__ == '__main__': PyApp() gtk.main() Upon execution, the program displays the following output − The second version of the program uses the convenience method combo_box_new_text() to create a combo box and append_text() function to add strings in it. In both programs, the get_active_text() method is used to fetch user's selection and display on a label on the window. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Simple ComboBox") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) cb = gtk.combo_box_new_text() cb.connect("changed", self.on_changed) cb.append_text('PyQt') cb.append_text('Tkinter') cb.append_text('WxPython') cb.append_text('PyGTK') cb.append_text('PySide') fixed = gtk.Fixed() lbl = gtk.Label("select a GUI toolkit") fixed.put(lbl, 25,75) fixed.put(cb, 125,75) lbl2 = gtk.Label("Your choice is:") fixed.put(lbl2, 25,125) self.label = gtk.Label("") fixed.put(self.label, 125,125) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() def on_changed(self, widget): self.label.set_label(widget.get_active_text()) if __name__ == '__main__': PyApp() gtk.main() The output of this program is similar to that of the previous program. ToggleButton widget is a gtk.Button with two states — a pressed or active (or on) state and a normal or inactive (or off) state. Every time the button is pressed, the state alternates. The state of the ToggleButton can also be changed programmatically by set_active() method. To switch the state of the button, the toggled() method is also available. The gtk.ToggleButton class has the following constructor − gtk.ToggleButton(label = None, use_underline = True) Here, label is the test to be displayed on button. The use_underline property , if True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator. Some of the important methods of the gtk.ToggleButton class are given in the following table − The ToggleButton widget emits the following signal − The code given below demonstrates the use of ToggleButton widgets. Two ToggleButtons and Label widgets are placed in a VBox container. The toggled signal emitted by Button1 is connected to a callback function on_toggled(). In this function, the state of Button2 is set to True if that of Button1 is False and vice versa. if self.btn1.get_active() == True: self.btn2.set_active(False) else: self.btn2.set_active(True) It displays the instantaneous states of buttons on the Label. Observe the following code − import gtk PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Toggle Button") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() self.btn1 = gtk.ToggleButton("Button 1") self.btn1.connect("toggled", self.on_toggled) self.btn2 = gtk.ToggleButton("Button 2") self.lbl = gtk.Label() vbox.add(self.btn1) vbox.add(self.btn2) vbox.add(self.lbl) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() def on_toggled(self, widget, data = None): if self.btn1.get_active() == True: self.btn2.set_active(False) else: self.btn2.set_active(True) state = "Button1 : "+str(self.btn1.get_active())+" Button2 : "+str(self.btn2.get_active()) self.lbl.set_text(state) if __name__ == '__main__': PyApp() gtk.main() The above code generates the following output − A CheckButton widget is nothing but a ToggleButton styled as a checkbox and a label. It inherits all properties and methods from the ToggleButton class. Unlike ToggleButton where the caption is on the button's face, a CheckButton displays a small square which is checkable and has a label to its right. Constructor, methods, and signals associated with gtk.CheckButton are exactly the same as gtk.ToggleButton. The following example demonstrates the use of CheckButton widget. Two CheckButtons and a Label are placed in a VBox. The toggled signal of the first CheckButton is connected to the on_checked() method which sets the state of the second button to True if that of the first is false and vice versa. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Check Button") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() self.btn1 = gtk.CheckButton("Button 1") self.btn1.connect("toggled", self.on_checked) self.btn2 = gtk.CheckButton("Button 2") self.btn2.connect("toggled", self.on_checked) self.lbl = gtk.Label() vbox.add(self.btn1) vbox.add(self.btn2) vbox.add(self.lbl) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() def on_checked(self, widget, data = None): state = "Button1 : "+str(self.btn1.get_active())+" Button2 : "+str(self.btn2.get_active()) self.lbl.set_text(state) if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − A single RadioButton widget offers functionality similar to CheckButton. However, when more than one radio button is present in the same container, then a mutually exclusive choice is available for the user to choose from one of the available options. If every radio button in the container belongs to the same group, then as one is selected, others are automatically deselected. The following is a constructor of the gtk.RadioButton class − gtk.RadioButton(group = None, Label = None, unerline = None) In order to create a button group, provide group=None for the first Radio button, and for the subsequent options, provide the object of the first button as group. As in case of ToggleButton and CheckButton, the RadioButton also emits the toggled signal. In the example given below, three objects of the gtk.RadioButton widget are placed in a VBox. All of them are connected to a callback function on_selected(), to process the toggled signal. The callback function identifies the label of source RadioButton widget and displays it on the label put in the VBox. Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Radio Button") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() btn1 = gtk.RadioButton(None, "Button 1") btn1.connect("toggled", self.on_selected) btn2 = gtk.RadioButton(btn1,"Button 2") btn2.connect("toggled", self.on_selected) btn3 = gtk.RadioButton(btn1,"Button 3") btn3.connect("toggled", self.on_selected) self.lbl = gtk.Label() vbox.add(btn1) vbox.add(btn2) vbox.add(btn3) vbox.add(self.lbl) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() def on_selected(self, widget, data=None): self.lbl.set_text(widget.get_label()+" is selected") if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − A horizontal bar just below the title bar of a toplevel gtk.Window is reserved to display series of menus. It is an object of gtk.MenuBar class in PyGTK API. An object of the gtk.Menu class is added to the menu bar. It is also used to create context menu and popup menu. Each menu may contain one or more gtk.MenuItem widgets. Some of them can be a submenu.and have cascaded MenuItem buttons. The gtk.MenuBar is subclassed from the gtk.MenuShell class. It has a simple default constructor − gtk.MenuBar() To add a menu to MenuBar, the append() method of the MenuBar class is used. In order to construct a menu, create a MenuItem widget with a label which is desired to appear in menu bar and set it as submenu. For example, the following code is used to set up a File menu − menu1 = gtk.Menu() file = gtk.MenuItem("_File") file.set_submenu(menu1) Now, one or more widgets of the MenuItem class can be added in the menu. item1 = gtk.MenuItem("New") item2 = gtk.MenuItem("Open") These MenuItems are added to the Menu widget and the menu object in turn is added to the menu bar. menu1.append(item1) menu1.append(item2) mb.append(menu1) The PyGTK toolkit offers many types of MenuItem widgets. An ImageMenuItem is a menu item with an image associated with it. You can use any of the stock images by using Stock ID parameter or assign any other image by set_image() method. For example, 'New' menu item having image is created in the following way − new = gtk.ImageMenuItem(gtk.STOCK_NEW) menu1.append(new) Similarly, it is also possible to add CheckMenuItem using the following code − chk = gtk.CheckMenuItem("Checkable") menu1.append(chk) A group of radio items can also be added using this code − radio1 = gtk.RadioMenuItem(None,"Radio1") radio2 = gtk.RadioMenuItem(radio1, "Radio2") menu1.append(radio1) menu1.append(radio2) Sometimes, you may want to add a seperator line between menu items. For that purpose, the SeparatorMenuItem is also available. sep = gtk.SeparatorMenuItem() menu1.append(sep) You can also assign keyboard shortcuts to menu items. PyGTK has accelerators. Start by creating an accelerator group and attach it to the toplevel window. acgroup = gtk.AccelGroup() self.add_accel_group(acgroup) To assign shortcut, use add_accelerator() function with the following prototype − Item1.add_accelerator(signal, group, key, modifier, flags) The following are some of the predefined modifiers − SHIFT_MASK LOCK_MASK CONTROL_MASK BUTTON1_MASK BUTTON1_MASK In order to assign Ctrl+N shortcut to New Menu item, use the following syntax − new = gtk.ImageMenuItem(gtk.STOCK_NEW,acgroup) new.add_accelerator("activate", acgroup, ord('N'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) The following example demonstrates the features discussed above − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Menu Demo") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) mb = gtk.MenuBar() menu1 = gtk.Menu() file = gtk.MenuItem("_File") file.set_submenu(menu1) acgroup = gtk.AccelGroup() self.add_accel_group(acgroup) new = gtk.ImageMenuItem(gtk.STOCK_NEW,acgroup) new.add_accelerator("activate", acgroup, ord('N'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) menu1.append(new) open = gtk.ImageMenuItem(gtk.STOCK_OPEN) menu1.append(open) chk = gtk.CheckMenuItem("Checkable") menu1.append(chk) radio1 = gtk.RadioMenuItem(None,"Radio1") radio2 = gtk.RadioMenuItem(radio1, "Radio2") menu1.append(radio1) menu1.append(radio2) sep = gtk.SeparatorMenuItem() menu1.append(sep) exit = gtk.ImageMenuItem(gtk.STOCK_QUIT) menu1.append(exit) menu2 = gtk.Menu() edit = gtk.MenuItem("_Edit") edit.set_submenu(menu2) copy = gtk.ImageMenuItem(gtk.STOCK_COPY) menu2.append(copy) cut = gtk.ImageMenuItem(gtk.STOCK_CUT) menu2.append(cut) paste = gtk.ImageMenuItem(gtk.STOCK_PASTE) menu2.append(paste) mb.append(file) mb.append(edit) vbox = gtk.VBox(False, 2) vbox.pack_start(mb, False, False, 0) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() if __name__ == '__main__': PyApp() gtk.main() The above code will produce the following output − Toolbar class is inherited from the gtk.Container class. It holds and manages a set of buttons and other widgets. One or more horizontal strips of buttons are normally seen just below the menu bar in a top level window. The Toolbar can also be put in a detachable window called HandleBox. By default, the buttons in the gtk.Toolbar widget are laid horizontally. Vertical toolbar can be set up by setting the orientation property to gtk.ORIENTATION_VERTICAL. The toolbar can be configured to show buttons with icons, text, or both. The style enumerators are − A Toolbar widget is set up using the following constructor − bar = gtk.Toolbar() The constituents of Toolbar are instances of the gtk.ToolItem. The items can be ToolButton, RadioToolButton, ToggleToolButton, or SeparatorToolItem. In order to assign icon to the ToolItem object, images with predefined stock_ID can be used or a custom image can be assigned by the set_image() method. The following examples show how to construct different ToolItems − newbtn = gtk.ToolButton(gtk.STOCK_NEW) rb1 = gtk.RadioToolButton(None,gtk.STOCK_JUSTIFY_LEFT) rb2 = gtk.RadioToolButton(rb1,gtk.STOCK_JUSTIFY_RIGHT) Note that multiple radio buttons are put in the same group. sep = gtk.SeparatorToolItem() These items are put in the toolbar by calling its insert method. gtk.Toolbar.insert(item, index) For example, bar.insert(new,0) You can also assign a tooltip to the ToolButton using the set_tooltip_text() nethod. For example, New tooltip is assigned to the new ToolButton. newbtn.set_tooltip_text("New") The following code shows a toplevel window with a tool bar set up to contain normal tool item, radio items and a separator item. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Toolbar Demo") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) toolbar = gtk.Toolbar() toolbar.set_style(gtk.TOOLBAR_ICONS) toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL) newbtn = gtk.ToolButton(gtk.STOCK_NEW) newbtn.set_tooltip_text("New") openbtn = gtk.ToolButton(gtk.STOCK_OPEN) savebtn = gtk.ToolButton(gtk.STOCK_SAVE) sep = gtk.SeparatorToolItem() rb1 = gtk.RadioToolButton(None,gtk.STOCK_JUSTIFY_LEFT) 53 rb2 = gtk.RadioToolButton(rb1,gtk.STOCK_JUSTIFY_RIGHT) prv = gtk.ToggleToolButton(gtk.STOCK_PRINT_PREVIEW) quitbtn = gtk.ToolButton(gtk.STOCK_QUIT) toolbar.insert(newbtn, 0) toolbar.insert(openbtn, 1) toolbar.insert(savebtn, 2) toolbar.insert(sep, 3) toolbar.insert(rb1,4) toolbar.insert(rb2,5) toolbar.insert(prv,6) toolbar.insert(quitbtn, 7) quitbtn.connect("clicked", gtk.main_quit) vbox = gtk.VBox(False, 2) vbox.pack_start(toolbar, False, False, 0) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() def on_checked(self, widget, data = None): state = "Button1 : "+str(self.btn1.get_active())+" Button2 : "+str(self.btn2.get_active()) self.lbl.set_text(state) if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − Some widgets in PyGTK toolkit are such that their properties can be adjusted over a specified range by the user by using a mouse or a keyboard. A widget like Viewport is used to display some adjustable portion of a large data, for example, a multiline text in TextView control. PyGTK uses gtk.Adjustment object to be used in association with such widgets so that user adjustments are passed to some callback function for processing. An Adjustment object contains lower and upper bounds of an adjustable value and its increment step paramaters. When parameters of adjustment object changes, it emits changed or value_changed signals. The following is the constructor of the gtk.Adjustment class − gtk.Adjustment(value = 0, lower = 0, upper = 0, step_incr = 0, page_incr = 0, page_size = 0) The meaning of each of the attributes in the constructor is as follows − The following signals are emitted by the Adjustment object − As mentioned above, the Adjustment object is not a physical widget. Rather, it is used in association with the other widgets using which its attributes get changed. Range widgets are used along with the Adjustment object. This class acts as a base class for widgets which let the user to adjust the value of a numeric parameter between the lower and upper bounds. Scale widgets (gtk.Hscale and gtk.Vscale) and scrollbar widgets (gtk.HScrollbar and gtk.VScrollbar) derive functionality from the Range class. These Range widgets work in conjunction with the Adjustment object. The following important functions of the gtk.Range class are implemented by the Scale and Scrollbar widgets − set_update_policy() − This sets the "update-policy" property to the value. The policy has the following values − set_update_policy() − This sets the "update-policy" property to the value. The policy has the following values − set_adjustment() − This sets the "adjustment" property. The Adjustment object is used as model for the Range object. set_adjustment() − This sets the "adjustment" property. The Adjustment object is used as model for the Range object. set_increments() − This sets the step and page sizes for the range. set_increments() − This sets the step and page sizes for the range. set_range() − This sets the minimum and maximum allowable values for the Range widget set_range() − This sets the minimum and maximum allowable values for the Range widget set_value() − This sets the current value of the range to the value specified. set_value() − This sets the current value of the range to the value specified. The scale widget classes − (HScale and VScale) are derived from the gtk.Range class. This class acts as an abstract base class for HScale and VScale widgets. These widgets work as a slider control and select a numeric value. The following methods of this abstract class are implemented by the HScale class and the VScale class − set_digits() − This sets number of decimal places to be used to display instantaneous value of widget. set_digits() − This sets number of decimal places to be used to display instantaneous value of widget. set_draw_value() − set to True, current value will be displayed next to the slider. set_draw_value() − set to True, current value will be displayed next to the slider. set_value_pos() − This is the position at which the values are drawn. This can be either gtk.POS_LEFT, gtk.POS_RIGHT, gtk.POS_TOP or gtk.POS_BOTTOM. set_value_pos() − This is the position at which the values are drawn. This can be either gtk.POS_LEFT, gtk.POS_RIGHT, gtk.POS_TOP or gtk.POS_BOTTOM. An object of gtk.HScale class provides a horizontal slider, whereas an object of gtk.VScale class provides vertical slider. Both classes have identical constructors − gtk.HScale(Adjustment = None) gtk.VScale(Adjustment = None) The adjustment object contains many attributes that provide access to value and bounds. This class is an abstract base class for gtk.Hscrollbar and gtk.Vscrollbar widgets. Both are associated with an Adjustment object. The position of the thumb of the scrollbar is controlled by scroll adjustments. The attributes of adjustment object are used as follows − The following program shows an HScale and an HScrollbar widget placed in a VBox added to the toplevel window. Each of them is associated with an adjustment object. adj1 = gtk.Adjustment(0, 0, 101, 0.1, 1, 1) self.adj2 = gtk.Adjustment(10,0,101,5,1,1) An gtk.HScale widget is a slider control attached with adj1. Its update policy, number and position of drawing value are set up as follows − scale1 = gtk.HScale(adj1) scale1.set_update_policy(gtk.UPDATE_CONTINUOUS) scale1.set_digits(1) scale1.set_value_pos(gtk.POS_TOP) scale1.set_draw_value(True) gtk.HScrollbar provides a horizontal scrollbar. It is associated with adj2 object. Its update policy too is set to CONTINUOUS. self.bar1 = gtk.HScrollbar(self.adj2) self.bar1.set_update_policy(gtk.UPDATE_CONTINUOUS) In order to display instantaneous value of the scrollbar, 'value-changed' signal of the adjustment object — adj2 is connected to callback function on_scrolled(). The function retrieves the value property of adjustment object and displays it on a label below the scrollbar. self.adj2.connect("value_changed", self.on_scrolled) def on_scrolled(self, widget, data = None): self.lbl2.set_text("HScrollbar value: "+str(int(self.adj2.value))) Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Range widgets Demo") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) adj1 = gtk.Adjustment(0.0, 0.0, 101.0, 0.1, 1.0, 1.0) self.adj2 = gtk.Adjustment(10,0,101,5,1,1) scale1 = gtk.HScale(adj1) scale1.set_update_policy(gtk.UPDATE_CONTINUOUS) scale1.set_digits(1) scale1.set_value_pos(gtk.POS_TOP) scale1.set_draw_value(True) vb = gtk.VBox() vb.add(scale1) lbl1 = gtk.Label("HScale") vb.add(lbl1) self.bar1 = gtk.HScrollbar(self.adj2) self.bar1.set_update_policy(gtk.UPDATE_CONTINUOUS) vb.add(self.bar1) self.lbl2 = gtk.Label("HScrollbar value: ") vb.add(self.lbl2) self.adj2.connect("value_changed", self.on_scrolled) self.add(vb) self.connect("destroy", gtk.main_quit) self.show_all() def on_scrolled(self, widget, data=None): self.lbl2.set_text("HScrollbar value: "+str(int(self.adj2.value))) if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − A Dialog widget is normally used as a pop-up window on top of a parent window. The objective of a Dialog is to collect some data from the user and send it to the parent window. Dialog can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed). The Dialog widget of PyGTK library is a window split vertically. In its top section, there is a gtk.VBox in which Label or Entry Widgets are packed. The bottom section is called action_area in which one or more buttons are placed. Two areas are separated by gtk.HSeparator. gtk.Dialog class has the following constructor − dlg = gtk.Dialog (Title = None, parent = None, flags = 0, buttons = None) Where, Title − Is the text appearing in the Title bar of the Dialog widget. Title − Is the text appearing in the Title bar of the Dialog widget. Parent − Is the reference to the toplevel window from which the dialog pops up. Parent − Is the reference to the toplevel window from which the dialog pops up. Flag − Defines constants controlling operation of Dialog. The defined constants are − Flag − Defines constants controlling operation of Dialog. The defined constants are − A Button is a tuple object containing pairs of gtk.Button with a stock ID (or text) and its response IDs. The response ID can be any number or one of the predefined Response ID constants − gtk.RESPONSE_NONE gtk.RESPONSE_REJECT gtk.RESPONSE_ACCEPT gtk.RESPONSE_DELETE_EVENT gtk.RESPONSE_OK gtk.RESPONSE_CANCEL gtk.RESPONSE_CLOSE gtk.RESPONSE_YES gtk.RESPONSE_NO gtk.RESPONSE_APPLY gtk.RESPONSE_HELP The important methods of the gtk.Dialog class are given below − add_button() − Adds a button with the text specified by button_text (or a stock button, if button_text is a stock ID) in action_area. add_button() − Adds a button with the text specified by button_text (or a stock button, if button_text is a stock ID) in action_area. response() − Emits the "response" signal with the value specified in response_id response() − Emits the "response" signal with the value specified in response_id run() − Displays the dialog and returns the response_id when delete_event gets emitted. run() − Displays the dialog and returns the response_id when delete_event gets emitted. set_default_response() − Sets the last widget in the dialog's action area with the specified response_id as the default widget for the dialog. set_default_response() − Sets the last widget in the dialog's action area with the specified response_id as the default widget for the dialog. gtk.Dialog widget emits the following signals − Two buttons in action_area of Dialog widget use Stock IDs gtk.STOCK.CANCEL and gtk.STOCK_OK. They are associated with response IDs gtk. RESPONSE_REJECT and gtk. RESPONSE_ACCEPT respectively. The Dialog is closed when any button is pressed. The run() methods returns corresponding response ID which may be utilized for further processing. Following code displays a top level gtk.Window with a Button in it. When button is clicked, a Dialog appears with a label and two buttons. Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Dialog Demo") self.set_default_size(250, 200) fixed = gtk.Fixed() btn = gtk.Button("Show") btn.connect("clicked",self.show_sialog) fixed.put(btn,100,100) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() def show_sialog(self, widget, data=None): dialog = gtk.Dialog("My dialog", self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) label = gtk.Label("Simple dialog") dialog.vbox.add(label) label.show() res = dialog.run() print res dialog.destroy() if __name__ == '__main__': PyApp() gtk.main() The above code produces the following output − PyGTK API has a number of preconfigured Dialog widgets − MessageDialog AboutDialog ColorSelectionDialog FontSelectionDialog FileChooserDialog In order to demonstrate the functioning of the above standard dialog in PyGTK, a menu with a menu item each invoking a dialog when clicked, is put in a gtk.Window in the following program. The Callback functions responding to activate the signal of each menu item is listed. You can also understand the explanation provided for each type of dialog widget. Observe the following code − import gtk, pango class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Dialog Boxes") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) mb = gtk.MenuBar() menu1 = gtk.Menu() file = gtk.MenuItem("_File") file.set_submenu(menu1) msg = gtk.MenuItem("MessageDialog") menu1.append(msg) abt = gtk.MenuItem("AboutDialog") menu1.append(abt) colo = gtk.MenuItem("colorDialog") menu1.append(colo) font = gtk.MenuItem("FontSelectionDialog") menu1.append(font) fl = gtk.MenuItem("FileChooserDialog") menu1.append(fl) mb.append(file) vbox = gtk.VBox(False, 2) vbox.pack_start(mb, False, False, 0) self.add(vbox) self.text = gtk.Label("TutorialsPoint") vbox.pack_start(self.text, True, True, 0) msg.connect("activate",self.on_msgdlg) abt.connect("activate",self.on_abtdlg) font.connect("activate",self.on_fntdlg) colo.connect("activate",self.on_color) fl.connect("activate", self.on_file) self.connect("destroy", gtk.main_quit) self.show_all() def on_msgdlg(self, widget): #MessageDialog usage code def on_abtdlg(self, widget): #AboutDialog usage code def on_fntdlg(self,widget): #FontSelectionDialog usage code def on_color(self, widget): #ColorChooserDialog usage cde Def on_file(self, widget): #FileChooserDialog usage code if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − A Messagedialog widget is a Dialog window configured to display an image representing the type of message, i.e., error, question, or some informational text. A MessageDialog object is declared by using the following constructor − gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_INFO, buttons = gtk.BUTTONS_NONE, message_format = None) The following predefined message types are used to configure message dialog − A set of predefined button sets are also available for use. When the MessageBox menu item is activated, the following callback function is called and a message box pops up as an output. def on_msgdlg(self, widget): md = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error message") md.run() The above function will generate the following output − A simple way to display information about a program like its logo, name, copyright, website and license is offered by the gtk.AboutDialog widget. An about dialog is typically opened when the user selects the About option from the Help menu. All parts of the dialog are optional. The About Dialog can contain URLs and email addresses. gtk.AboutDialog offers global hooks when the user clicks URLs and email ID The following is a constructor of the gtk.AboutDialog class − dlg = gtk.AboutDialog() The following methods are used to configure the About Dialog set_program_name() − This sets the name to be displayed in the About Dialog. defaults to application_name(). set_program_name() − This sets the name to be displayed in the About Dialog. defaults to application_name(). set_version() − This sets the "version" property set_version() − This sets the "version" property set_copyright() − This sets the "copyright". If None, the copyright notice is hidden. set_copyright() − This sets the "copyright". If None, the copyright notice is hidden. set_license() − This sets the "license". If None, the license button is hidden. set_license() − This sets the "license". If None, the license button is hidden. set_website() − This sets the "website" property to the string whichg should be a valid URL. set_website() − This sets the "website" property to the string whichg should be a valid URL. set_author() − This sets the "authors" property to the list of author names displayed in the authors tab of the secondary credits dialog. set_author() − This sets the "authors" property to the list of author names displayed in the authors tab of the secondary credits dialog. set_logo() − This sets the "logo" property to the Pixbuf object. If None, the default window icon set will be used. set_logo() − This sets the "logo" property to the Pixbuf object. If None, the default window icon set will be used. When the AboutDialog menu button is clicked, the following callback function is called. This function generates the About Dialog − def on_abtdlg(self, widget): about = gtk.AboutDialog() about.set_program_name("PyGTK Dialog") about.set_version("0.1") about.set_authors("M.V.Lathkar") about.set_copyright("(c) TutorialsPoint") about.set_comments("About Dialog example") about.set_website("http://www.tutorialspoint.com") about.run() about.destroy() The above function generates the following output − The gtk.FontSelection widget allows users to select and apply the font of a particular name, size and style. The dialog has a preview box containing some text which will be displayed in selected font description, and two buttons CANCEL and OK. PyGTK API contains a Pango module which defines classes and functionality required to render high quality internationalized text. Font and text handling in gtk is supported by Pango. The pango.Font object represents a font in a system independent way. The pango.FontDescription object contains the characteristics of a font. gtk.FontSelectionDialog returns a pango.Font object. In order to apply the selected font, fontmetrics is fetched by obtaining the pango.FontDescription object from it. The following is a constructor of the FontSelectionDialog class − dlg = gtk.FontSelectionDialog(title) The following are some frequently used methods of this class − get_font_name() − This returns a string containing the currently selected font name or None if no font name is selected. get_font_name() − This returns a string containing the currently selected font name or None if no font name is selected. set_font_name() − This sets the current font set_font_name() − This sets the current font set_preview_text() − This sets the text in the preview area entry set_preview_text() − This sets the text in the preview area entry The selected font is applied to the text in a widget using the modify_font() method. When FontSelectionDialog menu item is activated, the following callback function is invoked − def on_abtdlg(self, widget): about = gtk.AboutDialog() about.set_program_name("PyGTK Dialog") about.set_version("0.1") about.set_authors("M.V.Lathkar") about.set_copyright("(c) TutorialsPoint") about.set_comments("About Dialog example") about.set_website("http://www.tutorialspoint.com") about.run() about.destroy() The selected font is applied to the text of label placed on the toplevel window. The following is the output − This is a preconfigured Dialog in PyGTK API which lets the user to select and apply color. It internally embeds a gtk.ColorSelection widget. The gtk.ColorScelection widget presents a colow wheel, and entry boxes for color parameters such as HSV and RGB. New color can be selected by manipulating color wheel or entering color parameters. Its get_current_color is useful for further processing. Following is the prototype of the constructor of the gtk.ColorSelectionDialog class − dlg = gtk.ColorSelectionDialog(title) The current selected color is obtained from the colorsel attribute. The selected color is applied to a widget using modify_fg() or modify_bg() methods. When the ColorDialog menu button is activated, the following callback function is executed − def on_color(self, widget): dlg = gtk.ColorSelectionDialog("Select color") col = dlg.run() sel = dlg.colorsel.get_current_color() self.text.modify_fg(gtk.STATE_NORMAL, sel) The chosen color is applied to the text in a label widget on the window − The following is the output − This dialog is useful to let the user select the location and the name of file that needs to be opened or saved. It embeds FileChooserWidget and provides OK and CANCEL buttons in the action_area. The following is a constructor of the gtk.FileChooserDialog class − Dlg=gtk.FileChooserDialog (title = None, parent = None, action = gtk.FILE_CHOOSER_ACTION_OPEN, buttons = None, backend = None) The parameters are − The following are the action modes − gtk.FILE_CHOOSER_ACTION_OPEN gtk.FILE_CHOOSER_ACTION_SAVE gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER If it is desired to restrict the types of files to be available for display, an object of the gtk.FileFilter can be applied by using the add_filter() method. If the FileChooserDialog menu button is clicked, the following callback function is run. def on_file(self, widget): dlg = gtk.FileChooserDialog("Open..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) response = dlg.run() self.text.set_text(dlg.get_filename()) dlg.destroy() The file is selected from the dialog − The selected file is displayed on the label on the toplevel gtk.Window − Notebook widget is a tabbed container. Each tab in this container holds a different page and the pages are seen in overlapped manner. Any desired page is made visible by clicking on the label of the tab. The labels can be configured to be displayed on top or bottom or to the left or right. A container widget with other widgets placed in it or a single widget is placed under each page. If data to be displayed is too big in one view, it is grouped in different pages, each placed under one tab of a Notebook widget. This type of control is very widely used. Internet browser for instance, uses this tabbed display for rendering different pages in different tabs. The following is a constructor of the gtk.Notebook class − gtk.Notebook() The following are the frequently used methods of the gtk.Notebook class − append_page(child, label) − This appends a page to the notebook containing a widget specified by tab_label as the label on the tab. If tab_label can be None to use a default label. append_page(child, label) − This appends a page to the notebook containing a widget specified by tab_label as the label on the tab. If tab_label can be None to use a default label. insert_page(child, label, position) − This inserts a page into the notebook at the location specified by position. insert_page(child, label, position) − This inserts a page into the notebook at the location specified by position. remove_page(index) − This removes a page at the specified index. remove_page(index) − This removes a page at the specified index. get_current_page() − This returns the page index of the current page. get_current_page() − This returns the page index of the current page. set_current_page(index) − This switches to the page number specified by the index. set_current_page(index) − This switches to the page number specified by the index. set_show_tabs() − If false, tabs will not be visible. This is True by default. set_show_tabs() − If false, tabs will not be visible. This is True by default. set_tab_pos(pos) − This sets the edge at which the tabs for switching pages in the notebook are drawn. The predefined constants are − gtk.POS_LEFT gtk.POS_RIGHT gtk.POS_TOP gtk.POS_BOTTOM set_tab_pos(pos) − This sets the edge at which the tabs for switching pages in the notebook are drawn. The predefined constants are − gtk.POS_LEFT gtk.POS_LEFT gtk.POS_RIGHT gtk.POS_RIGHT gtk.POS_TOP gtk.POS_TOP gtk.POS_BOTTOM gtk.POS_BOTTOM set_tab_label_text(child, text) − This creates a new label with the text specified and sets it as the tab label for the page containing child. set_tab_label_text(child, text) − This creates a new label with the text specified and sets it as the tab label for the page containing child. The gtk.Notebook widget emits the following signals − In the following example, a gtk.Notebook with three pages is placed in a toplevel gtk.Window. The first page holds a VBox in which a label and Entry field is packed. The second page labelled 'qualifications' has a HButtonBox in which three mutually exclusive RadioButton widgets are added. The third page has a TextView object. The page labels are displayed at top. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Notebook Demo") self.set_default_size(250, 200) nb = gtk.Notebook() nb.set_tab_pos(gtk.POS_TOP) vbox = gtk.VBox(False, 5) vb = gtk.VBox() hbox = gtk.HBox(True, 3) valign = gtk.Alignment(0.5,0.25, 0, 0) lbl = gtk.Label("Name of student") vb.pack_start(lbl, True, True, 10) text = gtk.Entry() vb.pack_start(text, True, True, 10) valign.add(vb) vbox.pack_start(valign) nb.append_page(vbox) nb.set_tab_label_text(vbox, "Name") hb = gtk.HButtonBox() btn1 = gtk.RadioButton(None,"Degree") hb.add(btn1) btn2 = gtk.RadioButton(btn1,"P.G.") hb.add(btn2) btn3 = gtk.RadioButton(btn1,"Doctorate") hb.add(btn3) nb.append_page(hb) nb.set_tab_label_text(hb, "Qualification") tv = gtk.TextView() nb.append_page(tv) nb.set_tab_label_text(tv, "about") self.add(nb) self.connect("destroy", gtk.main_quit) self.show_all() if __name__ == '__main__': PyApp() gtk.main() Upon execution, the above code displays a Notebook with three pages − Frame class is a subclass of the gtk.Bin class. It draws a decorative border around the child widget placed in it. The frame may contain a label whose position may be customized. A gtk.Frame object is constructed with the help of the following constructor − frame = gtk.Frame(label = None) The following are the methods of the gtk.Frame() class − set_label(text) − This sets the label as specified by text. If None, the current label is removed. set_label(text) − This sets the label as specified by text. If None, the current label is removed. set_label_widget() − This sets a widget other than gtk.Label as label for frame. set_label_widget() − This sets a widget other than gtk.Label as label for frame. set_label_align(x, y) − This sets the alignment of the frame's label widget and decoration (defaults are 0.0 and 0.5) set_label_align(x, y) − This sets the alignment of the frame's label widget and decoration (defaults are 0.0 and 0.5) set_shadow_type() − This sets the frame's shadow type. set_shadow_type() − This sets the frame's shadow type. The possible values are − gtk.SHADOW_NONE gtk.SHADOW_IN gtk.SHADOW_OUT gtk.SHADOW_ETCHED_IN tk.SHADOW_ETCHED_OUT The following code demonstrates the functioning of the Frame widget. A group of three objects of gtk.RadioButton is placed in an HButtonBox. btn1 = gtk.RadioButton(None,"Degree") btn2 = gtk.RadioButton(btn1,"P.G.") btn3 = gtk.RadioButton(btn1,"Doctorate") hb = gtk.HButtonBox() hb.add(btn1) hb.add(btn2) hb.add(btn3) In order to draw border around the box, it is placed in a Frame widget, and it is added to the toplevel window. frm = gtk.Frame() frm.add(hb) self.add(frm) Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Frame Demo") self.set_default_size(250, 200) self.set_border_width(5) frm = gtk.Frame() hb = gtk.HButtonBox() btn1 = gtk.RadioButton(None,"Degree") hb.add(btn1) btn2 = gtk.RadioButton(btn1,"P.G.") hb.add(btn2) btn3 = gtk.RadioButton(btn1,"Doctorate") hb.add(btn3) frm.add(hb) frm.set_label("Qualifications") self.add(frm) self.connect("destroy", gtk.main_quit) self.show_all() if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − gtk.AspectFrame class is a subclass of the Frame class. The child widget in this frame always retains its aspect ratio (of width and height) even if the main window is resized. The ratio property of gtk.AspectFrame widget determines the widget width:height ratio. An aspect ratio of 0.5 means the width is one half the height; an aspect ratio of 2.0 means the width is twice the height. The default value for the "ratio" property is 1.0. The following syntax is used for the constructor of gtk.AspectFrame class − gtk.AspectFrame (label = None, xalign = 0.5, yalign = 0.5, ratio = 1.0, obey_child = True) The xalign property determines the fraction of horizontal free space to the left of the child. 0.0 means no free space to the left, 1.0 means all free space to the left. The yalign property determines the fraction of vertical free space above the child. 0.0 means no free space above, 1.0 means all free space above. Ratio of width to height of frame is maintained if obey_child property is False. The obey_child property determines if the ratio is to be ignored. The default is True. The following code is similar to the one used for the Frame class. The only difference is that the ButonBox is placed in an AspectFrame widget. frm = gtk.AspectFrame(label = None, xalign = 0.5, yalign = 0.5, ratio = 5.0, obey_child = False) Note − The obey_child property is set to False because it is desired to retain the aspect ratio even if the window is resized. Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Aspect Frame Demo") self.set_default_size(250, 200) self.set_border_width(5) frm = gtk.AspectFrame(label = None, xalign = 0.5, yalign = 0.5, ratio = 5.0, obey_child = False) hb = gtk.HButtonBox() btn1 = gtk.RadioButton(None,"Degree") hb.add(btn1) btn2 = gtk.RadioButton(btn1,"P.G.") hb.add(btn2) btn3 = gtk.RadioButton(btn1,"Doctorate") hb.add(btn3) frm.add(hb) frm.set_label("Qualifications") self.add(frm) self.connect("destroy", gtk.main_quit) self.show_all() if __name__ == '__main__': PyApp() gtk.main() The above code will produce the following original and resized windows − Original Window Resized Window The Treeview widget displays contents of a model implementing the gtk.TreeModel interface. PyGTK provides the following types of models − gtk.ListStore gtk.TreeStore gtk.TreeModelSort ListStore is a list model. When associated with a gtk.TreeView widget, it produces a List box containing the items to be selected from. A gtk.ListStore object is declared with following syntax − store = gtk.ListStore(column_type) A list may have multiple columns, the predefined type constants are − gobject.TYPE_BOOLEAN gobject.TYPE_BOXED gobject.TYPE_CHAR gobject.TYPE_DOUBLE gobject.TYPE_ENUM gobject.TYPE_FLOAT gobject.TYPE_INT gobject.TYPE_LONG gobject.TYPE_NONE gobject.TYPE_OBJECT gobject.TYPE_STRING gobject.TYPE_UCHAR gobject.TYPE_UINT gobject.TYPE_ULONG gtk.gdk.pixbuf etc. For example, a ListStore object to store string items is declared as − store = gtk.ListStore(gobject.TYPE_STRING In order to add items in the store, append() methods are used − store.append (["item 1"]) TreeStore is a model for multi-columned Tree widget. For example, the following statement creates a store with one column having string item. Store = gtk.TreeStore(gobject.TYPE_STRING) In order to add items in a TreeStore, use the append() method. The append() method has two parameters, parent and row. To add toplevel item, parent is None. row1 = store.append(None, ['row1']) You need to repeat this statement to add multiple rows. In order to add child rows, pass the toplevel row as parent parameter to the append() method − childrow = store.append(row1, ['child1']) You need to repeat this statement to add multiple child rows. Now, create a TreeView widget and use the above TreeStore object as model. treeview = gtk.TreeView(store) We now have to create TreeViewColumn to display store data. The object of gtk.TreeViewColumn manages header and the cells using gtk.CelRenderer. TreeViewColumn object is created using the following constructor − gtk.TreeViewColumn(title, cell_renderer,...) In addition to title and renderer, it takes zero or more attribute=column pairs to specify from which tree model column the attribute's value is to be retrieved. These parameters can also be set using methods of TreeViewColumn class given below. A gtk.CellRenderer is a base class for a set of objects for rendering different types of data. The derived classes are CellRendererText, CellRendererPixBuf and CellRendererToggle. The following methods of the TreeViewColumn class are used to configure its object − TreeViewColumn.pack_start(cell, expand = True) − This method packs the CellRenderer object into the beginning column. If expand parameter is set to True, columns entire allocated space is assigned to cell. TreeViewColumn.pack_start(cell, expand = True) − This method packs the CellRenderer object into the beginning column. If expand parameter is set to True, columns entire allocated space is assigned to cell. TreeViewColumn.add_attribute(cell, attribute, column) − This method adds an attribute mapping to the list in the tree column. The column is the column of the tree model. TreeViewColumn.add_attribute(cell, attribute, column) − This method adds an attribute mapping to the list in the tree column. The column is the column of the tree model. TreeViewColumn.set_attributes() − This method sets the attribute locations of the renderer using the attribute = column pairs TreeViewColumn.set_attributes() − This method sets the attribute locations of the renderer using the attribute = column pairs TreeViewColumn.set_visible() − If True, the treeview column is visible TreeViewColumn.set_visible() − If True, the treeview column is visible TreeViewColumn.set_title() − This method sets the "title" property to the value specified. TreeViewColumn.set_title() − This method sets the "title" property to the value specified. TreeViewColumn.set_lickable() − If set to True, the header can take keyboard focus, and be clicked. TreeViewColumn.set_lickable() − If set to True, the header can take keyboard focus, and be clicked. TreeViewColumn.set_alignment(xalign) − This method sets the "alignment" property to the value of xalign. TreeViewColumn.set_alignment(xalign) − This method sets the "alignment" property to the value of xalign. The "clicked" signal is emitted when the user clicks on the treeviewcolumn header button. After having configured the TreeViewColumn object, it is added to the TreeView widget using the append_column() method. The following are the important methods of the TreeView class − TreevVew.set_model() − This sets the "model" property for the treeview. If the treeview already has a model set, this method will remove it before setting the new model. If model is None, it will unset the old model. TreevVew.set_model() − This sets the "model" property for the treeview. If the treeview already has a model set, this method will remove it before setting the new model. If model is None, it will unset the old model. TreeView.set_header_clickable() − If set to True, the column title buttons can be clicked. TreeView.set_header_clickable() − If set to True, the column title buttons can be clicked. TreeView.append_column() − This appends the specified TreeViewColumn to the list of columns. TreeView.append_column() − This appends the specified TreeViewColumn to the list of columns. TreeView.remove_column() − This removes the specified column from the treeview. TreeView.remove_column() − This removes the specified column from the treeview. TreeView.insert_column() − This inserts the specified column into the treeview at the location specified by position. TreeView.insert_column() − This inserts the specified column into the treeview at the location specified by position. The TreeView widget emits the following signals − Two examples of the TreeView widget are given below. The first example uses a ListStore to produce a simple ListView. Here a ListStore object is created and string items are added to it. This ListStore object is used as model for TreeView object − store = gtk.ListStore(str) treeView = gtk.TreeView() treeView.set_model(store) Then a CellRendererText is added to a TreeViewColumn object and the same is appended to TreeView. rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("Name", rendererText, text = 0) treeView.append_column(column) TreeView Object is placed on the toplevel window by adding it to a Fixed container. Observe the following code − import pygtk pygtk.require('2.0') import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("TreeView with ListStore") self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) store = gtk.ListStore(str) store.append (["PyQt"]) store.append (["Tkinter"]) store.append (["WxPython"]) store.append (["PyGTK"]) store.append (["PySide"]) treeView = gtk.TreeView() treeView.set_model(store) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("Python GUI Libraries", rendererText, text=0) treeView.append_column(column) fixed = gtk.Fixed() lbl = gtk.Label("select a GUI toolkit") fixed.put(lbl, 25,75) fixed.put(treeView, 125,15) lbl2 = gtk.Label("Your choice is:") fixed.put(lbl2, 25,175) self.label = gtk.Label("") fixed.put(self.label, 125,175) self.add(fixed) treeView.connect("row-activated", self.on_activated) self.connect("destroy", gtk.main_quit) self.show_all() def on_activated(self, widget, row, col): model = widget.get_model() text = model[row][0] self.label.set_text(text) def main(): gtk.main() return if __name__ == "__main__": bcb = PyApp() main() The item selected by the user is displayed on a label in the window as the on_activated callback function is invoked. The second example builds a hierarchical TreeView from a TreeStore. This program follows the same sequence of building the store, setting it as model for TreeView, designing a TreeViewColumn and appending it to TreeView. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("TreeView with TreeStore") self.set_size_request(400,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) # create a TreeStore with one string column to use as the model store = gtk.TreeStore(str) # add row row1 = store.append(None, ['JAVA']) #add child rows store.append(row1,['AWT']) store.append(row1,['Swing']) store.append(row1,['JSF']) # add another row row2 = store.append(None, ['Python']) store.append(row2,['PyQt']) store.append(row2,['WxPython']) store.append(row2,['PyGTK']) # create the TreeView using treestore treeview = gtk.TreeView(store) tvcolumn = gtk.TreeViewColumn('GUI Toolkits') treeview.append_column(tvcolumn) cell = gtk.CellRendererText() tvcolumn.pack_start(cell, True) tvcolumn.add_attribute(cell, 'text', 0) vbox.add(treeview) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The following TreeView is displayed as an output − Paned class is the base class for widgets which can display two adjustable panes either horizontally (gtk.Hpaned) or vertically (gtk.Vpaned). Child widgets to panes are added by using pack1() and pack2() methods. Paned widget draws a separator slider between two panes and provides a handle to adjust their relative width/height. If the resize property of child widget inside a pane is set to True, it will resize according to the size of the panes. The following methods are available for HPaned as well as VPaned class − Paned.add1(child) − This adds the widget specified by child to the top or left pane Paned.add1(child) − This adds the widget specified by child to the top or left pane Paned.add2(child) − This adds the widget specified by child to the bottom or right pane. Paned.add2(child) − This adds the widget specified by child to the bottom or right pane. Paned.pack1(child, resize, shrink) − This adds the widget specified by child to the top or left pane with the parameters. If resize is True, child should be resized when the paned widget is resized. If shrink is True, child can be made smaller than its minimum size request. Paned.pack1(child, resize, shrink) − This adds the widget specified by child to the top or left pane with the parameters. If resize is True, child should be resized when the paned widget is resized. If shrink is True, child can be made smaller than its minimum size request. Paned.pack2(child, resize, shrink) − This sets the position of the divider between the two panes. Paned.pack2(child, resize, shrink) − This sets the position of the divider between the two panes. Both types of Paned widgets emit the following signals − The following example uses a gtk.Hpaned widget. In the left pane, a TreeView widget is added, and in the right pane, there is a TextView widget. When any row in TreeView is selected, it will emit row_activated signal which is connected to a callback function. The on_activated()function retrieves row's text and displays in the text view panel. Observe the code − import gtk, gobject class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("HPaned widget Demo") self.set_default_size(250, 200) vp = gtk.HPaned() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) tree = gtk.TreeView() languages = gtk.TreeViewColumn() languages.set_title("GUI Toolkits") cell = gtk.CellRendererText() languages.pack_start(cell, True) languages.add_attribute(cell, "text", 0) treestore = gtk.TreeStore(str) it = treestore.append(None, ["Python"]) treestore.append(it, ["PyQt"]) treestore.append(it, ["wxPython"]) treestore.append(it, ["PyGTK"]) treestore.append(it, ["Pydide"]) it = treestore.append(None, ["Java"]) treestore.append(it, ["AWT"]) treestore.append(it, ["Swing"]) treestore.append(it, ["JSF"]) treestore.append(it, ["SWT"]) tree.append_column(languages) tree.set_model(treestore) vp.add1(tree) self.tv = gtk.TextView() vp.add2(self.tv) vp.set_position(100) self.add(vp) tree.connect("row-activated", self.on_activated) self.connect("destroy", gtk.main_quit) self.show_all() def on_activated(self, widget, row, col): model = widget.get_model() text = model[row][0] print text buffer = gtk.TextBuffer() buffer.set_text(text+" is selected") self.tv.set_buffer(buffer) if __name__ == '__main__': PyApp() gtk.main() The above code will generate the following output − A notification area, usually at the bottom of a window is called the status bar. Any type of status change message can be displayed on the status bar. It also has a grip using which it can be resized. The gtk.Statusbar widget maintains a stack of messages. Hence, new message gets displayed on top of the current message. If it is popped, earlier message will be visible again. Source of the message must be identified by context_id to identify it uniquely. The following is the constructor of the gtk.Statusbar widget − bar = gtk.Statusbar() The following are the methods of the gtk.Statusbar class − Statusbar.push(context_id, text) − This pushes a new message onto a statusbar's stack. Statusbar.push(context_id, text) − This pushes a new message onto a statusbar's stack. Statusbar.pop(context_id) − This removes the top message with the specified context_id from the statusbar's stack. Statusbar.pop(context_id) − This removes the top message with the specified context_id from the statusbar's stack. The following signals are emitted by the Statusbar widget − The following example demonstrates the functioning of Statusbar. Toplevel window contains a VBox with two rows. Upper row has a Fixed widget in which a label, an Entry widget and a button is put. Whereas, in the bottom row, a gtk.Statusbar widget is added. In order to send message to status bar, its context_id needs to be fetched. id1 = self.bar.get_context_id("Statusbar") The 'clicked' signal of the Button object is connected to a callback function through which a message is pushed in the status bar. And, the 'activate' signal is emitted when Enter key is pressed inside the Entry widget. This widget is connected to another callback. btn.connect("clicked", self.on_clicked, id1) txt.connect("activate", self.on_entered, id1) Both callbacks use push() method to flash the message in the notification area. Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Statusbar demo") self.set_size_request(400,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() fix = gtk.Fixed() lbl = gtk.Label("Enter name") fix.put(lbl, 175, 50) txt = gtk.Entry() fix.put(txt, 150, 100) btn = gtk.Button("ok") fix.put(btn, 200,150) vbox.add(fix) self.bar = gtk.Statusbar() vbox.pack_start(self.bar, True, False, 0) id1 = self.bar.get_context_id("Statusbar") btn.connect("clicked", self.on_clicked, id1) txt.connect("activate", self.on_entered, id1) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() def on_clicked(self, widget, data=None): self.bar.push(data, "Button clicked def on_entered(self, widget, data): self.bar.push(data, "text entered") PyApp() gtk.main() Upon execution, the above code will display the following output − Try typing in the text box and press Enter to see the 'text entered' message in status bar. Progress bars are used to give user the visual indication of a long running process. The gtk.ProgressBar widget can be used in two modes — percentage mode and activity mode. When it is possible to accurately estimate how much of work is pending to be completed, the progress bar can be used in percentage mode, and the user sees an incremental bar showing percentage of completed job. If on the other hand, the amount of work to be completed can be accurately determined, the progress bar is used in activity mode in which, the bar shows the activity by displaying a block moving back and forth. The following constructor initializes the widget of the gtk.ProgressBar class − pb = gtk.ProgressBar() gtk.ProgressBar uses the following methods to manage functionality − ProgressBar.pulse() − This nudges the progressbar to indicate that some progress has been made, but you don't know how much. This method also changes the progress bar mode to "activity mode," where a block bounces back and forth. ProgressBar.pulse() − This nudges the progressbar to indicate that some progress has been made, but you don't know how much. This method also changes the progress bar mode to "activity mode," where a block bounces back and forth. ProgressBar.set_fraction(fraction) − This causes the progress bar to "fill in" the portion of the bar specified by fraction. The value of fraction should be between 0.0 and 1.0. ProgressBar.set_fraction(fraction) − This causes the progress bar to "fill in" the portion of the bar specified by fraction. The value of fraction should be between 0.0 and 1.0. ProgressBar.set_pulse_setup() − This sets the portion (specified by fraction) of the total progress bar length to move the bouncing block for each call to the pulse() method. ProgressBar.set_pulse_setup() − This sets the portion (specified by fraction) of the total progress bar length to move the bouncing block for each call to the pulse() method. ProgressBar.set_orientation() − This sets the orientation of the progress bar. It may be set to one of the following constants: gtk.PROGRESS_LEFT_TO_RIGHT gtk.PROGRESS_RIGHT_TO_LEFT gtk.PROGRESS_BOTTOM_TO_TOP gtk.PROGRESS_TOP_TO_BOTTOM ProgressBar.set_orientation() − This sets the orientation of the progress bar. It may be set to one of the following constants: gtk.PROGRESS_LEFT_TO_RIGHT gtk.PROGRESS_LEFT_TO_RIGHT gtk.PROGRESS_RIGHT_TO_LEFT gtk.PROGRESS_RIGHT_TO_LEFT gtk.PROGRESS_BOTTOM_TO_TOP gtk.PROGRESS_BOTTOM_TO_TOP gtk.PROGRESS_TOP_TO_BOTTOM gtk.PROGRESS_TOP_TO_BOTTOM In the following program, the gtk.ProgressBar widget is used in activity mode. Hence, the initial position of progress is set to 0.0 by the set_fraction() method. self.pb = gtk.ProgressBar() self.pb.set_text("Progress") self.pb.set_fraction(0.0) In order to increment the progress by 1 percent after 100 milliseconds, a timer object is declared and a callback function is set up to be invoked after every 100 ms so that the progress bar is updated. self.timer = gobject.timeout_add (100, progress_timeout, self) Here, progress_timeout() is the callback function. It increments the parameter of the set_fraction() method by 1 percent and updates the text in progress bar to show the percentage of completion. def progress_timeout(pbobj): new_val = pbobj.pb.get_fraction() + 0.01 pbobj.pb.set_fraction(new_val) pbobj.pb.set_text(str(new_val*100)+" % completed") return True Observe the following code − import gtk, gobject def progress_timeout(pbobj): new_val = pbobj.pb.get_fraction() + 0.01 pbobj.pb.set_fraction(new_val) pbobj.pb.set_text(str(new_val*100)+" % completed") return True class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Progressbar demo") self.set_size_request(300,200) self.set_position(gtk.WIN_POS_CENTER) fix = gtk.Fixed() self.pb = gtk.ProgressBar() self.pb.set_text("Progress") self.pb.set_fraction(0.0) fix.put(self.pb,80,100) self.add(fix) self.timer = gobject.timeout_add (100, progress_timeout, self) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − To use the progress bar in activity mode, change callback function to the following and run − def progress_timeout(pbobj): pbobj.pb.pulse() return True The back and forth movement of a block inside the Progress bar will show the progress of the activity. If a widget has an area larger than that of the toplevel window, it is associated with a ViewPort container. A gtk.Viewport widget provides adjustment capability to be used in a ScrolledWindow. A Label widget for instance, doesn't have any adjustments. Hence it needs a Viewport. Some widgets have a native scrolling support. But a Label or a gtk.Table widget doesn't have an in-built scrolling support. Hence they must use Viewport. ViewPort class has the following constructor − gtk.Viewport(hadj, vadj) Here, hadj and vadj are the adjustment objects associated with the viewport. gtk.ViewPort class uses the following methods − Viewport.set_hadjustment() − This sets the "hadjustment" property Viewport.set_hadjustment() − This sets the "hadjustment" property Viewport.set_vadjustment() − This sets the "vadjustment" property Viewport.set_vadjustment() − This sets the "vadjustment" property Viewport.set_shadow_type() − This sets the "shadow-type" property to the value of type. The value of type must be one of − gtk.SHADOW_NONE gtk.SHADOW_IN gtk.SHADOW_OUT gtk.SHADOW_ETCHED_IN gtk.SHADOW_ETCHED_OUT Viewport.set_shadow_type() − This sets the "shadow-type" property to the value of type. The value of type must be one of − gtk.SHADOW_NONE gtk.SHADOW_NONE gtk.SHADOW_IN gtk.SHADOW_IN gtk.SHADOW_OUT gtk.SHADOW_OUT gtk.SHADOW_ETCHED_IN gtk.SHADOW_ETCHED_IN gtk.SHADOW_ETCHED_OUT gtk.SHADOW_ETCHED_OUT The gtk.Viewport object emits the set-scroll-adjustments signal when one or both of the horizontal and vertical gtk.Adjustment objects is changed. Scrolled window is created to access other widget of area larger than parent window. Some widgets like TreeView and TextView of native support for scrolling. For others such as Label or Table, a Viewport should be provided. The following syntax is used for the constructor of the gtk.ScrolledWindow class − sw = gtk.ScrolledWindow(hadj, vadj) The following are the methods of the gtk.ScrolledWindow class − ScrolledWindow.set_hadjustment() − This sets the horizontal adjustment to a gtk.Adjustment object ScrolledWindow.set_hadjustment() − This sets the horizontal adjustment to a gtk.Adjustment object ScrolledWindow.set_vadjustment() − This sets the vertical adjustment to a gtk.Adjustment object ScrolledWindow.set_vadjustment() − This sets the vertical adjustment to a gtk.Adjustment object ScrolledWindow.set_Policy (hpolicy, vpolicy) − This sets the "hscrollbar_policy" and "vscrollbar_policy" properties. One of the following predefined constants are used − gtk.POLICY_ALWAYS − The scrollbar is always present gtk.POLICY_AUTOMATIC − The scrollbar is present only if needed i.e. the contents are larget than the window gtk.POLICY_NEVER − The scrollbar is never present ScrolledWindow.set_Policy (hpolicy, vpolicy) − This sets the "hscrollbar_policy" and "vscrollbar_policy" properties. One of the following predefined constants are used − gtk.POLICY_ALWAYS − The scrollbar is always present gtk.POLICY_ALWAYS − The scrollbar is always present gtk.POLICY_AUTOMATIC − The scrollbar is present only if needed i.e. the contents are larget than the window gtk.POLICY_AUTOMATIC − The scrollbar is present only if needed i.e. the contents are larget than the window gtk.POLICY_NEVER − The scrollbar is never present gtk.POLICY_NEVER − The scrollbar is never present ScrolledWindow.add_with_viewport(child) − This method is used to add a widget (specified by child) without native scrolling capabilities to the scrolled window. This is a convenience function that is equivalent to adding child to a gtk.Viewport, then adding the viewport to the scrolled window. ScrolledWindow.add_with_viewport(child) − This method is used to add a widget (specified by child) without native scrolling capabilities to the scrolled window. This is a convenience function that is equivalent to adding child to a gtk.Viewport, then adding the viewport to the scrolled window. The following code adds a scrolled window around a gtk.Table object with 10 by 10 dimensions. Since a Table object doesn't support adjustments automatically, it is added in a Viewport. sw = gtk.ScrolledWindow() table = gtk.Table(10,10) Two nested loops are used to add 10 rows of 10 columns each. A gtk.Button widget is placed in each cell. for i in range(1,11): for j in range(1,11): caption = "Btn"+str(j)+str(i) btn = gtk.Button(caption) table.attach(btn, i, i+1, j, j+1) This large enough table is now added in the scrolled window along with a viewport. sw.add_with_viewport(table) Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("ScrolledWindow and Viewport") self.set_size_request(400,300) self.set_position(gtk.WIN_POS_CENTER) sw = gtk.ScrolledWindow() table = gtk.Table(10,10) table.set_row_spacings(10) table.set_col_spacings(10) for i in range(1,11): for j in range(1,11): caption = "Btn"+str(j)+str(i) btn = gtk.Button(caption) table.attach(btn, i, i+1, j, j+1) sw.add_with_viewport(table) self.add(sw) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − The gtk.Arrow object is used to draw simple arrow pointing towards four cardinal directions. This class is inherited from the gtk.Misc class and the object will occupy any space allocated it, for instance, a Label or Button widget. Typically, Arrow object is created using the following constructor − Arr = gtk.Arrow(arrow_type, shadow_type) The predefined arrow_type constants are − gtk.ARROW_UP gtk.ARROW_DOWN gtk.ARROW_LEFT gtk.ARROW_RIGHT The predefined shadow_type constants are listed in the following table − In the following example, four Button widgets are added to an Hbox. On top of each button, a gtk.Arrow object pointing UP, DOWN, LEFT and RIGHT respectively is placed. The HBOX container is placed at the bottom of the toplevel window with the help of an Alignment container. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Arrow Demo") self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) hbox = gtk.HBox(True, 3) valign = gtk.Alignment(0, 1, 0, 0) vbox.pack_start(valign) arr1 = gtk.Arrow(gtk.ARROW_UP, gtk.SHADOW_NONE) arr2 = gtk.Arrow(gtk.ARROW_DOWN, gtk.SHADOW_NONE) arr3 = gtk.Arrow(gtk.ARROW_LEFT, gtk.SHADOW_NONE) arr4 = gtk.Arrow(gtk.ARROW_RIGHT, gtk.SHADOW_NONE) btn1 = gtk.Button() btn1.add(arr1) btn2 = gtk.Button() btn2.add(arr2) btn3 = gtk.Button() btn3.add(arr3) btn4 = gtk.Button() btn4.add(arr4) hbox.add(btn1) hbox.add(btn2) hbox.add(btn3) hbox.add(btn4) halign = gtk.Alignment(0.5, 0.5, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, True, 10) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − This class is also inherited from the gtk.Misc class. The object of the gtk.Image class displays an image. Usually, the image is to be loaded from a file in a pixel buffer representing gtk.gdk.Pixbuf class. Instead a convenience function set_from_file() is commonly used to display image data from file in a gk.Image widget. The easiest way to create the gtk.Image object is to use the following constructor − img = gtk.Image() The following are the methods of the gtk.Image class − Image.set_from_file() − This sets the image data from the contents of the file. Image.set_from_file() − This sets the image data from the contents of the file. Image.set_from_pixbuf() − This sets the image data from pixmap in which the image data is loaded for offscreen manipulation. Image.set_from_pixbuf() − This sets the image data from pixmap in which the image data is loaded for offscreen manipulation. Image.set_from_pixbuf() − This sets the image data using pixbuf which is an object containing the data that describes an image using client side resources. Image.set_from_pixbuf() − This sets the image data using pixbuf which is an object containing the data that describes an image using client side resources. Image.set_from_stock() − This sets the image data from the stock item identified by stock_id. Image.set_from_stock() − This sets the image data from the stock item identified by stock_id. Image.clear() − This removes the current image. Image.clear() − This removes the current image. Image.set_from_image() − This sets the image data from a client-side image buffer in the pixel format of the current display. If the image is None, the current image data will be removed. Image.set_from_image() − This sets the image data from a client-side image buffer in the pixel format of the current display. If the image is None, the current image data will be removed. In the following program, the gtk.Image object is obtained from an image file. It is further added in the toplevel window. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("PyGtk Image demo") self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) image1 = gtk.Image() image1.set_from_file("python.png") self.add(image1) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn. PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files. In order to perform different drawing operations, we must fetch the device on text of the target output object. In this case, since the drawing is appearing on gtk.DrawingArea widget, the device context of gdk.Window contained inside it is obtained. This class has a cairo-create() method which returns the device context. area = gtk.DrawingArea() dc = area.window.cairo_create() The DrawingArea widget can be connected to the callbacks based on the following signals emitted by it − The Mouse and Keyboard events can also be used to invoke callbacks by add_events() method of the gtk.Widget class. Of particular interest is the expose-event signal which is emitted when the DrawingArea canvas first comes up. The different methods for drawing 2D objects, that are defined in the Cairo library are called from this callback connected to the expose-event signal. These methods draw corresponding objects on the Cairo device context. The following are the available drawing methods − dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height. dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height. dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles. dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles. dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates. dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates. dc.line_to(x,y) − This draws a line from the current position to (x,y) dc.line_to(x,y) − This draws a line from the current position to (x,y) dc.show_text(str) − draws string at current cursor position dc.show_text(str) − draws string at current cursor position dc.stroke() − draws outline dc.stroke() − draws outline dc.fill() − fills shape with current color dc.fill() − fills shape with current color dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0 dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0 The following script draws different shapes and test using Cairo methods. import gtk import math class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Basic shapes using Cairo") self.set_size_request(400, 250) self.set_position(gtk.WIN_POS_CENTER) self.connect("destroy", gtk.main_quit) darea = gtk.DrawingArea() darea.connect("expose-event", self.expose) self.add(darea) self.show_all() def expose(self, widget, event): cr = widget.window.cairo_create() cr.set_line_width(2) cr.set_source_rgb(0,0,1) cr.rectangle(10,10,100,100) cr.stroke() cr.set_source_rgb(1,0,0) cr.rectangle(10,125,100,100) cr.stroke() cr.set_source_rgb(0,1,0) cr.rectangle(125,10,100,100) cr.fill() cr.set_source_rgb(0.5,0.6,0.7) cr.rectangle(125,125,100,100) cr.fill() cr.arc(300, 50, 50,0, 2*math.pi) cr.set_source_rgb(0.2,0.2,0.2) cr.fill() cr.arc(300, 200, 50, math.pi,0) cr.set_source_rgb(0.1,0.1,0.1) cr.stroke() cr.move_to(50,240) cr.show_text("Hello PyGTK") cr.move_to(150,240) cr.line_to(400,240) cr.stroke() PyApp() gtk.main() The above script will generate the following output − The SpinnButton widget, often called the Spinner is a gtk.Entry widget with up and down arrows on its right. A user can type in a numeric value directly in it or increment or decrement using up and down arrows. The gtk.SpinButton class is inherited from the gtk.Entry class. It uses a gtk.Adjustment object with which the range and step of the numeric value in the spinner can be restricted. The SpinButton widget is created using the following constructor − sp = gtk.SpinButton(adj, climb_rate, digits) Here, adj represents the gtk.Adjustment object controlling range, climb_rate is an acceleration factor and the number of decimals specified by digits. The gtk.SpinButton class has the following methods − SpinButton.set_adjustment() − This sets the "adjustment" property. SpinButton.set_adjustment() − This sets the "adjustment" property. SpinButton.set_digits() − This sets the "digits" property to the value to determine the number of decimal places to be displayed by the spinbutton. SpinButton.set_digits() − This sets the "digits" property to the value to determine the number of decimal places to be displayed by the spinbutton. SpinButton.set_increments(step, page) − This sets the step value which has increment applied for each left mousebutton press and page value which is increment applied for each middle mousebutton press. SpinButton.set_increments(step, page) − This sets the step value which has increment applied for each left mousebutton press and page value which is increment applied for each middle mousebutton press. SpinButton.set_range() − This sets the minimum and maximum allowable values for spinbutton. SpinButton.set_range() − This sets the minimum and maximum allowable values for spinbutton. SpinButton.set_value() − This sets the spin button to a new value programmatically. SpinButton.set_value() − This sets the spin button to a new value programmatically. SpinButton.update_policy() − The valid values are gtk.UPDATE_ALWAYS and gtk.UPDATE_VALID SpinButton.update_policy() − The valid values are gtk.UPDATE_ALWAYS and gtk.UPDATE_VALID SpinButton.spin(direction, increment=1) − This increments or decrements Spinner's value in the specified direction. SpinButton.spin(direction, increment=1) − This increments or decrements Spinner's value in the specified direction. The following are the predefined direction constants − SpinButton.set_wrap() — If wrap is True, the spin button value wraps around to the opposite limit when the upper or lower limit of the range exceeds. SpinButton.set_wrap() — If wrap is True, the spin button value wraps around to the opposite limit when the upper or lower limit of the range exceeds. The gtk.SpinButton widget emits the following signals − The following example constructs a simple Date Selector by using three SpinButton widgets. The Day Selector is applied an Adjustment object to restrict value between 1—31. The second selector is for the number of months 1—12. The third selector selects the year range 2000—2020. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("SpinButton Demo") self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) self.set_border_width(20) vbox = gtk.VBox(False, 5) hbox = gtk.HBox(True, 3) lbl1 = gtk.Label("Date") hbox.add(lbl1) adj1 = gtk.Adjustment(1.0, 1.0, 31.0, 1.0, 5.0, 0.0) spin1 = gtk.SpinButton(adj1, 0, 0) spin1.set_wrap(True) hbox.add(spin1) lbl2 = gtk.Label("Month") hbox.add(lbl2) adj2 = gtk.Adjustment(1.0, 1.0, 12.0, 1.0, 5.0, 0.0) spin2 = gtk.SpinButton(adj2, 0, 0) spin2.set_wrap(True) hbox.add(spin2) lbl3 = gtk.Label("Year") hbox.add(lbl3) adj3 = gtk.Adjustment(1.0, 2000.0, 2020.0, 1.0, 5.0, 0.0) spin3 = gtk.SpinButton(adj3, 0, 0) spin3.set_wrap(True) hbox.add(spin3) frame = gtk.Frame() frame.add(hbox) frame.set_label("Date of Birth") vbox.add(frame) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() Upon execution, the above code will produce the following output − The Calendar widget in PyGTK toolkit displays a simple calendar with one month view at a time. The navigation controls to change month and year are displayed by default. The display options can be suitably configured. The value of month property is between 0 to 11, and that of date property is between 1 to 31. There is a simple constructor to create a gtk.Calendar object − cal = gtk.Calendar() The default display style shows the current month and year as well as names of days. The gtk.Calendar class has the following methods − Calendar.select_month(mm,yy) — This changes the calendar display to the specified mm and yy. Calendar.select_month(mm,yy) — This changes the calendar display to the specified mm and yy. Calendar.select_day(dd) — This selects the specified dd on the calendar when it has a value between 1 and 31. If dd is 0 then the current day selection is removed. Calendar.select_day(dd) — This selects the specified dd on the calendar when it has a value between 1 and 31. If dd is 0 then the current day selection is removed. Calendar.display_options() — This sets the calendar display options to the value specified by flags. The possible display options are a combination of: Calendar.display_options() — This sets the calendar display options to the value specified by flags. The possible display options are a combination of: Calendar.get_date() — This retrieves the calendar's current year, month and selected day numbers as a tuple (year, month, day). Calendar.get_date() — This retrieves the calendar's current year, month and selected day numbers as a tuple (year, month, day). The gtk.Calendar widget emits the following signals − In the following example, a gtk.Calendar control and four buttons are placed in the toplevel window. When the 'heading' button is clicked, the Calendar's display options are set to SHOW_HEADING − def heading(self, widget): self.cal.set_display_options(gtk.CALENDAR_SHOW_HEADING) When the user clicks the 'day name' button, the callback sets display options to SHOW_DAY_NAMES − def dayname(self, widget): self.cal.set_display_options(gtk.CALENDAR_SHOW_DAY_NAMES) Both the display options are enabled when 'both' button is pressed. To begin with, all flags of display options are removed by setting it to 0. self.cal.set_display_options(0) The 'set' button pops up a message box displaying the currently marked date. tp = self.cal.get_date() str1 = str(tp[0]) str2 = str(tp[1]+1) str3 = str(tp[2]) label = gtk.Label("Date selected:"+str3+"-"+str2+"-"+str1) dialog.vbox.add(label) label.show() Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Calendar Demo") self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) self.cal = gtk.Calendar() halign1 = gtk.Alignment(0.5, 0.5, 0, 0) halign1.add(self.cal) self.cal.set_display_options(0) valign = gtk.Alignment(0, 1, 0, 0) vbox.pack_start(halign1) self.btn1 = gtk.Button("set") self.btn2 = gtk.Button("heading") self.btn3 = gtk.Button("day name") self.btn4 = gtk.Button("Both") hbox = gtk.HBox(True, 3) hbox.add(self.btn1) hbox.add(self.btn2) hbox.add(self.btn3) hbox.add(self.btn4) halign = gtk.Alignment(0.5, 0.5, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, True, 10) self.add(vbox) self.btn1.connect("clicked", self.selectdate) self.btn2.connect("clicked", self.heading) self.btn3.connect("clicked", self.dayname) self.btn4.connect("clicked", self.bothflags) self.connect("destroy", gtk.main_quit) self.show_all() def heading(self, widget): self.cal.set_display_options(gtk.CALENDAR_SHOW_HEADING) def dayname(self, widget): self.cal.set_display_options(gtk.CALENDAR_SHOW_DAY_NAMES) def bothflags(self, widget): self.cal.set_display_options(gtk.CALENDAR_SHOW_HEADING|gtk.CALENDAR_SHOW_DAY_NAMES) def selectdate(self, widget): tp = self.cal.get_date() dialog = gtk.Dialog("My dialog", self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) str1 = str(tp[0]) str2 = str(tp[1]+1) str3 = str(tp[2]) label = gtk.Label("Date selected:"+str3+"-"+str2+"-"+str1) dialog.vbox.add(label) label.show() res = dialog.run() dialog.destroy() PyApp() gtk.main() The above code will generate the following output − A Clipboard object holds shared data between two processes or two widgets of the same application. The gtk.Clipboard is a high level interface for the gtk.SelectionData class. The following is a prototype of the gtk.Clipboard constructor − gtk.Clipboard(display,selction) Here, the display parameter corresponds to the gtk.gdk.Display object for which the clipboard is to be created or retrieved. By default, it is the standard output device. The selection parameter defaults to CLIPBOARD, an object representing an interned string. PyGTK provides a convenience function to create a clipboard object with defaults. gtk.clipboard.get() gtk.Clipboard class has the following methods − Clipboard.store() − This stores the current clipboard data somewhere so that it will stay around even after the application has quit. Clipboard.store() − This stores the current clipboard data somewhere so that it will stay around even after the application has quit. Clipboard.clear() − This removes the contents of the clipboard. Clipboard.clear() − This removes the contents of the clipboard. Clipboard.set_text(text) − This sets the contents of the clipboard to the string. Clipboard.set_text(text) − This sets the contents of the clipboard to the string. Clipboard.request_text() − This requests the contents of the clipboard as text. When the text is later received, callback will be called with the data specified by user_data. The signature of callback is: def callback(clipboard, text, data) − text will contain the text retrieved from clipboard. Clipboard.request_text() − This requests the contents of the clipboard as text. When the text is later received, callback will be called with the data specified by user_data. The signature of callback is: def callback(clipboard, text, data) − text will contain the text retrieved from clipboard. def callback(clipboard, text, data) − text will contain the text retrieved from clipboard. As a demonstration of clipboard, the following code uses two TextViews and two buttons on a toplevel gtk.Window. The 'Set' button calls the on_set() function which puts the text from first textView on the clipboard. buf = self.tv1.get_buffer() text = buf.get_text(buf.get_start_iter(), buf.get_end_iter()) self.clipboard = gtk.clipboard_get() self.clipboard.set_text(text) self.clipboard.store() When the second button ('retrieved') is pressed, the data from clipboard is fetched by the request_text() method − self.clipboard.request_text(self.readclipboard, user_data = None) The content of user_data goes to a callback method readclipboard() which displays it on second textview. def readclipboard(self, clipboard, text, data): buffer = gtk.TextBuffer() buffer.set_text(text) self.tv2.set_buffer(buffer) The following is the entire code for clipboard operation − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Clipboard demo") self.set_size_request(300,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) self.tv1 = gtk.TextView() vbox.add(self.tv1) self.tv2 = gtk.TextView() vbox.add(self.tv2) hbox = gtk.HBox(True, 3) Set = gtk.Button("set") Set.set_size_request(70, 30) retrieve = gtk.Button("retrieve") hbox.add(Set) hbox.add(retrieve) halign = gtk.Alignment(1, 0, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, False, 3) self.add(vbox) Set.connect("clicked", self.on_set) retrieve.connect("clicked", self.on_retrieve) self.connect("destroy", gtk.main_quit) self.show_all() def on_set(self, widget): buf = self.tv1.get_buffer() text = buf.get_text(buf.get_start_iter(), buf.get_end_iter()) self.clipboard = gtk.clipboard_get() self.clipboard.set_text(text) self.clipboard.store() def on_retrieve(self, widget): self.clipboard.request_text(self.readclipboard, user_data=None) def readclipboard(self, clipboard, text, data): buffer = gtk.TextBuffer() buffer.set_text(text) self.tv2.set_buffer(buffer) PyApp() gtk.main() The above code will generate the following output − This is a base class for horizontal (gtk.Hruler) and vertical (gtk.Vruler) rulers that are useful to show mouse pointer's position in window. A small triangle in the ruler indicates the location of pointer. Ruler objects are created with their respective constructors − hrule = gtk.Hruler() vrule = gtk.Vruler() The following gtk.Ruler class methods are available for both the derived classes − Ruler.set_metric() − This sets the measurement unit. The predefined metric constants are: gtk.PIXELS (default), gtk.INCHES and gtk.CENTIMETERS Ruler.set_metric() − This sets the measurement unit. The predefined metric constants are: gtk.PIXELS (default), gtk.INCHES and gtk.CENTIMETERS Ruler.set_range() − This sets the lower and upper bounds, position and maximum size of ruler. Ruler.set_range() − This sets the lower and upper bounds, position and maximum size of ruler. In the example given below, the horizontal and vertical rulers are placed above and to the left of a gtk.TextView widget. The measurement of horizontal ruler is in pixels. Its minimum and maximum values are 0 and 400 respectively. It is placed in the upper row of a gtk.VBox. hrule = gtk.HRuler() hrule.set_metric(gtk.PIXELS) hrule.set_range(0, 4,0,0.5) vbox.pack_start(hrule) The lower row of Vbox contains an HBox. A vertical ruler and a TextView widget, in which a multi-line text can be entered, is packed. vrule=gtk.VRuler() vrule.set_metric(gtk.PIXELS) vrule.set_range(0, 4, 10, 0.5) hbox.pack_start(vrule) Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Ruler demo") self.set_size_request(400,400) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() tv = gtk.TextView() tv.set_size_request(350,350) hrule = gtk.HRuler() hrule.set_metric(gtk.PIXELS) hrule.set_range(0, 4,0,0.5) vbox.pack_start(hrule) hbox = gtk.HBox() vrule = gtk.VRuler() vrule.set_metric(gtk.PIXELS) vrule.set_range(0, 4, 10, 0.5) hbox.pack_start(vrule) halign = gtk.Alignment(0.5, 0.5, 0, 0) halign.add(tv) hbox.pack_start(halign, False, True, 10) vbox.add(hbox) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() PyApp() gtk.main() The output generated by the above program resembles an MS Word document − The gobject module of the PyGTK API has a useful function to create a timeout function that will be called periodically. source_id = gobject.timeout_add(interval, function, ...) The second argument is the callback function you wish to have called after every millisecond which is the value of the first argument – interval. Additional arguments may be passed to the callback as function data. The return value of this function is source_id. Using it, the callback function is stopped from calling. gobject.source_remove(source_id) The callback function must return True in order to keep repeating. Therefore, it can be stopped by returning False. Two buttons and two labels are put on a toplevel window in the following program. One label displays an incrementing number. The btn1 calls on_click which sets the timeout function with an interval of 1000 ms (1 second). btn1.connect("clicked", self.on_click) def on_click(self, widget): self.source_id = gobject.timeout_add(1000, counter, self) The timeout function is named as counter(). It increments the number on a label after every 1 second. def counter(timer): c=timer.count+1 print c timer.count=c timer.lbl.set_label(str(c)) return True The Callback on the second button removes the timeout function. btn2.connect("clicked", self.on_stop) def on_stop(self, widget): gobject.source_remove(self.source_id) The following is the complete code for the Timeout example − import gtk, gobject def counter(timer): c = timer.count+1 print c timer.count = c timer.lbl.set_label(str(c)) return True class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Timeout Demo") self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) hbox = gtk.HBox(True, 3) hb = gtk.HBox() lbl1 = gtk.Label("Counter: ") hb.add(lbl1) self.lbl = gtk.Label("") hb.add(self.lbl) valign = gtk.Alignment(0.5, 0.5, 0, 0) valign.add(hb) vbox.pack_start(valign, True, True, 10) btn1 = gtk.Button("start") btn2 = gtk.Button("stop") self.count = 0 self.source_id = 0 hbox.add(btn1) hbox.add(btn2) halign = gtk.Alignment(0.5, 0.5, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, True, 10) self.add(vbox) btn1.connect("clicked", self.on_click) btn2.connect("clicked", self.on_stop) self.connect("destroy", gtk.main_quit) self.show_all() def on_click(self, widget): self.source_id = gobject.timeout_add(1000, counter, self) def on_stop(self, widget): gobject.source_remove(self.source_id) PyApp() gtk.main() When executed, the window shows two buttons at the bottom. The number on the label will increment periodically when the Start button is clicked on and it will stop incrementing when the Stop button is clicked on. Observe the output − Widgets having associated X Window are capable of drag and drop. In the program, a widget as a source and/or destination for drag-and-drop must first be designated. The widget defined as source can send out the dragged data. The destination widget accepts it when dragged data is dropped on it. The following steps are involved in setting up a drag-and-drop enabled application − Step 1 − Setting up a source widget. Step 2 − The drag_source_set() method specifies the target types for a drag operation − widget.drag_source_set(start_button_mask, targets, info) Step 3 − The start_button_mask argument specifies a bitmask of buttons that starts the drag operation. Step 4 − The target argument is a list of tuples of this structure − (target, flags, info) The target argument is a string representing drag type, for example, text/plain or image/x-xpixmap. Step 6 − The following flags are predefined − gtk.TARGET_SAME_APP gtk.TARGET_SAME_WIDGET Step 7 − There will be no limitation as the flag is set to 0. If the widget is not required to act as source, it can be unset − widget.drag_source_unset() The source signal emits signals. The following table lists the signals and their callbacks. The drag_dest_set() method specifies which widget can receive dragged data. widget.drag_dest_set(flags, targets, action) The flags parameter can take one of the following constants − The target is a list of tuples containing target information. The actions argument is a bitmask of or a combination of one or more of the following values − gtk.gdk.ACTION_DEFAULT gtk.gdk.ACTION_COPY gtk.gdk.ACTION_MOVE gtk.gdk.ACTION_LINK gtk.gdk.ACTION_PRIVATE gtk.gdk.ACTION_ASK The "drag-motion" handler must determine if the drag data is appropriate by matching the destination targets with the gtk.gdk.DragContext targets and optionally by examining the drag data by calling the drag_get_data() method. The gtk.gdk.DragContext. drag_status() method must be called to update the drag_context status. The "drag-drop" handler must determine the matching target using the drag_dest_find_target() method and then ask for the drag data using the drag_get_data() method. The data will be available in the "drag-data-received" handler. Print Add Notes Bookmark this page
[ { "code": null, "e": 2984, "s": 2734, "text": "PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available." }, { "code": null, "e": 3204, "s": 2984, "text": "PyQt is a Python port of QT library. Our PyQt tutorial can be found here. Similarly, wxPython toolkit is Python binding for wxWidgets, another popular cross-platform GUI library. Our wxPython tutorial is available here." }, { "code": null, "e": 3430, "s": 3204, "text": "GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating graphical user interfaces. Offering a complete set of widgets, GTK+ is suitable for projects ranging from small one-off tools to complete application suites." }, { "code": null, "e": 3546, "s": 3430, "text": "GTK+ has been designed from the ground up to support a wide range of languages. PyGTK is a Python wrapper for GTK+." }, { "code": null, "e": 3598, "s": 3546, "text": "GTK+ is built around the following four libraries −" }, { "code": null, "e": 3703, "s": 3598, "text": "Glib − A low-level core library that forms the basis of GTK+. It provides data structure handling for C." }, { "code": null, "e": 3808, "s": 3703, "text": "Glib − A low-level core library that forms the basis of GTK+. It provides data structure handling for C." }, { "code": null, "e": 3901, "s": 3808, "text": "Pango − A library for layout and rendering of text with an emphasis on internationalization." }, { "code": null, "e": 3994, "s": 3901, "text": "Pango − A library for layout and rendering of text with an emphasis on internationalization." }, { "code": null, "e": 4108, "s": 3994, "text": "Cairo − A library for 2D graphics with support for multiple output devices (including the X Window System, Win32)" }, { "code": null, "e": 4222, "s": 4108, "text": "Cairo − A library for 2D graphics with support for multiple output devices (including the X Window System, Win32)" }, { "code": null, "e": 4359, "s": 4222, "text": "ATK − A library for a set of interfaces providing accessibility tools such as screen readers, magnifiers, and alternative input devices." }, { "code": null, "e": 4496, "s": 4359, "text": "ATK − A library for a set of interfaces providing accessibility tools such as screen readers, magnifiers, and alternative input devices." }, { "code": null, "e": 4862, "s": 4496, "text": "PyGTK eases the process and helps you create programs with a graphical user interface using the Python programming language. The underlying GTK+ library provides all kinds of visual elements and utilities for it to develop full-featured applications for the GNOME Desktop. PyGTK is a cross-platform library. It is a free software distributed under the LGPL license." }, { "code": null, "e": 4978, "s": 4862, "text": "PyGTK is built around GTK + 2.x. In order to build applications for GTK +3, PyGObject bindings are also available. " }, { "code": null, "e": 5057, "s": 4978, "text": "The installation of PyGTK for Microsoft Windows involves the following steps −" }, { "code": null, "e": 5135, "s": 5057, "text": "Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution)" }, { "code": null, "e": 5213, "s": 5135, "text": "Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution)" }, { "code": null, "e": 5257, "s": 5213, "text": "Step 2 − Download and install GTK+ runtime." }, { "code": null, "e": 5301, "s": 5257, "text": "Step 2 − Download and install GTK+ runtime." }, { "code": null, "e": 5367, "s": 5301, "text": "Step 3 − Download and install GTK+ runtime −https://ftp.gnome.org" }, { "code": null, "e": 5433, "s": 5367, "text": "Step 3 − Download and install GTK+ runtime −https://ftp.gnome.org" }, { "code": null, "e": 5587, "s": 5433, "text": "Step 4 − It is also recommended that you download PyCairo and PyGobject modules from the following URLs −\nhttps://ftp.gnome.org\nhttps://ftp.gnome.org/pub" }, { "code": null, "e": 5741, "s": 5587, "text": "Step 4 − It is also recommended that you download PyCairo and PyGobject modules from the following URLs −\nhttps://ftp.gnome.org\nhttps://ftp.gnome.org/pub" }, { "code": null, "e": 5973, "s": 5741, "text": "Step 5 − For convenience, all-in-one installer which handles all of the PyGTK dependencies is also available. Download and install the latest all-in-one installer for Windows from the following URL − https://ftp.gnome.org/pub/GNOME" }, { "code": null, "e": 6205, "s": 5973, "text": "Step 5 − For convenience, all-in-one installer which handles all of the PyGTK dependencies is also available. Download and install the latest all-in-one installer for Windows from the following URL − https://ftp.gnome.org/pub/GNOME" }, { "code": null, "e": 6373, "s": 6205, "text": "PyGTK is included in most Linux distributions (including Debian, Fedora, Ubuntu,RedHat etc); the source code can also be downloaded and compiled from the following URL" }, { "code": null, "e": 6425, "s": 6373, "text": "https://ftp.gnome.org/pub/GNOME/sources/pygtk/2.24/" }, { "code": null, "e": 6535, "s": 6425, "text": "Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code." }, { "code": null, "e": 6547, "s": 6535, "text": "import gtk\n" }, { "code": null, "e": 6669, "s": 6547, "text": "The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window." }, { "code": null, "e": 6695, "s": 6669, "text": "class PyApp(gtk.Window):\n" }, { "code": null, "e": 6774, "s": 6695, "text": "Define the constructor and call the show_all() method of the gtk.window class." }, { "code": null, "e": 6847, "s": 6774, "text": "def __init__(self):\n super(PyApp, self).__init__()\n self.show_all()\n" }, { "code": null, "e": 6949, "s": 6847, "text": "We now have to declare the object of this class and start an event loop by calling its main() method." }, { "code": null, "e": 6969, "s": 6949, "text": "PyApp()\ngtk.main()\n" }, { "code": null, "e": 7038, "s": 6969, "text": "It is recommended we add a label “Hello World” in the parent window." }, { "code": null, "e": 7088, "s": 7038, "text": "label = gtk.Label(\"Hello World\")\nself.add(label)\n" }, { "code": null, "e": 7147, "s": 7088, "text": "The following is a complete code to display “Hello World”−" }, { "code": null, "e": 7427, "s": 7147, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_default_size(300,200)\n self.set_title(\"Hello World in PyGTK\")\n label = gtk.Label(\"Hello World\")\n self.add(label)\n self.show_all()\nPyApp()\ngtk.main()" }, { "code": null, "e": 7498, "s": 7427, "text": "The implementation of the above code will yield the following output −" }, { "code": null, "e": 7805, "s": 7498, "text": "The PyGTK module contains various widgets. gtk.Object class acts as the base class for most of the widgets as well as for some non-widget classes. The toplevel window for desktop applications using PyGTK is provided by gtk.Window class. The following table lists the important widgets and their functions −" }, { "code": null, "e": 7816, "s": 7805, "text": "gtk.Widget" }, { "code": null, "e": 7937, "s": 7816, "text": "This is a gtk.base class for all PyGTK widgets. gtk.Widget provides a common set of methods and signals for the widgets." }, { "code": null, "e": 7948, "s": 7937, "text": "gtk.Window" }, { "code": null, "e": 8126, "s": 7948, "text": "This is a toplevel window that holds one child widget. gtk.Window is a display area decorated with a title bar, and items to allow the user to close, resize and move the window." }, { "code": null, "e": 8137, "s": 8126, "text": "gtk.Button" }, { "code": null, "e": 8319, "s": 8137, "text": "This is a pushbutton widget that issues a signal when clicked. gtk.Button is usually displayed as a pushbutton with a text label and is generally used to attach a callback function." }, { "code": null, "e": 8329, "s": 8319, "text": "gtk.Entry" }, { "code": null, "e": 8370, "s": 8329, "text": "This is a single line text entry widget." }, { "code": null, "e": 8380, "s": 8370, "text": "gtk.Label" }, { "code": null, "e": 8437, "s": 8380, "text": "This widget displays a limited amount of read-only text." }, { "code": null, "e": 8451, "s": 8437, "text": "gtk.ButtonBox" }, { "code": null, "e": 8516, "s": 8451, "text": "This is a base class for widgets that contains multiple buttons." }, { "code": null, "e": 8525, "s": 8516, "text": "gtk.HBox" }, { "code": null, "e": 8608, "s": 8525, "text": "This is a container that organizes its child widgets into a single horizontal row." }, { "code": null, "e": 8617, "s": 8608, "text": "gtk.VBox" }, { "code": null, "e": 8692, "s": 8617, "text": "This is a container that organizes its child widgets into a single column." }, { "code": null, "e": 8702, "s": 8692, "text": "gtk.Fixed" }, { "code": null, "e": 8809, "s": 8702, "text": "This is a container that can place child widgets at fixed positions and with fixed sizes, given in pixels." }, { "code": null, "e": 8820, "s": 8809, "text": "gtk.Layout" }, { "code": null, "e": 8904, "s": 8820, "text": "This provides infinite scrollable area containing child widgets and custom drawing." }, { "code": null, "e": 8917, "s": 8904, "text": "gtk.MenuItem" }, { "code": null, "e": 9169, "s": 8917, "text": "This widget implements the appearance and behavior of menu items. The derived widget subclasses of the gtk.MenuItem are the only valid children of menus. When selected by a user, they can display a popup menu or invoke an associated function or method" }, { "code": null, "e": 9178, "s": 9169, "text": "gtk.Menu" }, { "code": null, "e": 9326, "s": 9178, "text": "This is a dropdown menu consisting of a list of MenuItem objects which can be navigated and activated by the user to perform application functions." }, { "code": null, "e": 9338, "s": 9326, "text": "gtk.MenuBar" }, { "code": null, "e": 9416, "s": 9338, "text": "This displays the menu items horizontally in an application window or dialog." }, { "code": null, "e": 9429, "s": 9416, "text": "gtk.ComboBox" }, { "code": null, "e": 9481, "s": 9429, "text": "This widget is used to choose from a list of items." }, { "code": null, "e": 9491, "s": 9481, "text": "gtk.Scale" }, { "code": null, "e": 9566, "s": 9491, "text": "This is a horizontal or vertical slider control to select a numeric value." }, { "code": null, "e": 9580, "s": 9566, "text": "gtk.Scrollbar" }, { "code": null, "e": 9630, "s": 9580, "text": "This displays a horizontal or vertical scrollbar." }, { "code": null, "e": 9646, "s": 9630, "text": "gtk.ProgressBar" }, { "code": null, "e": 9712, "s": 9646, "text": "This is used to display the progress of a long running operation." }, { "code": null, "e": 9723, "s": 9712, "text": "gtk.Dialog" }, { "code": null, "e": 9785, "s": 9723, "text": "This displays a popup window for user information and action." }, { "code": null, "e": 9798, "s": 9785, "text": "gtk.Notebook" }, { "code": null, "e": 9909, "s": 9798, "text": "This widget is a container whose children are overlapping pages that can be switched between using tab labels." }, { "code": null, "e": 9919, "s": 9909, "text": "gtk.Paned" }, { "code": null, "e": 10131, "s": 9919, "text": "This is a base class for widgets with two panes, arranged either horizontally or vertically. Child widgets are added to the panes of the widget. The division between the two children can be adjusted by the user." }, { "code": null, "e": 10144, "s": 10131, "text": "gtk.TextView" }, { "code": null, "e": 10202, "s": 10144, "text": "This widget displays the contents of a TextBuffer object." }, { "code": null, "e": 10214, "s": 10202, "text": "gtk.Toolbar" }, { "code": null, "e": 10309, "s": 10214, "text": "This container holds and manages a set of buttons and widgets in a horizontal or vertical bar." }, { "code": null, "e": 10322, "s": 10309, "text": "gtk.TreeView" }, { "code": null, "e": 10416, "s": 10322, "text": "This widget displays the contents of standard TreeModel (ListStore, TreeStore, TreeModelSort)" }, { "code": null, "e": 10432, "s": 10416, "text": "gtk.DrawingArea" }, { "code": null, "e": 10582, "s": 10432, "text": "This widget helps in creating custom user interface elements. gtk.DrawingArea is essentially a blank widget containing a window that you can draw on." }, { "code": null, "e": 10595, "s": 10582, "text": "gtk.Calendar" }, { "code": null, "e": 10665, "s": 10595, "text": "This widget displays a calendar and allows the user to select a date." }, { "code": null, "e": 10678, "s": 10665, "text": "gtk.Viewport" }, { "code": null, "e": 10729, "s": 10678, "text": "This widget displays a portion of a larger widget." }, { "code": null, "e": 10967, "s": 10729, "text": "An object of the gtk.Window class provides a widget that users commonly think of as a Wwindow. This widget is a container hence, it can hold one child widget. It provides a displayable area decorated with title bar and resizing controls." }, { "code": null, "e": 11016, "s": 10967, "text": "gtk.Window class has the following constructor −" }, { "code": null, "e": 11034, "s": 11016, "text": "gtk.Window(type)\n" }, { "code": null, "e": 11084, "s": 11034, "text": "Type paramter takes one of the following values −" }, { "code": null, "e": 11157, "s": 11084, "text": "Some of the important methods of the gtk.Window class are listed below −" }, { "code": null, "e": 11175, "s": 11157, "text": "set_title(string)" }, { "code": null, "e": 11319, "s": 11175, "text": "This sets the \"title\" property of the gtk.window to the value specified by the title. The title of a window will be displayed in its title bar." }, { "code": null, "e": 11331, "s": 11319, "text": "get_title()" }, { "code": null, "e": 11374, "s": 11331, "text": "This returns the title of a window if set." }, { "code": null, "e": 11389, "s": 11374, "text": "set_position()" }, { "code": null, "e": 11463, "s": 11389, "text": "This sets the position of window. The predefined position\nconstants are −" }, { "code": null, "e": 11480, "s": 11463, "text": "gtk.WIN_POS_NONE" }, { "code": null, "e": 11497, "s": 11480, "text": "gtk.WIN_POS_NONE" }, { "code": null, "e": 11516, "s": 11497, "text": "gtk.WIN_POS_CENTER" }, { "code": null, "e": 11535, "s": 11516, "text": "gtk.WIN_POS_CENTER" }, { "code": null, "e": 11553, "s": 11535, "text": "gtk.WIN_POS_MOUSE" }, { "code": null, "e": 11571, "s": 11553, "text": "gtk.WIN_POS_MOUSE" }, { "code": null, "e": 11597, "s": 11571, "text": "gtk.WIN_POS_CENTER_ALWAYS" }, { "code": null, "e": 11623, "s": 11597, "text": "gtk.WIN_POS_CENTER_ALWAYS" }, { "code": null, "e": 11652, "s": 11623, "text": "gtk.WIN_POS_CENTER_ON_PARENT" }, { "code": null, "e": 11681, "s": 11652, "text": "gtk.WIN_POS_CENTER_ON_PARENT" }, { "code": null, "e": 11693, "s": 11681, "text": "set_focus()" }, { "code": null, "e": 11763, "s": 11693, "text": "This sets the widget specified to be the focus widget for the window." }, { "code": null, "e": 11779, "s": 11763, "text": "set_resizable()" }, { "code": null, "e": 11864, "s": 11779, "text": "This is true by default. set_resizable() helps the user to set the size of a window." }, { "code": null, "e": 11880, "s": 11864, "text": "set_decorated()" }, { "code": null, "e": 11983, "s": 11880, "text": "This is true by default. If false, the title bar and the resizing controls of window will be disabled." }, { "code": null, "e": 11995, "s": 11983, "text": "set_modal()" }, { "code": null, "e": 12115, "s": 11995, "text": "If true, window becomes modal and the interaction with other windows is prevented. This is used for the Dialog widgets." }, { "code": null, "e": 12134, "s": 12115, "text": "set_default_size()" }, { "code": null, "e": 12220, "s": 12134, "text": "This sets the default size of the window to the specified width and height in pixels." }, { "code": null, "e": 12272, "s": 12220, "text": "The gtk.Window widget emits the following signals −" }, { "code": null, "e": 12454, "s": 12272, "text": "The gtk.Button widget is usually displayed as a pushbutton with a text label. It is generally used to attach a callback function or method that is called when the button is clicked." }, { "code": null, "e": 12507, "s": 12454, "text": "The gtk.Button class has the following constructor −" }, { "code": null, "e": 12569, "s": 12507, "text": "gtk.Button(label = None, stock = None, use_underline = True)\n" }, { "code": null, "e": 12578, "s": 12569, "text": "Wherein," }, { "code": null, "e": 12631, "s": 12578, "text": "Label − The text to be displayed by the button label" }, { "code": null, "e": 12684, "s": 12631, "text": "Label − The text to be displayed by the button label" }, { "code": null, "e": 12785, "s": 12684, "text": "Stock − The stock id identifying the stock image and text to be used in the button.\nDefault is None." }, { "code": null, "e": 12886, "s": 12785, "text": "Stock − The stock id identifying the stock image and text to be used in the button.\nDefault is None." }, { "code": null, "e": 13022, "s": 12886, "text": "Underline − If True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator." }, { "code": null, "e": 13158, "s": 13022, "text": "Underline − If True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator." }, { "code": null, "e": 13217, "s": 13158, "text": "Some of the predefined constants for stock parameter are −" }, { "code": null, "e": 13226, "s": 13217, "text": "STOCK_OK" }, { "code": null, "e": 13237, "s": 13226, "text": "STOCK_STOP" }, { "code": null, "e": 13247, "s": 13237, "text": "STOCK_YES" }, { "code": null, "e": 13256, "s": 13247, "text": "STOCK_NO" }, { "code": null, "e": 13267, "s": 13256, "text": "STOCK_QUIT" }, { "code": null, "e": 13280, "s": 13267, "text": "STOCK_CANCEL" }, { "code": null, "e": 13292, "s": 13280, "text": "STOCK_CLOSE" }, { "code": null, "e": 13347, "s": 13292, "text": "The Button class has the following important methods −" }, { "code": null, "e": 13359, "s": 13347, "text": "set_label()" }, { "code": null, "e": 13495, "s": 13359, "text": "This sets the text of the button label to label. This string is also used to select the stock item if the \"use_stock\" property is True." }, { "code": null, "e": 13507, "s": 13495, "text": "get_label()" }, { "code": null, "e": 13560, "s": 13507, "text": "This retrieves the text from the label of the button" }, { "code": null, "e": 13581, "s": 13560, "text": "set_focus_on_click()" }, { "code": null, "e": 13642, "s": 13581, "text": "If True, the button grabs focus when clicked with the mouse." }, { "code": null, "e": 13658, "s": 13642, "text": "set_alignment()" }, { "code": null, "e": 13759, "s": 13658, "text": "This is the horizontal and vertical alignment of the child widget. The value ranges from 0.0 to 1.0." }, { "code": null, "e": 13771, "s": 13759, "text": "set_image()" }, { "code": null, "e": 13878, "s": 13771, "text": "This sets the image property to the value of image. The \"gtkbutton-images\" property should be set to True." }, { "code": null, "e": 13935, "s": 13878, "text": "The following signals are emitted by the Button widget −" }, { "code": null, "e": 14208, "s": 13935, "text": "A Label widget is useful to display non-editable text. Label is used by many other widgets internally. For example, Button has a label to show text on the face. Similarly, MenuItem objects have a label. A label is a windowless object, so it cannot receive events directly." }, { "code": null, "e": 14247, "s": 14208, "text": "Label class has a simple constructor −" }, { "code": null, "e": 14270, "s": 14247, "text": "gtk.Label(str = None)\n" }, { "code": null, "e": 14331, "s": 14270, "text": "The following useful methods can be used with Label object −" }, { "code": null, "e": 14342, "s": 14331, "text": "set_text()" }, { "code": null, "e": 14370, "s": 14342, "text": "This sets new text as label" }, { "code": null, "e": 14381, "s": 14370, "text": "get_text()" }, { "code": null, "e": 14410, "s": 14381, "text": "This returns text from label" }, { "code": null, "e": 14430, "s": 14410, "text": "set_use_underline()" }, { "code": null, "e": 14543, "s": 14430, "text": "If true, an underscore in the text indicates the next character should be used for the mnemonic accelerator key." }, { "code": null, "e": 14555, "s": 14543, "text": "set_justify" }, { "code": null, "e": 14641, "s": 14555, "text": "This sets the alignment of the lines in the text of the label relative to each other." }, { "code": null, "e": 14742, "s": 14641, "text": "Possible values are – gtk.JUSTIFY_LEFT, gtk.JUSTIFY_RIGHT, gtk.JUSTIFY_CENTER, and gtk.JUSTIFY_FILL." }, { "code": null, "e": 14758, "s": 14742, "text": "Set_line_wrap()" }, { "code": null, "e": 14792, "s": 14758, "text": "If true, the line will be wrapped" }, { "code": null, "e": 14809, "s": 14792, "text": "set_selectable()" }, { "code": null, "e": 14871, "s": 14809, "text": "If true, the text in the label can be selected for copy-paste" }, { "code": null, "e": 14889, "s": 14871, "text": "set_width_chars()" }, { "code": null, "e": 14920, "s": 14889, "text": "This sets the width of a label" }, { "code": null, "e": 14972, "s": 14920, "text": "The following signals are emitted by label widget −" }, { "code": null, "e": 15149, "s": 14972, "text": "Entry widget is a single-line text entry widget. If the entered text is longer than the allocation of the widget, the widget will scroll so that the cursor position is visible." }, { "code": null, "e": 15335, "s": 15149, "text": "Entry field can be converted in password mode using set_visibility() method of this class. Entered text is substituted by character chosen by invisible_char() method, default being '*'." }, { "code": null, "e": 15383, "s": 15335, "text": "The Entry class has the following constructor −" }, { "code": null, "e": 15403, "s": 15383, "text": "gtk.Entry(max = 0)\n" }, { "code": null, "e": 15516, "s": 15403, "text": "Here, max stands for maximum length of entry field in characters. The parameter takes a numeric value (0-65536)." }, { "code": null, "e": 15584, "s": 15516, "text": "The following table shows the important methods of an Entry class −" }, { "code": null, "e": 15608, "s": 15584, "text": "set_visibility(visible)" }, { "code": null, "e": 15715, "s": 15608, "text": "If false, the contents are obscured by replacing the characters with the default invisible character — '*'" }, { "code": null, "e": 15740, "s": 15715, "text": "set_invisible_char(char)" }, { "code": null, "e": 15807, "s": 15740, "text": "The default '*' characters in the entry field are replaced by char" }, { "code": null, "e": 15825, "s": 15807, "text": "set_max_length(x)" }, { "code": null, "e": 15890, "s": 15825, "text": "This sets the \"max-length\" property to the value of x. (0-65536)" }, { "code": null, "e": 15904, "s": 15890, "text": "set_text(str)" }, { "code": null, "e": 16017, "s": 15904, "text": "This sets the \"text\" property to the value of str. The string in str replaces the current contents of the entry." }, { "code": null, "e": 16028, "s": 16017, "text": "get_text()" }, { "code": null, "e": 16130, "s": 16028, "text": "This returns the value of the \"text\" property which is a string containing the contents of the entry." }, { "code": null, "e": 16146, "s": 16130, "text": "set_alignment()" }, { "code": null, "e": 16290, "s": 16146, "text": "This sets the \"xalign\" property to the value of xalign. set_alignment() controls the horizontal positioning of the contents in the Entry field." }, { "code": null, "e": 16342, "s": 16290, "text": "The following signals are emitted by entry widget −" }, { "code": null, "e": 16588, "s": 16342, "text": "Unlike a console mode application, which is executed in a sequential manner, a GUI-based application is event driven. The gtk.main() function starts an infinite loop. Events occurring on the GUI are transferred to appropriate callback functions." }, { "code": null, "e": 16814, "s": 16588, "text": "Each PyGTK widget, which is derived from the GObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a callback function." }, { "code": null, "e": 16967, "s": 16814, "text": "Some signals are inherited by the widget, whereas some signals are widget specific. For example, \"toggled\" signal is emitted by the toggleButton widget." }, { "code": null, "e": 17052, "s": 16967, "text": "A signal handler is set up by invoking the connect() method of the gtk.widget class." }, { "code": null, "e": 17104, "s": 17052, "text": "handler_id = object.connect(name, func, func_data)\n" }, { "code": null, "e": 17195, "s": 17104, "text": "The first argument, name, is a string containing the name of the signal you wish to catch." }, { "code": null, "e": 17286, "s": 17195, "text": "The first argument, name, is a string containing the name of the signal you wish to catch." }, { "code": null, "e": 17380, "s": 17286, "text": "The second argument, func, is the call back function you wish to be called when it is caught." }, { "code": null, "e": 17474, "s": 17380, "text": "The second argument, func, is the call back function you wish to be called when it is caught." }, { "code": null, "e": 17549, "s": 17474, "text": "The third argument, func_data, the data you wish to pass to this function." }, { "code": null, "e": 17624, "s": 17549, "text": "The third argument, func_data, the data you wish to pass to this function." }, { "code": null, "e": 17696, "s": 17624, "text": "The handler id, which is used to uniquely identify the callback method." }, { "code": null, "e": 17768, "s": 17696, "text": "The handler id, which is used to uniquely identify the callback method." }, { "code": null, "e": 17865, "s": 17768, "text": "For example, to invoke onClicked() function when a button is clicked, use the following syntax −" }, { "code": null, "e": 17904, "s": 17865, "text": "btn.connect(\"clicked\",onClicked,None)\n" }, { "code": null, "e": 17945, "s": 17904, "text": "The onClicked() function is defined as −" }, { "code": null, "e": 17980, "s": 17945, "text": "def onClicked(widget, data=None):\n" }, { "code": null, "e": 18069, "s": 17980, "text": "If the callback method is an object method, it receives self as an additional argument −" }, { "code": null, "e": 18110, "s": 18069, "text": "def onClicked(self, widget, data=None):\n" }, { "code": null, "e": 18230, "s": 18110, "text": "In the following example, a Button is added to gtk.Window. “Hello World” message is printed when the button is clicked." }, { "code": null, "e": 18892, "s": 18230, "text": "import gtk\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Hello World in PyGTK\")\n self.set_default_size(400,300)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n self.label = gtk.Label(\"Enter name\")\n self.entry = gtk.Entry()\n\t\t\n self.btn = gtk.Button(\"Say Hello\")\n self.btn.connect(\"clicked\",self.hello)\n\t\t\n fixed = gtk.Fixed()\n fixed.put(self.label, 100,100)\n fixed.put(self.entry, 100,125)\n fixed.put(self.btn,100,150)\n\t\t\n self.add(fixed)\n self.show_all()\n\t\t\n def hello(self,widget):\n print \"hello\",self.entry.get_text()\nPyApp()\ngtk.main()" }, { "code": null, "e": 18972, "s": 18892, "text": "Run the above code from Python prompt. The following output will be displayed −" }, { "code": null, "e": 19051, "s": 18972, "text": "When the button is pressed, the following output is displayed on the console −" }, { "code": null, "e": 19073, "s": 19051, "text": "Hello TutorialsPoint\n" }, { "code": null, "e": 19390, "s": 19073, "text": "In addition to the signal mechanism, window system events can also be connected to callback functions. Window resizing, key press, scroll event etc. are some of common window system events. These events are reported to application's main loop. From there, they are passed along via signals to the callback functions." }, { "code": null, "e": 19435, "s": 19390, "text": "Some of the system events are listed below −" }, { "code": null, "e": 19454, "s": 19435, "text": "button_press_event" }, { "code": null, "e": 19475, "s": 19454, "text": "button_release_event" }, { "code": null, "e": 19488, "s": 19475, "text": "scroll_event" }, { "code": null, "e": 19508, "s": 19488, "text": "motion_notify_event" }, { "code": null, "e": 19521, "s": 19508, "text": "delete_event" }, { "code": null, "e": 19535, "s": 19521, "text": "destroy_event" }, { "code": null, "e": 19548, "s": 19535, "text": "expose_event" }, { "code": null, "e": 19564, "s": 19548, "text": "key_press_event" }, { "code": null, "e": 19582, "s": 19564, "text": "key_release_event" }, { "code": null, "e": 19680, "s": 19582, "text": "The connect() method is used to associate the event with callback function following the syntax −" }, { "code": null, "e": 19718, "s": 19680, "text": "Object.connect(name, function, data)\n" }, { "code": null, "e": 19964, "s": 19718, "text": "Here, name stands for the string corresponding to the name of event which is to be captured. And, function is name of the callback function that is to be called when an event occurs. Data is the argument to be passed on to the callback function." }, { "code": null, "e": 20053, "s": 19964, "text": "Hence, the following code connects a Button widget and captures the button_press event −" }, { "code": null, "e": 20105, "s": 20053, "text": "self.btn.connect(\"button_press_event\", self.hello)\n" }, { "code": null, "e": 20163, "s": 20105, "text": "The following will be the Prototype of hello() function −" }, { "code": null, "e": 20194, "s": 20163, "text": "def hello(self,widget,event):\n" }, { "code": null, "e": 20247, "s": 20194, "text": "The following is the code for button event handler −" }, { "code": null, "e": 20925, "s": 20247, "text": "import gtk\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Hello World in PyGTK\")\n self.set_default_size(400,300)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n self.label = gtk.Label(\"Enter name\")\n self.entry = gtk.Entry()\n self.btn = gtk.Button(\"Say Hello\")\n self.btn.connect(\"button_press_event\", self.hello)\n\t\t\n fixed = gtk.Fixed()\n fixed.put(self.label, 100,100)\n fixed.put(self.entry, 100,125)\n fixed.put(self.btn,100,150)\n\t\t\n self.add(fixed)\n self.show_all()\n\t\t\n def hello(self,widget,event):\n print \"hello\",self.entry.get_text()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 21004, "s": 20925, "text": "When you run the above code, it displays the following output on the console −" }, { "code": null, "e": 21026, "s": 21004, "text": "Hello TutorialsPoint\n" }, { "code": null, "e": 21268, "s": 21026, "text": "PyGTK library provides different container classes to control the placement of widgets inside a window. The easiest way is to use a fixed container class and place a widget inside it by specifying its absolute coordinates measured in pixels." }, { "code": null, "e": 21300, "s": 21268, "text": "Let us now follow these steps −" }, { "code": null, "e": 21346, "s": 21300, "text": "Step 1 − Declare an object of the fixed class" }, { "code": null, "e": 21367, "s": 21346, "text": "fixed = gtk.Fixed()\n" }, { "code": null, "e": 21543, "s": 21367, "text": "Step 2 − Create a button widget and add it to the fixed container by using put() method which needs x and y coordinates. Here, the button will be placed at (100,100) position." }, { "code": null, "e": 21594, "s": 21543, "text": "btn = gtk.Button(\"Hello\")\nfixed.put(btn, 100,100)\n" }, { "code": null, "e": 21728, "s": 21594, "text": "Step 3 − You can place multiple controls in the fixed container. And, add it to the top-level\nwindow and invoke the show_all() method" }, { "code": null, "e": 21761, "s": 21728, "text": "self.add(fixed)\nself.show_all()\n" }, { "code": null, "e": 21843, "s": 21761, "text": "This Absolute Layout, however, is not suitable because of the following reasons −" }, { "code": null, "e": 21917, "s": 21843, "text": "The position of the widget does not change even if the window is resized." }, { "code": null, "e": 22008, "s": 21917, "text": "The appearance may not be uniform on different display devices with different resolutions." }, { "code": null, "e": 22095, "s": 22008, "text": "Modification in the layout is difficult as it may need redesigning of the entire form." }, { "code": null, "e": 22134, "s": 22095, "text": "The following is the original window −" }, { "code": null, "e": 22172, "s": 22134, "text": "The following is the resized window −" }, { "code": null, "e": 22218, "s": 22172, "text": "The position of the button is unchanged here." }, { "code": null, "e": 22393, "s": 22218, "text": "PyGTK API provides container classes for enhanced management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −" }, { "code": null, "e": 22446, "s": 22393, "text": "Widgets inside the window are automatically resized." }, { "code": null, "e": 22520, "s": 22446, "text": "Ensures uniform appearance on display devices with different resolutions." }, { "code": null, "e": 22598, "s": 22520, "text": "Adding or removing widget dynamically is possible without having to redesign." }, { "code": null, "e": 22663, "s": 22598, "text": "gtk.Container acts as the base class for the following classes −" }, { "code": null, "e": 22677, "s": 22663, "text": "gtk.ButtonBox" }, { "code": null, "e": 22685, "s": 22677, "text": "gtk.Box" }, { "code": null, "e": 22699, "s": 22685, "text": "gtk.Alignment" }, { "code": null, "e": 22712, "s": 22699, "text": "gtk.EventBox" }, { "code": null, "e": 22722, "s": 22712, "text": "gtk.Table" }, { "code": null, "e": 22905, "s": 22722, "text": "The gtk.Box class is an abstract class defining the functionality of a container in which widgets are placed in a rectangular area. gtk.HBox and gtk.VBox widgets are derived from it." }, { "code": null, "e": 23063, "s": 22905, "text": "Child widgets in gtk.Hbox are arranged horizontally in the same row. On the other hand, child widgets of gtk.VBox are arranged vertically in the same column." }, { "code": null, "e": 23110, "s": 23063, "text": "gtk.Box class uses the following constructor −" }, { "code": null, "e": 23151, "s": 23110, "text": "gtk.Box(homogenous = True, spacing = 0)\n" }, { "code": null, "e": 23261, "s": 23151, "text": "The homogenous property is set to True by default. As a result, all child widgets are given equal allocation." }, { "code": null, "e": 23608, "s": 23261, "text": "gtk.Box uses the packing mechanism to place child widgets in it with reference to a particular position, either with reference to start or end. pack_start() method places widgets from start to end. On the contrary, the pack_end() method puts widgets from end to start. Alternatively, you can use the add() method which is similar to pack_start()." }, { "code": null, "e": 23679, "s": 23608, "text": "The following methods are available for gtk.HBox as well as gtk.VBox −" }, { "code": null, "e": 23701, "s": 23679, "text": "gtk_box_pack_start ()" }, { "code": null, "e": 23723, "s": 23701, "text": "gtk_box_pack_start ()" }, { "code": null, "e": 23743, "s": 23723, "text": "gtk_box_pack_end ()" }, { "code": null, "e": 23763, "s": 23743, "text": "gtk_box_pack_end ()" }, { "code": null, "e": 23842, "s": 23763, "text": "This method adds child to the box, packed with reference to the start of box −" }, { "code": null, "e": 23902, "s": 23842, "text": "pack_start(child, expand = True, fill = True, padding = 0)\n" }, { "code": null, "e": 23937, "s": 23902, "text": "The following are the parameters −" }, { "code": null, "e": 23990, "s": 23937, "text": "child − This is the widget object to be added to box" }, { "code": null, "e": 24043, "s": 23990, "text": "child − This is the widget object to be added to box" }, { "code": null, "e": 24170, "s": 24043, "text": "expand − This is set to True if child is to be given extra space in the box. Extra space is divided between all child widgets." }, { "code": null, "e": 24297, "s": 24170, "text": "expand − This is set to True if child is to be given extra space in the box. Extra space is divided between all child widgets." }, { "code": null, "e": 24399, "s": 24297, "text": "fill − If True, extra space will be allocated to child. Otherwise, this parameter is used as padding." }, { "code": null, "e": 24501, "s": 24399, "text": "fill − If True, extra space will be allocated to child. Otherwise, this parameter is used as padding." }, { "code": null, "e": 24567, "s": 24501, "text": "padding − This is the space in pixels between widgets in the box." }, { "code": null, "e": 24633, "s": 24567, "text": "padding − This is the space in pixels between widgets in the box." }, { "code": null, "e": 24706, "s": 24633, "text": "This adds child to the box, packed with reference to the end of the box." }, { "code": null, "e": 24765, "s": 24706, "text": "pack_end (child, expand = True, fill = True, padding = 0)\n" }, { "code": null, "e": 24800, "s": 24765, "text": "The following are the parameters −" }, { "code": null, "e": 24846, "s": 24800, "text": "child − This is the widget object to be added" }, { "code": null, "e": 24892, "s": 24846, "text": "child − This is the widget object to be added" }, { "code": null, "e": 25024, "s": 24892, "text": "expand − This is set to True if child is to be given extra space in the box. This extra space is divided between all child widgets." }, { "code": null, "e": 25156, "s": 25024, "text": "expand − This is set to True if child is to be given extra space in the box. This extra space is divided between all child widgets." }, { "code": null, "e": 25238, "s": 25156, "text": "fill − If True, extra space will be allocated to child otherwise used as padding." }, { "code": null, "e": 25320, "s": 25238, "text": "fill − If True, extra space will be allocated to child otherwise used as padding." }, { "code": null, "e": 25390, "s": 25320, "text": "padding − This is the space in pixels between the widgets in the box." }, { "code": null, "e": 25460, "s": 25390, "text": "padding − This is the space in pixels between the widgets in the box." }, { "code": null, "e": 25571, "s": 25460, "text": "set_spacing (spacing) is the function that sets the number of pixels to place between the children of the box." }, { "code": null, "e": 25731, "s": 25571, "text": "The method add (widget) is inherited from the gtk.Container class. It adds widget to the container. This method can be used instead of the pack_start() method." }, { "code": null, "e": 26037, "s": 25731, "text": "In the example given below, the toplevel window contains a vertical box (gtk.VBox object box). It in turn has a VBox object vb and HBox object hb. In the upper box, a label, an entry widget and a button are placed vertically. In the lower box, another set of label, entry and button are placed vertically." }, { "code": null, "e": 26066, "s": 26037, "text": "Observe the following code −" }, { "code": null, "e": 27004, "s": 26066, "text": "import gtk\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Box demo\")\n\t\t\n box = gtk.VBox()\n vb = gtk.VBox()\n lbl = gtk.Label(\"Enter name\")\n\t\t\n vb.pack_start(lbl, expand = True, fill = True, padding = 10)\n text = gtk.Entry()\n\t\t\n vb.pack_start(text, expand = True, fill = True, padding = 10)\n btn = gtk.Button(stock = gtk.STOCK_OK)\n\t\t\n vb.pack_start(btn, expand = True, fill = True, padding = 10)\n hb = gtk.HBox()\n\t\t\n lbl1 = gtk.Label(\"Enter marks\")\n hb.pack_start(lbl1, expand = True, fill = True, padding = 5)\n text1 = gtk.Entry()\n\t\t\n hb.pack_start(text1, expand = True, fill = True, padding = 5)\n btn1 = gtk.Button(stock = gtk.STOCK_SAVE)\n\t\t\n hb.pack_start(btn1, expand = True, fill = True, padding = 5)\n box.add(vb)\n box.add(hb)\n self.add(box)\n self.show_all()\nPyApp()\ngtk.main()" }, { "code": null, "e": 27055, "s": 27004, "text": "The above code will produce the following output −" }, { "code": null, "e": 27308, "s": 27055, "text": "The ButtonBox class in gtk API serves as a base class for containers to hold multiple buttons either horizontally or vertically. Two subclasses HButtonBox and VButtonBox are derived from the ButtonBox class, which itself is a subclass of gtk.Box class." }, { "code": null, "e": 27497, "s": 27308, "text": "A button box is used to provide a consistent layout of buttons throughout an application. It provides one default layout and a default spacing value that are persistent across all widgets." }, { "code": null, "e": 27620, "s": 27497, "text": "The set_spacing() method of the gtk.Box class can be used to change the default spacing between buttons in the button box." }, { "code": null, "e": 27741, "s": 27620, "text": "The default layout of buttons can be changed by the set_default() method. The possible values of the button layout are −" }, { "code": null, "e": 27762, "s": 27741, "text": "gtk.BUTTONBOX_SPREAD" }, { "code": null, "e": 27783, "s": 27762, "text": "gtk.BUTTONBOX_SPREAD" }, { "code": null, "e": 27802, "s": 27783, "text": "gtk.BUTTONBOX_EDGE" }, { "code": null, "e": 27821, "s": 27802, "text": "gtk.BUTTONBOX_EDGE" }, { "code": null, "e": 27841, "s": 27821, "text": "gtk.BUTTONBOX_START" }, { "code": null, "e": 27861, "s": 27841, "text": "gtk.BUTTONBOX_START" }, { "code": null, "e": 27880, "s": 27861, "text": "gtk.BUTTONBOX_END." }, { "code": null, "e": 27899, "s": 27880, "text": "gtk.BUTTONBOX_END." }, { "code": null, "e": 28115, "s": 27899, "text": "In the following example, a VBox object inside the toplevel window internally contains one VButtonBox object and one HButtonBox object, each containing two buttons, arranged vertically and horizontally respectively." }, { "code": null, "e": 28134, "s": 28115, "text": "Observe the code −" }, { "code": null, "e": 28995, "s": 28134, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"Button Box demo\")\n self.set_size_request(200,100)\n self.set_position(gtk.WIN_POS_CENTER)\n\t vb = gtk.VBox()\n box1 = gtk.VButtonBox()\n btn1 = gtk.Button(stock = gtk.STOCK_OK)\n btn2 = gtk.Button(stock = gtk.STOCK_CANCEL)\n\t\t\n box1.pack_start(btn1, True, True, 0)\n box1.pack_start(btn2, True, True, 0)\n box1.set_border_width(5)\n\t\t\n vb.add(box1)\n box2 = gtk.HButtonBox()\n btn3 = gtk.Button(stock = gtk.STOCK_OK)\n btn4 = gtk.Button(stock = gtk.STOCK_CANCEL)\n\t\t\n ent = gtk.Entry()\n box2.pack_start(btn3, True, True, 0)\n box2.pack_start(btn4, True, True, 0)\n box1.set_border_width(5)\n\t\t\n vb.add(box2)\n self.add(vb)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 29043, "s": 28995, "text": "The above code generates the following output −" }, { "code": null, "e": 29355, "s": 29043, "text": "This widget proves useful in controlling alignment and size of its child widgets. It has four properties called xalign, yalign, xscale and yscale. The scale properties specify how much of free space will be used by the child widgets. The align properties areused to place the child widget within available area." }, { "code": null, "e": 29599, "s": 29355, "text": "All four properties take up a float value between 0 and 1.0. If xscale and yscale property is set to 0, it means that widget absorbs none of free space and if set to 1, widget absorbs maximum free space horizontally or vertically respectively." }, { "code": null, "e": 29786, "s": 29599, "text": "The xalign and yalign property if set to 0, means that there will be no free space to the left or above widget. If set to 1, there will be maximum free space to left or above the widget." }, { "code": null, "e": 29842, "s": 29786, "text": "The gtk.alignment class has the following constructor −" }, { "code": null, "e": 29913, "s": 29842, "text": "gtk.alignment(xalign = 0.0, yalign = 0.0, xscale = 0.0, yscale = 0.0)\n" }, { "code": null, "e": 29920, "s": 29913, "text": "Where," }, { "code": null, "e": 30007, "s": 29920, "text": "xalign − Is the fraction of the horizontal free space to the left of the child widget." }, { "code": null, "e": 30094, "s": 30007, "text": "xalign − Is the fraction of the horizontal free space to the left of the child widget." }, { "code": null, "e": 30166, "s": 30094, "text": "yalign − Is the fraction of vertical free space above the child widget." }, { "code": null, "e": 30238, "s": 30166, "text": "yalign − Is the fraction of vertical free space above the child widget." }, { "code": null, "e": 30322, "s": 30238, "text": "xscale − Is is the fraction of horizontal free space that the child widget absorbs." }, { "code": null, "e": 30406, "s": 30322, "text": "xscale − Is is the fraction of horizontal free space that the child widget absorbs." }, { "code": null, "e": 30488, "s": 30406, "text": "yscale − Is is the fraction of vertical free space that the child widget absorbs." }, { "code": null, "e": 30570, "s": 30488, "text": "yscale − Is is the fraction of vertical free space that the child widget absorbs." }, { "code": null, "e": 30925, "s": 30570, "text": "The following code demonstrates the use of gtk.alignment widget. A Vbox in the toplevel window has an upper Vbox and lower Hbox placed in it. In the upper vertical box, a label and an Entry widget are placed such that towards the left, 50% of space is kept free and more than 25% of this is occupied by assigning 0.5 xalign and 0.25 to yalign properties." }, { "code": null, "e": 31109, "s": 30925, "text": "In the lower HBox, all the available free space is on the left side. This is achieved by assigning 1 to xalign property. Hence, two buttons in the horizontal box appear right aligned." }, { "code": null, "e": 32038, "s": 31109, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Alignment demo\")\n self.set_size_request(400,200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox(False, 5)\n vb = gtk.VBox()\n hbox = gtk.HBox(True, 3)\n valign = gtk.Alignment(0.5,0.25, 0, 0)\n\t\t\n lbl = gtk.Label(\"Name of student\")\n vb.pack_start(lbl, True, True, 10)\n text = gtk.Entry()\n\t\t\n vb.pack_start(text, True, True, 10)\n valign.add(vb)\n vbox.pack_start(valign)\n\t\t\n ok = gtk.Button(\"OK\")\n ok.set_size_request(70, 30)\n\t\t\n close = gtk.Button(\"Close\")\n hbox.add(ok)\n hbox.add(close)\n\t\t\n halign = gtk.Alignment(1, 0, 0, 0)\n halign.add(hbox)\n\t\t\n vbox.pack_start(halign, False, False, 3)\n\t\t\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\nPyApp()\ngtk.main()" }, { "code": null, "e": 32085, "s": 32038, "text": "The above code produces the following output −" }, { "code": null, "e": 32282, "s": 32085, "text": "Some widgets in PyGTK tool kit do not have their own window. Such windowless widgets cannot receive event signals. Such widgets, for example a label, if put inside an eventbox can receive signals." }, { "code": null, "e": 32412, "s": 32282, "text": "EventBox is an invisible container that provides window to windowless widgets. It has a simple constructor without any argument −" }, { "code": null, "e": 32428, "s": 32412, "text": "gtk.EventBox()\n" }, { "code": null, "e": 32835, "s": 32428, "text": "In the following example, two widgets of the gtk.EventBox are placed in the toplevel window. Inside each eventbox, a label is added. The eventbox is now connected to a callback function to process the button_press_event on it. As the eventbox itself is invisible, effectively the event occurs on the embedded label. Hence, as and when we click on any label, the corresponding callback function is invoked." }, { "code": null, "e": 32854, "s": 32835, "text": "Observe the code −" }, { "code": null, "e": 33721, "s": 32854, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"EventBox demo\")\n self.set_size_request(200,100)\n self.set_position(gtk.WIN_POS_CENTER)\n fixed = gtk.Fixed()\n \n event1 = gtk.EventBox()\n label1 = gtk.Label(\"Label 1\")\n event1.add(label1)\n fixed.put(event1, 80,20)\n \n event1.connect(\"button_press_event\",self.hello1)\n event2 = gtk.EventBox()\n label2 = gtk.Label(\"Label 2\")\n event2.add(label2)\n event2.connect(\"button_press_event\",self.hello2)\n fixed.put(event2, 80,70)\n \n self.add(fixed)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def hello1(self, widget, event):\n print \"clicked label 1\"\n\t\t\n def hello2(self, widget, event):\n print \"clicked label 2\"\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 33769, "s": 33721, "text": "The above code generates the following output −" }, { "code": null, "e": 33930, "s": 33769, "text": "When Label 1 is clicked on the console, the message \"clicked label 1\" gets printed. Similarly, when Label 2 is clicked on, \"clicked label 2\" message is printed." }, { "code": null, "e": 34131, "s": 33930, "text": "The gtk.Layout is a container widget similar to gtk.Fixed. Widgets are placed in Layout widget by specifying absolute coordinates. However, the Layout differs from fixed widget in the following ways −" }, { "code": null, "e": 34267, "s": 34131, "text": "The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer." }, { "code": null, "e": 34403, "s": 34267, "text": "The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer." }, { "code": null, "e": 34556, "s": 34403, "text": "A gtk.DrawingArea widget can be enclosed in a layout container. The DrawingArea is a canvas on which 2D elements like line, rectangle etc. can be drawn." }, { "code": null, "e": 34709, "s": 34556, "text": "A gtk.DrawingArea widget can be enclosed in a layout container. The DrawingArea is a canvas on which 2D elements like line, rectangle etc. can be drawn." }, { "code": null, "e": 34870, "s": 34709, "text": "In order to put the Layout container in the toplevel window of lesser dimensions, it can be associated with the scrollbars or can be placed in a ScrolledWindow." }, { "code": null, "e": 35031, "s": 34870, "text": "In order to put the Layout container in the toplevel window of lesser dimensions, it can be associated with the scrollbars or can be placed in a ScrolledWindow." }, { "code": null, "e": 35084, "s": 35031, "text": "The gtk.Layout class has the following constructor −" }, { "code": null, "e": 35135, "s": 35084, "text": "gtk.Layout(hadjustment = None, vadjustment = None)" }, { "code": null, "e": 35234, "s": 35135, "text": "The hadjustment and vadjustment properties represent an object having an adjustable bounded value." }, { "code": null, "e": 35308, "s": 35234, "text": "The following table lists out the frequently used methods of the layout −" }, { "code": null, "e": 35418, "s": 35308, "text": "The Layout object emits the set_scroll_adjustment signal when the adjustments associated with it are changed." }, { "code": null, "e": 35668, "s": 35418, "text": "In the following example, a Label is paced at the centre of a Layout container, which in turn is to be placed in a toplevel window of smaller size. Hence, it is first added to a ScrolledWindow and the ScrolledWindow is then added to the main window." }, { "code": null, "e": 35687, "s": 35668, "text": "Observe the code −" }, { "code": null, "e": 36173, "s": 35687, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"layout\")\n self.set_size_request(300,200)\n self.set_position(gtk.WIN_POS_CENTER)\n sc = gtk.ScrolledWindow()\n lo = gtk.Layout()\n lo.set_size(400,400)\n button = gtk.Button(\"Press Me\")\n lo.put(button, 125,200)\n sc.add(lo)\n self.add(sc)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 36225, "s": 36173, "text": "The above code will generate the following output −" }, { "code": null, "e": 36479, "s": 36225, "text": "ComboBox is a powerful and popular widget in any GUI toolkit. It provides a dropdown list of items from which a user can choose. The gtk.ComboBox widget implements the CellLayout interface and provides a number of methods to manage the display of items." }, { "code": null, "e": 36760, "s": 36479, "text": "The object of gtk.ComboBox class is associated with a ListSore, which is a list model that can be used with widgets that display collection of items. Items are added to ListStore with the append() method. Further, a CellRendererText object is created and packed into the combobox." }, { "code": null, "e": 36801, "s": 36760, "text": "Follow these steps to set up a combobox." }, { "code": null, "e": 36967, "s": 36801, "text": "combobox = gtk.ComboBox()\nstore = gtk.ListStore(gobject.TYPE_STRING)\ncell = gtk.CellRendererText()\ncombobox.pack_start(cell)\ncombobox.add_attribute(cell, 'text', 0)\n" }, { "code": null, "e": 37217, "s": 36967, "text": "PyGTK offers a convenience method — gtk.combo_box_new_text() to create a combo box instead of using a list store. Associated convenience methods append_text(), prepend_text(), insert_text() and remove_text() are used to manage the combo boxcontents." }, { "code": null, "e": 37264, "s": 37217, "text": "gtk.ComboBox class has the following methods −" }, { "code": null, "e": 37281, "s": 37264, "text": "set_wrap_width()" }, { "code": null, "e": 37350, "s": 37281, "text": "Sets the number of columns to be displayed in the popup table layout" }, { "code": null, "e": 37363, "s": 37350, "text": "get_active()" }, { "code": null, "e": 37467, "s": 37363, "text": "Returns the value of the \"active\" property which is the index in the model of the currently active item" }, { "code": null, "e": 37480, "s": 37467, "text": "set_active()" }, { "code": null, "e": 37561, "s": 37480, "text": "Sets the active item of the combo_box to the item with the model index specified" }, { "code": null, "e": 37573, "s": 37561, "text": "set_model()" }, { "code": null, "e": 37610, "s": 37573, "text": "Sets the model used by the combo box" }, { "code": null, "e": 37624, "s": 37610, "text": "append_text()" }, { "code": null, "e": 37719, "s": 37624, "text": "Appends the string specified by text to the list of strings stored in the combo box list store" }, { "code": null, "e": 37733, "s": 37719, "text": "Insert_text()" }, { "code": null, "e": 37836, "s": 37733, "text": "Inserts the string specified by text in the combo box gtk.ListStore at the index specified by position" }, { "code": null, "e": 37851, "s": 37836, "text": "prepend_text()" }, { "code": null, "e": 37937, "s": 37851, "text": "Prepends the string specified by text to the list of strings stored in the list store" }, { "code": null, "e": 37951, "s": 37937, "text": "remove_text()" }, { "code": null, "e": 38033, "s": 37951, "text": "Removes the string at the index specified by position in the associated liststore" }, { "code": null, "e": 38051, "s": 38033, "text": "get_active_text()" }, { "code": null, "e": 38087, "s": 38051, "text": "Returns the currently active string" }, { "code": null, "e": 38137, "s": 38087, "text": "The ComboBox widget emits the following signals −" }, { "code": null, "e": 38206, "s": 38137, "text": "Two example codes for the demonstration of ComboBox are given below." }, { "code": null, "e": 38465, "s": 38206, "text": "In this example, a ListStore is populated with the names of popular Python GUI toolkits and it is associated with a ComboBox widget. As a user makes a choice, the changed signal is emitted. It is connected to a callback function to display the user's choice." }, { "code": null, "e": 39724, "s": 38465, "text": "import pygtk\npygtk.require('2.0')\nimport gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"ComboBox with ListStore\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n combobox = gtk.ComboBox()\n store = gtk.ListStore(str)\n cell = gtk.CellRendererText()\n combobox.pack_start(cell)\n combobox.add_attribute(cell, 'text', 0)\n fixed = gtk.Fixed()\n lbl = gtk.Label(\"select a GUI toolkit\")\n fixed.put(lbl, 25,75)\n fixed.put(combobox, 125,75)\n lbl2 = gtk.Label(\"Your choice is:\")\n fixed.put(lbl2, 25,125)\n self.label = gtk.Label(\"\")\n fixed.put(self.label, 125,125)\n self.add(fixed)\n \n store.append ([\"PyQt\"])\n store.append ([\"Tkinter\"])\n store.append ([\"WxPython\"])\n store.append ([\"PyGTK\"])\n store.append ([\"PySide\"])\n combobox.set_model(store)\n combobox.connect('changed', self.on_changed)\n combobox.set_active(0)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n return\n \n def on_changed(self, widget):\n self.label.set_label(widget.get_active_text())\n return\n \nif __name__ == '__main__':\nPyApp()\ngtk.main()" }, { "code": null, "e": 39784, "s": 39724, "text": "Upon execution, the program displays the following output −" }, { "code": null, "e": 40057, "s": 39784, "text": "The second version of the program uses the convenience method combo_box_new_text() to create a combo box and append_text() function to add strings in it. In both programs, the get_active_text() method is used to fetch user's selection and display on a label on the window." }, { "code": null, "e": 41040, "s": 40057, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Simple ComboBox\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n cb = gtk.combo_box_new_text()\n cb.connect(\"changed\", self.on_changed)\n cb.append_text('PyQt')\n cb.append_text('Tkinter')\n cb.append_text('WxPython')\n cb.append_text('PyGTK')\n cb.append_text('PySide')\n \n fixed = gtk.Fixed()\n lbl = gtk.Label(\"select a GUI toolkit\")\n fixed.put(lbl, 25,75)\n \n fixed.put(cb, 125,75)\n lbl2 = gtk.Label(\"Your choice is:\")\n fixed.put(lbl2, 25,125)\n \n self.label = gtk.Label(\"\")\n fixed.put(self.label, 125,125)\n self.add(fixed)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \n def on_changed(self, widget):\n self.label.set_label(widget.get_active_text())\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 41111, "s": 41040, "text": "The output of this program is similar to that of the previous program." }, { "code": null, "e": 41462, "s": 41111, "text": "ToggleButton widget is a gtk.Button with two states — a pressed or active (or on) state and a normal or inactive (or off) state. Every time the button is pressed, the state alternates. The state of the ToggleButton can also be changed programmatically by set_active() method. To switch the state of the button, the toggled() method is also available." }, { "code": null, "e": 41521, "s": 41462, "text": "The gtk.ToggleButton class has the following constructor −" }, { "code": null, "e": 41575, "s": 41521, "text": "gtk.ToggleButton(label = None, use_underline = True)\n" }, { "code": null, "e": 41779, "s": 41575, "text": "Here, label is the test to be displayed on button. The use_underline property , if True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator." }, { "code": null, "e": 41874, "s": 41779, "text": "Some of the important methods of the gtk.ToggleButton class are given in the following table −" }, { "code": null, "e": 41927, "s": 41874, "text": "The ToggleButton widget emits the following signal −" }, { "code": null, "e": 41994, "s": 41927, "text": "The code given below demonstrates the use of ToggleButton widgets." }, { "code": null, "e": 42248, "s": 41994, "text": "Two ToggleButtons and Label widgets are placed in a VBox container. The toggled signal emitted by Button1 is connected to a callback function on_toggled(). In this function, the state of Button2 is set to True if that of Button1 is False and vice versa." }, { "code": null, "e": 42351, "s": 42248, "text": "if self.btn1.get_active() == True:\n self.btn2.set_active(False)\nelse:\n self.btn2.set_active(True)\n" }, { "code": null, "e": 42413, "s": 42351, "text": "It displays the instantaneous states of buttons on the Label." }, { "code": null, "e": 42442, "s": 42413, "text": "Observe the following code −" }, { "code": null, "e": 43407, "s": 42442, "text": "import gtk\n\n PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Toggle Button\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n vbox = gtk.VBox()\n self.btn1 = gtk.ToggleButton(\"Button 1\")\n self.btn1.connect(\"toggled\", self.on_toggled)\n self.btn2 = gtk.ToggleButton(\"Button 2\")\n self.lbl = gtk.Label()\n \n vbox.add(self.btn1)\n vbox.add(self.btn2)\n vbox.add(self.lbl)\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \n def on_toggled(self, widget, data = None):\n if self.btn1.get_active() == True:\n self.btn2.set_active(False)\n else:\n self.btn2.set_active(True)\n state = \"Button1 : \"+str(self.btn1.get_active())+\" \n Button2 : \"+str(self.btn2.get_active())\n self.lbl.set_text(state)\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 43455, "s": 43407, "text": "The above code generates the following output −" }, { "code": null, "e": 43758, "s": 43455, "text": "A CheckButton widget is nothing but a ToggleButton styled as a checkbox and a label. It inherits all properties and methods from the ToggleButton class. Unlike ToggleButton where the caption is on the button's face, a CheckButton displays a small square which is checkable and has a label to its right." }, { "code": null, "e": 43866, "s": 43758, "text": "Constructor, methods, and signals associated with gtk.CheckButton are exactly the same as gtk.ToggleButton." }, { "code": null, "e": 44163, "s": 43866, "text": "The following example demonstrates the use of CheckButton widget. Two CheckButtons and a Label are placed in a VBox. The toggled signal of the first CheckButton is connected to the on_checked() method which sets the state of the second button to True if that of the first is false and vice versa." }, { "code": null, "e": 44182, "s": 44163, "text": "Observe the code −" }, { "code": null, "e": 45061, "s": 44182, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Check Button\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n\n vbox = gtk.VBox()\n self.btn1 = gtk.CheckButton(\"Button 1\")\n self.btn1.connect(\"toggled\", self.on_checked)\n self.btn2 = gtk.CheckButton(\"Button 2\")\n self.btn2.connect(\"toggled\", self.on_checked)\n self.lbl = gtk.Label()\n\t\t\n vbox.add(self.btn1)\n vbox.add(self.btn2)\n vbox.add(self.lbl)\n\t\t\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def on_checked(self, widget, data = None):\n state = \"Button1 : \"+str(self.btn1.get_active())+\" \n Button2 : \"+str(self.btn2.get_active())\n self.lbl.set_text(state)\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 45113, "s": 45061, "text": "The above code will generate the following output −" }, { "code": null, "e": 45493, "s": 45113, "text": "A single RadioButton widget offers functionality similar to CheckButton. However, when more than one radio button is present in the same container, then a mutually exclusive choice is available for the user to choose from one of the available options. If every radio button in the container belongs to the same group, then as one is selected, others are automatically deselected." }, { "code": null, "e": 45555, "s": 45493, "text": "The following is a constructor of the gtk.RadioButton class −" }, { "code": null, "e": 45617, "s": 45555, "text": "gtk.RadioButton(group = None, Label = None, unerline = None)\n" }, { "code": null, "e": 45780, "s": 45617, "text": "In order to create a button group, provide group=None for the first Radio button, and for the subsequent options, provide the object of the first button as group." }, { "code": null, "e": 46060, "s": 45780, "text": "As in case of ToggleButton and CheckButton, the RadioButton also emits the toggled signal. In the example given below, three objects of the gtk.RadioButton widget are placed in a VBox. All of them are connected to a callback function on_selected(), to process the toggled signal." }, { "code": null, "e": 46178, "s": 46060, "text": "The callback function identifies the label of source RadioButton widget and displays it on the label put in the VBox." }, { "code": null, "e": 46207, "s": 46178, "text": "Observe the following code −" }, { "code": null, "e": 47109, "s": 46207, "text": "import gtk\n\nclass PyApp(gtk.Window):\n\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Radio Button\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n vbox = gtk.VBox()\n \n btn1 = gtk.RadioButton(None, \"Button 1\")\n btn1.connect(\"toggled\", self.on_selected)\n btn2 = gtk.RadioButton(btn1,\"Button 2\")\n btn2.connect(\"toggled\", self.on_selected)\n btn3 = gtk.RadioButton(btn1,\"Button 3\")\n btn3.connect(\"toggled\", self.on_selected)\n \n self.lbl = gtk.Label()\n vbox.add(btn1)\n vbox.add(btn2)\n vbox.add(btn3)\n vbox.add(self.lbl)\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \n def on_selected(self, widget, data=None):\n self.lbl.set_text(widget.get_label()+\" is selected\")\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 47161, "s": 47109, "text": "The above code will generate the following output −" }, { "code": null, "e": 47319, "s": 47161, "text": "A horizontal bar just below the title bar of a toplevel gtk.Window is reserved to display series of menus. It is an object of gtk.MenuBar class in PyGTK API." }, { "code": null, "e": 47554, "s": 47319, "text": "An object of the gtk.Menu class is added to the menu bar. It is also used to create context menu and popup menu. Each menu may contain one or more gtk.MenuItem widgets. Some of them can be a submenu.and have cascaded MenuItem buttons." }, { "code": null, "e": 47652, "s": 47554, "text": "The gtk.MenuBar is subclassed from the gtk.MenuShell class. It has a simple default constructor −" }, { "code": null, "e": 47667, "s": 47652, "text": "gtk.MenuBar()\n" }, { "code": null, "e": 47743, "s": 47667, "text": "To add a menu to MenuBar, the append() method of the MenuBar class is used." }, { "code": null, "e": 47873, "s": 47743, "text": "In order to construct a menu, create a MenuItem widget with a label which is desired to appear in menu bar and set it as submenu." }, { "code": null, "e": 47937, "s": 47873, "text": "For example, the following code is used to set up a File menu −" }, { "code": null, "e": 48010, "s": 47937, "text": "menu1 = gtk.Menu()\nfile = gtk.MenuItem(\"_File\")\nfile.set_submenu(menu1)\n" }, { "code": null, "e": 48083, "s": 48010, "text": "Now, one or more widgets of the MenuItem class can be added in the menu." }, { "code": null, "e": 48141, "s": 48083, "text": "item1 = gtk.MenuItem(\"New\")\nitem2 = gtk.MenuItem(\"Open\")\n" }, { "code": null, "e": 48240, "s": 48141, "text": "These MenuItems are added to the Menu widget and the menu object in turn is added to the menu bar." }, { "code": null, "e": 48298, "s": 48240, "text": "menu1.append(item1)\nmenu1.append(item2)\nmb.append(menu1)\n" }, { "code": null, "e": 48534, "s": 48298, "text": "The PyGTK toolkit offers many types of MenuItem widgets. An ImageMenuItem is a menu item with an image associated with it. You can use any of the stock images by using Stock ID parameter or assign any other image by set_image() method." }, { "code": null, "e": 48610, "s": 48534, "text": "For example, 'New' menu item having image is created in the following way −" }, { "code": null, "e": 48668, "s": 48610, "text": "new = gtk.ImageMenuItem(gtk.STOCK_NEW)\nmenu1.append(new)\n" }, { "code": null, "e": 48747, "s": 48668, "text": "Similarly, it is also possible to add CheckMenuItem using the following code −" }, { "code": null, "e": 48803, "s": 48747, "text": "chk = gtk.CheckMenuItem(\"Checkable\")\nmenu1.append(chk)\n" }, { "code": null, "e": 48862, "s": 48803, "text": "A group of radio items can also be added using this code −" }, { "code": null, "e": 48992, "s": 48862, "text": "radio1 = gtk.RadioMenuItem(None,\"Radio1\")\nradio2 = gtk.RadioMenuItem(radio1, \"Radio2\")\nmenu1.append(radio1)\nmenu1.append(radio2)\n" }, { "code": null, "e": 49119, "s": 48992, "text": "Sometimes, you may want to add a seperator line between menu items. For that purpose, the SeparatorMenuItem is also available." }, { "code": null, "e": 49168, "s": 49119, "text": "sep = gtk.SeparatorMenuItem()\nmenu1.append(sep)\n" }, { "code": null, "e": 49323, "s": 49168, "text": "You can also assign keyboard shortcuts to menu items. PyGTK has accelerators. Start by creating an accelerator group and attach it to the toplevel window." }, { "code": null, "e": 49381, "s": 49323, "text": "acgroup = gtk.AccelGroup()\nself.add_accel_group(acgroup)\n" }, { "code": null, "e": 49463, "s": 49381, "text": "To assign shortcut, use add_accelerator() function with the following prototype −" }, { "code": null, "e": 49523, "s": 49463, "text": "Item1.add_accelerator(signal, group, key, modifier, flags)\n" }, { "code": null, "e": 49576, "s": 49523, "text": "The following are some of the predefined modifiers −" }, { "code": null, "e": 49587, "s": 49576, "text": "SHIFT_MASK" }, { "code": null, "e": 49597, "s": 49587, "text": "LOCK_MASK" }, { "code": null, "e": 49610, "s": 49597, "text": "CONTROL_MASK" }, { "code": null, "e": 49623, "s": 49610, "text": "BUTTON1_MASK" }, { "code": null, "e": 49636, "s": 49623, "text": "BUTTON1_MASK" }, { "code": null, "e": 49716, "s": 49636, "text": "In order to assign Ctrl+N shortcut to New Menu item, use the following syntax −" }, { "code": null, "e": 49860, "s": 49716, "text": "new = gtk.ImageMenuItem(gtk.STOCK_NEW,acgroup)\nnew.add_accelerator(\"activate\", acgroup, ord('N'), \n gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)\n" }, { "code": null, "e": 49926, "s": 49860, "text": "The following example demonstrates the features discussed above −" }, { "code": null, "e": 51584, "s": 49926, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n \n super(PyApp, self).__init__()\n self.set_title(\"Menu Demo\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n mb = gtk.MenuBar()\n \n\t menu1 = gtk.Menu()\n file = gtk.MenuItem(\"_File\")\n file.set_submenu(menu1)\n acgroup = gtk.AccelGroup()\n self.add_accel_group(acgroup)\n new = gtk.ImageMenuItem(gtk.STOCK_NEW,acgroup)\n new.add_accelerator(\"activate\", acgroup, ord('N'), \n gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)\n \n menu1.append(new)\n open = gtk.ImageMenuItem(gtk.STOCK_OPEN)\n \n menu1.append(open)\n chk = gtk.CheckMenuItem(\"Checkable\")\n \n menu1.append(chk)\n radio1 = gtk.RadioMenuItem(None,\"Radio1\")\n radio2 = gtk.RadioMenuItem(radio1, \"Radio2\")\n \n menu1.append(radio1)\n menu1.append(radio2)\n sep = gtk.SeparatorMenuItem()\n \n menu1.append(sep)\n exit = gtk.ImageMenuItem(gtk.STOCK_QUIT)\n \n menu1.append(exit)\n menu2 = gtk.Menu()\n edit = gtk.MenuItem(\"_Edit\")\n edit.set_submenu(menu2)\n copy = gtk.ImageMenuItem(gtk.STOCK_COPY)\n \n menu2.append(copy)\n cut = gtk.ImageMenuItem(gtk.STOCK_CUT)\n \n menu2.append(cut)\n paste = gtk.ImageMenuItem(gtk.STOCK_PASTE)\n \n menu2.append(paste)\n mb.append(file)\n mb.append(edit)\n vbox = gtk.VBox(False, 2)\n vbox.pack_start(mb, False, False, 0)\n \n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 51635, "s": 51584, "text": "The above code will produce the following output −" }, { "code": null, "e": 52093, "s": 51635, "text": "Toolbar class is inherited from the gtk.Container class. It holds and manages a set of buttons and other widgets. One or more horizontal strips of buttons are normally seen just below the menu bar in a top level window. The Toolbar can also be put in a detachable window called HandleBox. By default, the buttons in the gtk.Toolbar widget are laid horizontally. Vertical toolbar can be set up by setting the orientation property to gtk.ORIENTATION_VERTICAL." }, { "code": null, "e": 52194, "s": 52093, "text": "The toolbar can be configured to show buttons with icons, text, or both. The style enumerators are −" }, { "code": null, "e": 52255, "s": 52194, "text": "A Toolbar widget is set up using the following constructor −" }, { "code": null, "e": 52276, "s": 52255, "text": "bar = gtk.Toolbar()\n" }, { "code": null, "e": 52578, "s": 52276, "text": "The constituents of Toolbar are instances of the gtk.ToolItem. The items can be ToolButton, RadioToolButton, ToggleToolButton, or SeparatorToolItem. In order to assign icon to the ToolItem object, images with predefined stock_ID can be used or a custom image can be assigned by the set_image() method." }, { "code": null, "e": 52645, "s": 52578, "text": "The following examples show how to construct different ToolItems −" }, { "code": null, "e": 52685, "s": 52645, "text": "newbtn = gtk.ToolButton(gtk.STOCK_NEW)\n" }, { "code": null, "e": 52797, "s": 52685, "text": "rb1 = gtk.RadioToolButton(None,gtk.STOCK_JUSTIFY_LEFT) \nrb2 = gtk.RadioToolButton(rb1,gtk.STOCK_JUSTIFY_RIGHT)\n" }, { "code": null, "e": 52857, "s": 52797, "text": "Note that multiple radio buttons are put in the same group." }, { "code": null, "e": 52888, "s": 52857, "text": "sep = gtk.SeparatorToolItem()\n" }, { "code": null, "e": 52953, "s": 52888, "text": "These items are put in the toolbar by calling its insert method." }, { "code": null, "e": 52986, "s": 52953, "text": "gtk.Toolbar.insert(item, index)\n" }, { "code": null, "e": 52999, "s": 52986, "text": "For example," }, { "code": null, "e": 53018, "s": 52999, "text": "bar.insert(new,0)\n" }, { "code": null, "e": 53163, "s": 53018, "text": "You can also assign a tooltip to the ToolButton using the set_tooltip_text() nethod. For example, New tooltip is assigned to the new ToolButton." }, { "code": null, "e": 53195, "s": 53163, "text": "newbtn.set_tooltip_text(\"New\")\n" }, { "code": null, "e": 53324, "s": 53195, "text": "The following code shows a toplevel window with a tool bar set up to contain normal tool item, radio items and a separator item." }, { "code": null, "e": 54868, "s": 53324, "text": "import gtk\n\nclass PyApp(gtk.Window):\n\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Toolbar Demo\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n toolbar = gtk.Toolbar()\n toolbar.set_style(gtk.TOOLBAR_ICONS)\n toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)\n \n newbtn = gtk.ToolButton(gtk.STOCK_NEW)\n newbtn.set_tooltip_text(\"New\")\n openbtn = gtk.ToolButton(gtk.STOCK_OPEN)\n savebtn = gtk.ToolButton(gtk.STOCK_SAVE)\n sep = gtk.SeparatorToolItem()\n \n rb1 = gtk.RadioToolButton(None,gtk.STOCK_JUSTIFY_LEFT)\n 53\n rb2 = gtk.RadioToolButton(rb1,gtk.STOCK_JUSTIFY_RIGHT)\n \n prv = gtk.ToggleToolButton(gtk.STOCK_PRINT_PREVIEW)\n quitbtn = gtk.ToolButton(gtk.STOCK_QUIT)\n \n toolbar.insert(newbtn, 0)\n toolbar.insert(openbtn, 1)\n toolbar.insert(savebtn, 2)\n toolbar.insert(sep, 3)\n toolbar.insert(rb1,4)\n toolbar.insert(rb2,5)\n toolbar.insert(prv,6)\n toolbar.insert(quitbtn, 7)\n \n quitbtn.connect(\"clicked\", gtk.main_quit)\n vbox = gtk.VBox(False, 2)\n vbox.pack_start(toolbar, False, False, 0)\n \n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \n def on_checked(self, widget, data = None):\n state = \"Button1 : \"+str(self.btn1.get_active())+\" \n Button2 : \"+str(self.btn2.get_active())\n self.lbl.set_text(state)\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 54920, "s": 54868, "text": "The above code will generate the following output −" }, { "code": null, "e": 55198, "s": 54920, "text": "Some widgets in PyGTK toolkit are such that their properties can be adjusted over a specified range by the user by using a mouse or a keyboard. A widget like Viewport is used to display some adjustable portion of a large data, for example, a multiline text in TextView control." }, { "code": null, "e": 55553, "s": 55198, "text": "PyGTK uses gtk.Adjustment object to be used in association with such widgets so that user adjustments are passed to some callback function for processing. An Adjustment object contains lower and upper bounds of an adjustable value and its increment step paramaters. When parameters of adjustment object changes, it emits changed or value_changed signals." }, { "code": null, "e": 55616, "s": 55553, "text": "The following is the constructor of the gtk.Adjustment class −" }, { "code": null, "e": 55714, "s": 55616, "text": "gtk.Adjustment(value = 0, lower = 0, upper = 0, step_incr = 0, \n page_incr = 0, page_size = 0)\n" }, { "code": null, "e": 55787, "s": 55714, "text": "The meaning of each of the attributes in the constructor is as follows −" }, { "code": null, "e": 55848, "s": 55787, "text": "The following signals are emitted by the Adjustment object −" }, { "code": null, "e": 56070, "s": 55848, "text": "As mentioned above, the Adjustment object is not a physical widget. Rather, it is used in association with the other widgets using which its attributes get changed. Range widgets are used along with the Adjustment object." }, { "code": null, "e": 56423, "s": 56070, "text": "This class acts as a base class for widgets which let the user to adjust the value of a numeric parameter between the lower and upper bounds. Scale widgets (gtk.Hscale and gtk.Vscale) and scrollbar widgets (gtk.HScrollbar and gtk.VScrollbar) derive functionality from the Range class. These Range widgets work in conjunction with the Adjustment object." }, { "code": null, "e": 56533, "s": 56423, "text": "The following important functions of the gtk.Range class are implemented by the Scale and Scrollbar widgets −" }, { "code": null, "e": 56646, "s": 56533, "text": "set_update_policy() − This sets the \"update-policy\" property to the value. The policy has the following values −" }, { "code": null, "e": 56759, "s": 56646, "text": "set_update_policy() − This sets the \"update-policy\" property to the value. The policy has the following values −" }, { "code": null, "e": 56876, "s": 56759, "text": "set_adjustment() − This sets the \"adjustment\" property. The Adjustment object is used as model for the Range object." }, { "code": null, "e": 56993, "s": 56876, "text": "set_adjustment() − This sets the \"adjustment\" property. The Adjustment object is used as model for the Range object." }, { "code": null, "e": 57061, "s": 56993, "text": "set_increments() − This sets the step and page sizes for the range." }, { "code": null, "e": 57129, "s": 57061, "text": "set_increments() − This sets the step and page sizes for the range." }, { "code": null, "e": 57215, "s": 57129, "text": "set_range() − This sets the minimum and maximum allowable values for the Range widget" }, { "code": null, "e": 57301, "s": 57215, "text": "set_range() − This sets the minimum and maximum allowable values for the Range widget" }, { "code": null, "e": 57380, "s": 57301, "text": "set_value() − This sets the current value of the range to the value specified." }, { "code": null, "e": 57459, "s": 57380, "text": "set_value() − This sets the current value of the range to the value specified." }, { "code": null, "e": 57544, "s": 57459, "text": "The scale widget classes − (HScale and VScale) are derived from the gtk.Range class." }, { "code": null, "e": 57684, "s": 57544, "text": "This class acts as an abstract base class for HScale and VScale widgets. These widgets work as a slider control and select a numeric value." }, { "code": null, "e": 57788, "s": 57684, "text": "The following methods of this abstract class are implemented by the HScale class and the VScale class −" }, { "code": null, "e": 57891, "s": 57788, "text": "set_digits() − This sets number of decimal places to be used to display instantaneous value of widget." }, { "code": null, "e": 57994, "s": 57891, "text": "set_digits() − This sets number of decimal places to be used to display instantaneous value of widget." }, { "code": null, "e": 58078, "s": 57994, "text": "set_draw_value() − set to True, current value will be displayed next to the slider." }, { "code": null, "e": 58162, "s": 58078, "text": "set_draw_value() − set to True, current value will be displayed next to the slider." }, { "code": null, "e": 58311, "s": 58162, "text": "set_value_pos() − This is the position at which the values are drawn. This can be either gtk.POS_LEFT, gtk.POS_RIGHT, gtk.POS_TOP or gtk.POS_BOTTOM." }, { "code": null, "e": 58460, "s": 58311, "text": "set_value_pos() − This is the position at which the values are drawn. This can be either gtk.POS_LEFT, gtk.POS_RIGHT, gtk.POS_TOP or gtk.POS_BOTTOM." }, { "code": null, "e": 58627, "s": 58460, "text": "An object of gtk.HScale class provides a horizontal slider, whereas an object of gtk.VScale class provides vertical slider. Both classes have identical constructors −" }, { "code": null, "e": 58688, "s": 58627, "text": "gtk.HScale(Adjustment = None)\ngtk.VScale(Adjustment = None)\n" }, { "code": null, "e": 58776, "s": 58688, "text": "The adjustment object contains many attributes that provide access to value and bounds." }, { "code": null, "e": 59045, "s": 58776, "text": "This class is an abstract base class for gtk.Hscrollbar and gtk.Vscrollbar widgets. Both are associated with an Adjustment object. The position of the thumb of the scrollbar is controlled by scroll adjustments. The attributes of adjustment object are used as follows −" }, { "code": null, "e": 59209, "s": 59045, "text": "The following program shows an HScale and an HScrollbar widget placed in a VBox added to the toplevel window. Each of them is associated with an adjustment object." }, { "code": null, "e": 59297, "s": 59209, "text": "adj1 = gtk.Adjustment(0, 0, 101, 0.1, 1, 1)\nself.adj2 = gtk.Adjustment(10,0,101,5,1,1)\n" }, { "code": null, "e": 59438, "s": 59297, "text": "An gtk.HScale widget is a slider control attached with adj1. Its update policy, number and position of drawing value are set up as follows −" }, { "code": null, "e": 59596, "s": 59438, "text": "scale1 = gtk.HScale(adj1)\nscale1.set_update_policy(gtk.UPDATE_CONTINUOUS)\nscale1.set_digits(1)\nscale1.set_value_pos(gtk.POS_TOP)\nscale1.set_draw_value(True)\n" }, { "code": null, "e": 59723, "s": 59596, "text": "gtk.HScrollbar provides a horizontal scrollbar. It is associated with adj2 object. Its update policy too is set to CONTINUOUS." }, { "code": null, "e": 59813, "s": 59723, "text": "self.bar1 = gtk.HScrollbar(self.adj2)\nself.bar1.set_update_policy(gtk.UPDATE_CONTINUOUS)\n" }, { "code": null, "e": 60086, "s": 59813, "text": "In order to display instantaneous value of the scrollbar, 'value-changed' signal of the adjustment object — adj2 is connected to callback function on_scrolled(). The function retrieves the value property of adjustment object and displays it on a label below the scrollbar." }, { "code": null, "e": 60257, "s": 60086, "text": "self.adj2.connect(\"value_changed\", self.on_scrolled)\n def on_scrolled(self, widget, data = None):\n self.lbl2.set_text(\"HScrollbar value: \"+str(int(self.adj2.value)))\n" }, { "code": null, "e": 60286, "s": 60257, "text": "Observe the following code −" }, { "code": null, "e": 61455, "s": 60286, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Range widgets Demo\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n adj1 = gtk.Adjustment(0.0, 0.0, 101.0, 0.1, 1.0, 1.0)\n self.adj2 = gtk.Adjustment(10,0,101,5,1,1)\n \n scale1 = gtk.HScale(adj1)\n scale1.set_update_policy(gtk.UPDATE_CONTINUOUS)\n scale1.set_digits(1)\n scale1.set_value_pos(gtk.POS_TOP)\n scale1.set_draw_value(True)\n \n vb = gtk.VBox()\n vb.add(scale1)\n lbl1 = gtk.Label(\"HScale\")\n \n vb.add(lbl1)\n self.bar1 = gtk.HScrollbar(self.adj2)\n self.bar1.set_update_policy(gtk.UPDATE_CONTINUOUS)\n vb.add(self.bar1)\n self.lbl2 = gtk.Label(\"HScrollbar value: \")\n \n vb.add(self.lbl2)\n self.adj2.connect(\"value_changed\", self.on_scrolled)\n self.add(vb)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \n def on_scrolled(self, widget, data=None):\n self.lbl2.set_text(\"HScrollbar value: \"+str(int(self.adj2.value)))\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 61507, "s": 61455, "text": "The above code will generate the following output −" }, { "code": null, "e": 61783, "s": 61507, "text": "A Dialog widget is normally used as a pop-up window on top of a parent window. The objective of a Dialog is to collect some data from the user and send it to the parent window. Dialog can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed)." }, { "code": null, "e": 62057, "s": 61783, "text": "The Dialog widget of PyGTK library is a window split vertically. In its top section, there is a gtk.VBox in which Label or Entry Widgets are packed. The bottom section is called action_area in which one or more buttons are placed. Two areas are separated by gtk.HSeparator." }, { "code": null, "e": 62106, "s": 62057, "text": "gtk.Dialog class has the following constructor −" }, { "code": null, "e": 62181, "s": 62106, "text": "dlg = gtk.Dialog (Title = None, parent = None, flags = 0, buttons = None)\n" }, { "code": null, "e": 62188, "s": 62181, "text": "Where," }, { "code": null, "e": 62257, "s": 62188, "text": "Title − Is the text appearing in the Title bar of the Dialog widget." }, { "code": null, "e": 62326, "s": 62257, "text": "Title − Is the text appearing in the Title bar of the Dialog widget." }, { "code": null, "e": 62406, "s": 62326, "text": "Parent − Is the reference to the toplevel window from which the dialog pops up." }, { "code": null, "e": 62486, "s": 62406, "text": "Parent − Is the reference to the toplevel window from which the dialog pops up." }, { "code": null, "e": 62572, "s": 62486, "text": "Flag − Defines constants controlling operation of Dialog. The defined constants are −" }, { "code": null, "e": 62658, "s": 62572, "text": "Flag − Defines constants controlling operation of Dialog. The defined constants are −" }, { "code": null, "e": 62764, "s": 62658, "text": "A Button is a tuple object containing pairs of gtk.Button with a stock ID (or text) and its response IDs." }, { "code": null, "e": 62847, "s": 62764, "text": "The response ID can be any number or one of the predefined Response ID constants −" }, { "code": null, "e": 62865, "s": 62847, "text": "gtk.RESPONSE_NONE" }, { "code": null, "e": 62885, "s": 62865, "text": "gtk.RESPONSE_REJECT" }, { "code": null, "e": 62905, "s": 62885, "text": "gtk.RESPONSE_ACCEPT" }, { "code": null, "e": 62931, "s": 62905, "text": "gtk.RESPONSE_DELETE_EVENT" }, { "code": null, "e": 62947, "s": 62931, "text": "gtk.RESPONSE_OK" }, { "code": null, "e": 62967, "s": 62947, "text": "gtk.RESPONSE_CANCEL" }, { "code": null, "e": 62986, "s": 62967, "text": "gtk.RESPONSE_CLOSE" }, { "code": null, "e": 63003, "s": 62986, "text": "gtk.RESPONSE_YES" }, { "code": null, "e": 63019, "s": 63003, "text": "gtk.RESPONSE_NO" }, { "code": null, "e": 63038, "s": 63019, "text": "gtk.RESPONSE_APPLY" }, { "code": null, "e": 63056, "s": 63038, "text": "gtk.RESPONSE_HELP" }, { "code": null, "e": 63120, "s": 63056, "text": "The important methods of the gtk.Dialog class are given below −" }, { "code": null, "e": 63254, "s": 63120, "text": "add_button() − Adds a button with the text specified by button_text (or a stock button, if button_text is a stock ID) in action_area." }, { "code": null, "e": 63388, "s": 63254, "text": "add_button() − Adds a button with the text specified by button_text (or a stock button, if button_text is a stock ID) in action_area." }, { "code": null, "e": 63469, "s": 63388, "text": "response() − Emits the \"response\" signal with the value specified in response_id" }, { "code": null, "e": 63550, "s": 63469, "text": "response() − Emits the \"response\" signal with the value specified in response_id" }, { "code": null, "e": 63638, "s": 63550, "text": "run() − Displays the dialog and returns the response_id when delete_event gets emitted." }, { "code": null, "e": 63726, "s": 63638, "text": "run() − Displays the dialog and returns the response_id when delete_event gets emitted." }, { "code": null, "e": 63869, "s": 63726, "text": "set_default_response() − Sets the last widget in the dialog's action area with the specified response_id as the default widget for the dialog." }, { "code": null, "e": 64012, "s": 63869, "text": "set_default_response() − Sets the last widget in the dialog's action area with the specified response_id as the default widget for the dialog." }, { "code": null, "e": 64060, "s": 64012, "text": "gtk.Dialog widget emits the following signals −" }, { "code": null, "e": 64398, "s": 64060, "text": "Two buttons in action_area of Dialog widget use Stock IDs gtk.STOCK.CANCEL and gtk.STOCK_OK. They are associated with response IDs gtk. RESPONSE_REJECT and gtk. RESPONSE_ACCEPT respectively. The Dialog is closed when any button is pressed. The run() methods returns corresponding response ID which may be utilized for further processing." }, { "code": null, "e": 64537, "s": 64398, "text": "Following code displays a top level gtk.Window with a Button in it. When button is clicked, a Dialog appears with a label and two buttons." }, { "code": null, "e": 64566, "s": 64537, "text": "Observe the following code −" }, { "code": null, "e": 65422, "s": 64566, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Dialog Demo\")\n self.set_default_size(250, 200)\n fixed = gtk.Fixed()\n btn = gtk.Button(\"Show\")\n btn.connect(\"clicked\",self.show_sialog)\n fixed.put(btn,100,100)\n self.add(fixed)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \n def show_sialog(self, widget, data=None):\n dialog = gtk.Dialog(\"My dialog\",\n self,\n gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,\n gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))\n label = gtk.Label(\"Simple dialog\")\n dialog.vbox.add(label)\n label.show()\n res = dialog.run()\n print res\n dialog.destroy()\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 65469, "s": 65422, "text": "The above code produces the following output −" }, { "code": null, "e": 65526, "s": 65469, "text": "PyGTK API has a number of preconfigured Dialog widgets −" }, { "code": null, "e": 65540, "s": 65526, "text": "MessageDialog" }, { "code": null, "e": 65552, "s": 65540, "text": "AboutDialog" }, { "code": null, "e": 65573, "s": 65552, "text": "ColorSelectionDialog" }, { "code": null, "e": 65593, "s": 65573, "text": "FontSelectionDialog" }, { "code": null, "e": 65611, "s": 65593, "text": "FileChooserDialog" }, { "code": null, "e": 65967, "s": 65611, "text": "In order to demonstrate the functioning of the above standard dialog in PyGTK, a menu with a menu item each invoking a dialog when clicked, is put in a gtk.Window in the following program. The Callback functions responding to activate the signal of each menu item is listed. You can also understand the explanation provided for each type of dialog widget." }, { "code": null, "e": 65996, "s": 65967, "text": "Observe the following code −" }, { "code": null, "e": 67582, "s": 65996, "text": "import gtk, pango\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Dialog Boxes\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n mb = gtk.MenuBar()\n menu1 = gtk.Menu()\n file = gtk.MenuItem(\"_File\")\n file.set_submenu(menu1)\n msg = gtk.MenuItem(\"MessageDialog\")\n \n menu1.append(msg)\n abt = gtk.MenuItem(\"AboutDialog\")\n menu1.append(abt)\n colo = gtk.MenuItem(\"colorDialog\")\n menu1.append(colo)\n font = gtk.MenuItem(\"FontSelectionDialog\")\n menu1.append(font)\n fl = gtk.MenuItem(\"FileChooserDialog\")\n menu1.append(fl)\n mb.append(file)\n \n vbox = gtk.VBox(False, 2)\n vbox.pack_start(mb, False, False, 0)\n self.add(vbox)\n self.text = gtk.Label(\"TutorialsPoint\")\n vbox.pack_start(self.text, True, True, 0)\n msg.connect(\"activate\",self.on_msgdlg)\n abt.connect(\"activate\",self.on_abtdlg)\n font.connect(\"activate\",self.on_fntdlg)\n colo.connect(\"activate\",self.on_color)\n \n fl.connect(\"activate\", self.on_file)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n def on_msgdlg(self, widget):\n #MessageDialog usage code\n def on_abtdlg(self, widget):\n #AboutDialog usage code\n def on_fntdlg(self,widget):\n #FontSelectionDialog usage code\n def on_color(self, widget):\n #ColorChooserDialog usage cde\n Def on_file(self, widget):\n #FileChooserDialog usage code\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 67634, "s": 67582, "text": "The above code will generate the following output −" }, { "code": null, "e": 67864, "s": 67634, "text": "A Messagedialog widget is a Dialog window configured to display an image representing the type of message, i.e., error, question, or some informational text. A MessageDialog object is declared by using the following constructor −" }, { "code": null, "e": 67989, "s": 67864, "text": "gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_INFO, \n buttons = gtk.BUTTONS_NONE, message_format = None)\n" }, { "code": null, "e": 68067, "s": 67989, "text": "The following predefined message types are used to configure message dialog −" }, { "code": null, "e": 68127, "s": 68067, "text": "A set of predefined button sets are also available for use." }, { "code": null, "e": 68253, "s": 68127, "text": "When the MessageBox menu item is activated, the following callback function is called and a message box pops up as an output." }, { "code": null, "e": 68426, "s": 68253, "text": "def on_msgdlg(self, widget):\n md = gtk.MessageDialog(self,\n gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR,\n gtk.BUTTONS_CLOSE, \"Error message\")\n md.run()\n" }, { "code": null, "e": 68482, "s": 68426, "text": "The above function will generate the following output −" }, { "code": null, "e": 68761, "s": 68482, "text": "A simple way to display information about a program like its logo, name, copyright, website and license is offered by the gtk.AboutDialog widget. An about dialog is typically opened when the user selects the About option from the Help menu. All parts of the dialog are optional." }, { "code": null, "e": 68891, "s": 68761, "text": "The About Dialog can contain URLs and email addresses. gtk.AboutDialog offers global hooks when the user clicks URLs and email ID" }, { "code": null, "e": 68953, "s": 68891, "text": "The following is a constructor of the gtk.AboutDialog class −" }, { "code": null, "e": 68978, "s": 68953, "text": "dlg = gtk.AboutDialog()\n" }, { "code": null, "e": 69039, "s": 68978, "text": "The following methods are used to configure the About Dialog" }, { "code": null, "e": 69148, "s": 69039, "text": "set_program_name() − This sets the name to be displayed in the About Dialog. defaults to application_name()." }, { "code": null, "e": 69257, "s": 69148, "text": "set_program_name() − This sets the name to be displayed in the About Dialog. defaults to application_name()." }, { "code": null, "e": 69306, "s": 69257, "text": "set_version() − This sets the \"version\" property" }, { "code": null, "e": 69355, "s": 69306, "text": "set_version() − This sets the \"version\" property" }, { "code": null, "e": 69441, "s": 69355, "text": "set_copyright() − This sets the \"copyright\". If None, the copyright notice is hidden." }, { "code": null, "e": 69527, "s": 69441, "text": "set_copyright() − This sets the \"copyright\". If None, the copyright notice is hidden." }, { "code": null, "e": 69607, "s": 69527, "text": "set_license() − This sets the \"license\". If None, the license button is hidden." }, { "code": null, "e": 69687, "s": 69607, "text": "set_license() − This sets the \"license\". If None, the license button is hidden." }, { "code": null, "e": 69780, "s": 69687, "text": "set_website() − This sets the \"website\" property to the string whichg should be a valid URL." }, { "code": null, "e": 69873, "s": 69780, "text": "set_website() − This sets the \"website\" property to the string whichg should be a valid URL." }, { "code": null, "e": 70011, "s": 69873, "text": "set_author() − This sets the \"authors\" property to the list of author names displayed in the authors tab of the secondary credits dialog." }, { "code": null, "e": 70149, "s": 70011, "text": "set_author() − This sets the \"authors\" property to the list of author names displayed in the authors tab of the secondary credits dialog." }, { "code": null, "e": 70265, "s": 70149, "text": "set_logo() − This sets the \"logo\" property to the Pixbuf object. If None, the default window icon set will be used." }, { "code": null, "e": 70381, "s": 70265, "text": "set_logo() − This sets the \"logo\" property to the Pixbuf object. If None, the default window icon set will be used." }, { "code": null, "e": 70512, "s": 70381, "text": "When the AboutDialog menu button is clicked, the following callback function is called. This function generates the About Dialog −" }, { "code": null, "e": 70863, "s": 70512, "text": "def on_abtdlg(self, widget):\n \n about = gtk.AboutDialog()\n about.set_program_name(\"PyGTK Dialog\")\n about.set_version(\"0.1\")\n about.set_authors(\"M.V.Lathkar\")\n about.set_copyright(\"(c) TutorialsPoint\")\n about.set_comments(\"About Dialog example\")\n about.set_website(\"http://www.tutorialspoint.com\")\n \n about.run()\n about.destroy()" }, { "code": null, "e": 70915, "s": 70863, "text": "The above function generates the following output −" }, { "code": null, "e": 71159, "s": 70915, "text": "The gtk.FontSelection widget allows users to select and apply the font of a particular name, size and style. The dialog has a preview box containing some text which will be displayed in selected font description, and two buttons CANCEL and OK." }, { "code": null, "e": 71484, "s": 71159, "text": "PyGTK API contains a Pango module which defines classes and functionality required to render high quality internationalized text. Font and text handling in gtk is supported by Pango. The pango.Font object represents a font in a system independent way. The pango.FontDescription object contains the characteristics of a font." }, { "code": null, "e": 71652, "s": 71484, "text": "gtk.FontSelectionDialog returns a pango.Font object. In order to apply the selected font, fontmetrics is fetched by obtaining the pango.FontDescription object from it." }, { "code": null, "e": 71718, "s": 71652, "text": "The following is a constructor of the FontSelectionDialog class −" }, { "code": null, "e": 71756, "s": 71718, "text": "dlg = gtk.FontSelectionDialog(title)\n" }, { "code": null, "e": 71819, "s": 71756, "text": "The following are some frequently used methods of this class −" }, { "code": null, "e": 71940, "s": 71819, "text": "get_font_name() − This returns a string containing the currently selected font name or None if no font name is selected." }, { "code": null, "e": 72061, "s": 71940, "text": "get_font_name() − This returns a string containing the currently selected font name or None if no font name is selected." }, { "code": null, "e": 72106, "s": 72061, "text": "set_font_name() − This sets the current font" }, { "code": null, "e": 72151, "s": 72106, "text": "set_font_name() − This sets the current font" }, { "code": null, "e": 72217, "s": 72151, "text": "set_preview_text() − This sets the text in the preview area entry" }, { "code": null, "e": 72283, "s": 72217, "text": "set_preview_text() − This sets the text in the preview area entry" }, { "code": null, "e": 72368, "s": 72283, "text": "The selected font is applied to the text in a widget using the modify_font() method." }, { "code": null, "e": 72462, "s": 72368, "text": "When FontSelectionDialog menu item is activated, the following callback function is invoked −" }, { "code": null, "e": 72805, "s": 72462, "text": "def on_abtdlg(self, widget):\n about = gtk.AboutDialog()\n about.set_program_name(\"PyGTK Dialog\")\n about.set_version(\"0.1\")\n about.set_authors(\"M.V.Lathkar\")\n about.set_copyright(\"(c) TutorialsPoint\")\n about.set_comments(\"About Dialog example\")\n about.set_website(\"http://www.tutorialspoint.com\")\n about.run()\n about.destroy()" }, { "code": null, "e": 72886, "s": 72805, "text": "The selected font is applied to the text of label placed on the toplevel window." }, { "code": null, "e": 72916, "s": 72886, "text": "The following is the output −" }, { "code": null, "e": 73057, "s": 72916, "text": "This is a preconfigured Dialog in PyGTK API which lets the user to select and apply color. It internally embeds a gtk.ColorSelection widget." }, { "code": null, "e": 73310, "s": 73057, "text": "The gtk.ColorScelection widget presents a colow wheel, and entry boxes for color parameters such as HSV and RGB. New color can be selected by manipulating color wheel or entering color parameters. Its get_current_color is useful for further processing." }, { "code": null, "e": 73396, "s": 73310, "text": "Following is the prototype of the constructor of the gtk.ColorSelectionDialog class −" }, { "code": null, "e": 73435, "s": 73396, "text": "dlg = gtk.ColorSelectionDialog(title)\n" }, { "code": null, "e": 73587, "s": 73435, "text": "The current selected color is obtained from the colorsel attribute. The selected color is applied to a widget using modify_fg() or modify_bg() methods." }, { "code": null, "e": 73680, "s": 73587, "text": "When the ColorDialog menu button is activated, the following callback function is executed −" }, { "code": null, "e": 73865, "s": 73680, "text": "def on_color(self, widget):\n dlg = gtk.ColorSelectionDialog(\"Select color\")\n col = dlg.run()\n sel = dlg.colorsel.get_current_color()\n self.text.modify_fg(gtk.STATE_NORMAL, sel)" }, { "code": null, "e": 73939, "s": 73865, "text": "The chosen color is applied to the text in a label widget on the window −" }, { "code": null, "e": 73969, "s": 73939, "text": "The following is the output −" }, { "code": null, "e": 74165, "s": 73969, "text": "This dialog is useful to let the user select the location and the name of file that needs to be opened or saved. It embeds FileChooserWidget and provides OK and CANCEL buttons in the action_area." }, { "code": null, "e": 74233, "s": 74165, "text": "The following is a constructor of the gtk.FileChooserDialog class −" }, { "code": null, "e": 74366, "s": 74233, "text": "Dlg=gtk.FileChooserDialog (title = None, parent = None, \n action = gtk.FILE_CHOOSER_ACTION_OPEN, buttons = None, backend = None)\n" }, { "code": null, "e": 74387, "s": 74366, "text": "The parameters are −" }, { "code": null, "e": 74424, "s": 74387, "text": "The following are the action modes −" }, { "code": null, "e": 74453, "s": 74424, "text": "gtk.FILE_CHOOSER_ACTION_OPEN" }, { "code": null, "e": 74482, "s": 74453, "text": "gtk.FILE_CHOOSER_ACTION_SAVE" }, { "code": null, "e": 74520, "s": 74482, "text": "gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER" }, { "code": null, "e": 74558, "s": 74520, "text": "gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER" }, { "code": null, "e": 74716, "s": 74558, "text": "If it is desired to restrict the types of files to be available for display, an object of the gtk.FileFilter can be applied by using the add_filter() method." }, { "code": null, "e": 74805, "s": 74716, "text": "If the FileChooserDialog menu button is clicked, the following callback function is run." }, { "code": null, "e": 75072, "s": 74805, "text": "def on_file(self, widget):\n dlg = gtk.FileChooserDialog(\"Open..\", None, gtk.FILE_CHOOSER_ACTION_OPEN,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))\n response = dlg.run()\n self.text.set_text(dlg.get_filename())\n dlg.destroy()" }, { "code": null, "e": 75111, "s": 75072, "text": "The file is selected from the dialog −" }, { "code": null, "e": 75184, "s": 75111, "text": "The selected file is displayed on the label on the toplevel gtk.Window −" }, { "code": null, "e": 75572, "s": 75184, "text": "Notebook widget is a tabbed container. Each tab in this container holds a different page and the pages are seen in overlapped manner. Any desired page is made visible by clicking on the label of the tab. The labels can be configured to be displayed on top or bottom or to the left or right. A container widget with other widgets placed in it or a single widget is placed under each page." }, { "code": null, "e": 75849, "s": 75572, "text": "If data to be displayed is too big in one view, it is grouped in different pages, each placed under one tab of a Notebook widget. This type of control is very widely used. Internet browser for instance, uses this tabbed display for rendering different pages in different tabs." }, { "code": null, "e": 75908, "s": 75849, "text": "The following is a constructor of the gtk.Notebook class −" }, { "code": null, "e": 75924, "s": 75908, "text": "gtk.Notebook()\n" }, { "code": null, "e": 75998, "s": 75924, "text": "The following are the frequently used methods of the gtk.Notebook class −" }, { "code": null, "e": 76179, "s": 75998, "text": "append_page(child, label) − This appends a page to the notebook containing a widget specified by tab_label as the label on the tab. If tab_label can be None to use a default label." }, { "code": null, "e": 76360, "s": 76179, "text": "append_page(child, label) − This appends a page to the notebook containing a widget specified by tab_label as the label on the tab. If tab_label can be None to use a default label." }, { "code": null, "e": 76475, "s": 76360, "text": "insert_page(child, label, position) − This inserts a page into the notebook at the location specified by position." }, { "code": null, "e": 76590, "s": 76475, "text": "insert_page(child, label, position) − This inserts a page into the notebook at the location specified by position." }, { "code": null, "e": 76655, "s": 76590, "text": "remove_page(index) − This removes a page at the specified index." }, { "code": null, "e": 76720, "s": 76655, "text": "remove_page(index) − This removes a page at the specified index." }, { "code": null, "e": 76790, "s": 76720, "text": "get_current_page() − This returns the page index of the current page." }, { "code": null, "e": 76860, "s": 76790, "text": "get_current_page() − This returns the page index of the current page." }, { "code": null, "e": 76943, "s": 76860, "text": "set_current_page(index) − This switches to the page number specified by the index." }, { "code": null, "e": 77026, "s": 76943, "text": "set_current_page(index) − This switches to the page number specified by the index." }, { "code": null, "e": 77105, "s": 77026, "text": "set_show_tabs() − If false, tabs will not be visible. This is True by default." }, { "code": null, "e": 77184, "s": 77105, "text": "set_show_tabs() − If false, tabs will not be visible. This is True by default." }, { "code": null, "e": 77374, "s": 77184, "text": "set_tab_pos(pos) − This sets the edge at which the tabs for switching pages in the notebook are drawn. The predefined constants are −\n\ngtk.POS_LEFT\ngtk.POS_RIGHT\ngtk.POS_TOP\ngtk.POS_BOTTOM\n" }, { "code": null, "e": 77508, "s": 77374, "text": "set_tab_pos(pos) − This sets the edge at which the tabs for switching pages in the notebook are drawn. The predefined constants are −" }, { "code": null, "e": 77521, "s": 77508, "text": "gtk.POS_LEFT" }, { "code": null, "e": 77534, "s": 77521, "text": "gtk.POS_LEFT" }, { "code": null, "e": 77548, "s": 77534, "text": "gtk.POS_RIGHT" }, { "code": null, "e": 77562, "s": 77548, "text": "gtk.POS_RIGHT" }, { "code": null, "e": 77574, "s": 77562, "text": "gtk.POS_TOP" }, { "code": null, "e": 77586, "s": 77574, "text": "gtk.POS_TOP" }, { "code": null, "e": 77601, "s": 77586, "text": "gtk.POS_BOTTOM" }, { "code": null, "e": 77616, "s": 77601, "text": "gtk.POS_BOTTOM" }, { "code": null, "e": 77759, "s": 77616, "text": "set_tab_label_text(child, text) − This creates a new label with the text specified and sets it as the tab label for the page containing child." }, { "code": null, "e": 77902, "s": 77759, "text": "set_tab_label_text(child, text) − This creates a new label with the text specified and sets it as the tab label for the page containing child." }, { "code": null, "e": 77956, "s": 77902, "text": "The gtk.Notebook widget emits the following signals −" }, { "code": null, "e": 78322, "s": 77956, "text": "In the following example, a gtk.Notebook with three pages is placed in a toplevel gtk.Window. The first page holds a VBox in which a label and Entry field is packed. The second page labelled 'qualifications' has a HButtonBox in which three mutually exclusive RadioButton widgets are added. The third page has a TextView object. The page labels are displayed at top." }, { "code": null, "e": 78341, "s": 78322, "text": "Observe the code −" }, { "code": null, "e": 79529, "s": 78341, "text": "import gtk\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Notebook Demo\")\n self.set_default_size(250, 200)\n\t\t\n nb = gtk.Notebook()\n nb.set_tab_pos(gtk.POS_TOP)\n vbox = gtk.VBox(False, 5)\n\t\t\n vb = gtk.VBox()\n hbox = gtk.HBox(True, 3)\n\t\t\n valign = gtk.Alignment(0.5,0.25, 0, 0)\n lbl = gtk.Label(\"Name of student\")\n\t\t\n vb.pack_start(lbl, True, True, 10)\n text = gtk.Entry()\n\t\t\n vb.pack_start(text, True, True, 10)\n valign.add(vb)\n\t\t\n vbox.pack_start(valign)\n nb.append_page(vbox)\n nb.set_tab_label_text(vbox, \"Name\")\n hb = gtk.HButtonBox()\n\t\t\n btn1 = gtk.RadioButton(None,\"Degree\")\n hb.add(btn1)\n\t\t\n btn2 = gtk.RadioButton(btn1,\"P.G.\")\n hb.add(btn2)\n\t\t\n btn3 = gtk.RadioButton(btn1,\"Doctorate\")\n hb.add(btn3)\n\t\t\n nb.append_page(hb)\n nb.set_tab_label_text(hb, \"Qualification\")\n\t\t\n tv = gtk.TextView()\n nb.append_page(tv)\n nb.set_tab_label_text(tv, \"about\")\n\t\t\n self.add(nb)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 79599, "s": 79529, "text": "Upon execution, the above code displays a Notebook with three pages −" }, { "code": null, "e": 79778, "s": 79599, "text": "Frame class is a subclass of the gtk.Bin class. It draws a decorative border around the child widget placed in it. The frame may contain a label whose position may be customized." }, { "code": null, "e": 79857, "s": 79778, "text": "A gtk.Frame object is constructed with the help of the following constructor −" }, { "code": null, "e": 79890, "s": 79857, "text": "frame = gtk.Frame(label = None)\n" }, { "code": null, "e": 79947, "s": 79890, "text": "The following are the methods of the gtk.Frame() class −" }, { "code": null, "e": 80046, "s": 79947, "text": "set_label(text) − This sets the label as specified by text. If None, the current label is removed." }, { "code": null, "e": 80145, "s": 80046, "text": "set_label(text) − This sets the label as specified by text. If None, the current label is removed." }, { "code": null, "e": 80226, "s": 80145, "text": "set_label_widget() − This sets a widget other than gtk.Label as label for frame." }, { "code": null, "e": 80307, "s": 80226, "text": "set_label_widget() − This sets a widget other than gtk.Label as label for frame." }, { "code": null, "e": 80425, "s": 80307, "text": "set_label_align(x, y) − This sets the alignment of the frame's label widget and decoration (defaults are 0.0 and 0.5)" }, { "code": null, "e": 80543, "s": 80425, "text": "set_label_align(x, y) − This sets the alignment of the frame's label widget and decoration (defaults are 0.0 and 0.5)" }, { "code": null, "e": 80598, "s": 80543, "text": "set_shadow_type() − This sets the frame's shadow type." }, { "code": null, "e": 80653, "s": 80598, "text": "set_shadow_type() − This sets the frame's shadow type." }, { "code": null, "e": 80679, "s": 80653, "text": "The possible values are −" }, { "code": null, "e": 80695, "s": 80679, "text": "gtk.SHADOW_NONE" }, { "code": null, "e": 80709, "s": 80695, "text": "gtk.SHADOW_IN" }, { "code": null, "e": 80724, "s": 80709, "text": "gtk.SHADOW_OUT" }, { "code": null, "e": 80745, "s": 80724, "text": "gtk.SHADOW_ETCHED_IN" }, { "code": null, "e": 80766, "s": 80745, "text": "tk.SHADOW_ETCHED_OUT" }, { "code": null, "e": 80907, "s": 80766, "text": "The following code demonstrates the functioning of the Frame widget. A group of three objects of gtk.RadioButton is placed in an HButtonBox." }, { "code": null, "e": 81084, "s": 80907, "text": "btn1 = gtk.RadioButton(None,\"Degree\")\nbtn2 = gtk.RadioButton(btn1,\"P.G.\")\nbtn3 = gtk.RadioButton(btn1,\"Doctorate\")\nhb = gtk.HButtonBox()\nhb.add(btn1)\nhb.add(btn2)\nhb.add(btn3)\n" }, { "code": null, "e": 81196, "s": 81084, "text": "In order to draw border around the box, it is placed in a Frame widget, and it is added to the toplevel window." }, { "code": null, "e": 81241, "s": 81196, "text": "frm = gtk.Frame()\nfrm.add(hb)\nself.add(frm)\n" }, { "code": null, "e": 81270, "s": 81241, "text": "Observe the following code −" }, { "code": null, "e": 81908, "s": 81270, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Frame Demo\")\n self.set_default_size(250, 200)\n self.set_border_width(5)\n frm = gtk.Frame()\n hb = gtk.HButtonBox()\n btn1 = gtk.RadioButton(None,\"Degree\")\n hb.add(btn1)\n btn2 = gtk.RadioButton(btn1,\"P.G.\")\n hb.add(btn2)\n btn3 = gtk.RadioButton(btn1,\"Doctorate\")\n hb.add(btn3)\n frm.add(hb)\n frm.set_label(\"Qualifications\")\n self.add(frm)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 81960, "s": 81908, "text": "The above code will generate the following output −" }, { "code": null, "e": 82137, "s": 81960, "text": "gtk.AspectFrame class is a subclass of the Frame class. The child widget in this frame always retains its aspect ratio (of width and height) even if the main window is resized." }, { "code": null, "e": 82398, "s": 82137, "text": "The ratio property of gtk.AspectFrame widget determines the widget width:height ratio. An aspect ratio of 0.5 means the width is one half the height; an aspect ratio of 2.0 means the width is twice the height. The default value for the \"ratio\" property is 1.0." }, { "code": null, "e": 82474, "s": 82398, "text": "The following syntax is used for the constructor of gtk.AspectFrame class −" }, { "code": null, "e": 82566, "s": 82474, "text": "gtk.AspectFrame (label = None, xalign = 0.5, yalign = 0.5, ratio = 1.0, obey_child = True)\n" }, { "code": null, "e": 82736, "s": 82566, "text": "The xalign property determines the fraction of horizontal free space to the left of the child. 0.0 means no free space to the left, 1.0 means all free space to the left." }, { "code": null, "e": 82883, "s": 82736, "text": "The yalign property determines the fraction of vertical free space above the child. 0.0 means no free space above, 1.0 means all free space above." }, { "code": null, "e": 82964, "s": 82883, "text": "Ratio of width to height of frame is maintained if obey_child property is False." }, { "code": null, "e": 83051, "s": 82964, "text": "The obey_child property determines if the ratio is to be ignored. The default is True." }, { "code": null, "e": 83195, "s": 83051, "text": "The following code is similar to the one used for the Frame class. The only difference is that the ButonBox is placed in an AspectFrame widget." }, { "code": null, "e": 83297, "s": 83195, "text": "frm = gtk.AspectFrame(label = None, xalign = 0.5, yalign = 0.5, \n ratio = 5.0, obey_child = False)\n" }, { "code": null, "e": 83424, "s": 83297, "text": "Note − The obey_child property is set to False because it is desired to retain the aspect ratio even if the window is resized." }, { "code": null, "e": 83453, "s": 83424, "text": "Observe the following code −" }, { "code": null, "e": 84193, "s": 83453, "text": "import gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Aspect Frame Demo\")\n self.set_default_size(250, 200)\n self.set_border_width(5)\n frm = gtk.AspectFrame(label = None, xalign = 0.5, yalign = 0.5, \n ratio = 5.0, obey_child = False)\n hb = gtk.HButtonBox()\n btn1 = gtk.RadioButton(None,\"Degree\")\n hb.add(btn1)\n btn2 = gtk.RadioButton(btn1,\"P.G.\")\n hb.add(btn2)\n btn3 = gtk.RadioButton(btn1,\"Doctorate\")\n hb.add(btn3)\n frm.add(hb)\n frm.set_label(\"Qualifications\")\n self.add(frm)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n \nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 84266, "s": 84193, "text": "The above code will produce the following original and resized windows −" }, { "code": null, "e": 84282, "s": 84266, "text": "Original Window" }, { "code": null, "e": 84297, "s": 84282, "text": "Resized Window" }, { "code": null, "e": 84435, "s": 84297, "text": "The Treeview widget displays contents of a model implementing the gtk.TreeModel interface. PyGTK provides the following types of models −" }, { "code": null, "e": 84449, "s": 84435, "text": "gtk.ListStore" }, { "code": null, "e": 84463, "s": 84449, "text": "gtk.TreeStore" }, { "code": null, "e": 84481, "s": 84463, "text": "gtk.TreeModelSort" }, { "code": null, "e": 84676, "s": 84481, "text": "ListStore is a list model. When associated with a gtk.TreeView widget, it produces a List box containing the items to be selected from. A gtk.ListStore object is declared with following syntax −" }, { "code": null, "e": 84712, "s": 84676, "text": "store = gtk.ListStore(column_type)\n" }, { "code": null, "e": 84782, "s": 84712, "text": "A list may have multiple columns, the predefined type constants are −" }, { "code": null, "e": 84803, "s": 84782, "text": "gobject.TYPE_BOOLEAN" }, { "code": null, "e": 84822, "s": 84803, "text": "gobject.TYPE_BOXED" }, { "code": null, "e": 84840, "s": 84822, "text": "gobject.TYPE_CHAR" }, { "code": null, "e": 84860, "s": 84840, "text": "gobject.TYPE_DOUBLE" }, { "code": null, "e": 84878, "s": 84860, "text": "gobject.TYPE_ENUM" }, { "code": null, "e": 84897, "s": 84878, "text": "gobject.TYPE_FLOAT" }, { "code": null, "e": 84914, "s": 84897, "text": "gobject.TYPE_INT" }, { "code": null, "e": 84932, "s": 84914, "text": "gobject.TYPE_LONG" }, { "code": null, "e": 84950, "s": 84932, "text": "gobject.TYPE_NONE" }, { "code": null, "e": 84970, "s": 84950, "text": "gobject.TYPE_OBJECT" }, { "code": null, "e": 84990, "s": 84970, "text": "gobject.TYPE_STRING" }, { "code": null, "e": 85009, "s": 84990, "text": "gobject.TYPE_UCHAR" }, { "code": null, "e": 85027, "s": 85009, "text": "gobject.TYPE_UINT" }, { "code": null, "e": 85046, "s": 85027, "text": "gobject.TYPE_ULONG" }, { "code": null, "e": 85066, "s": 85046, "text": "gtk.gdk.pixbuf etc." }, { "code": null, "e": 85137, "s": 85066, "text": "For example, a ListStore object to store string items is declared as −" }, { "code": null, "e": 85180, "s": 85137, "text": "store = gtk.ListStore(gobject.TYPE_STRING\n" }, { "code": null, "e": 85244, "s": 85180, "text": "In order to add items in the store, append() methods are used −" }, { "code": null, "e": 85271, "s": 85244, "text": "store.append ([\"item 1\"])\n" }, { "code": null, "e": 85413, "s": 85271, "text": "TreeStore is a model for multi-columned Tree widget. For example, the following statement creates a store with one column having string item." }, { "code": null, "e": 85457, "s": 85413, "text": "Store = gtk.TreeStore(gobject.TYPE_STRING)\n" }, { "code": null, "e": 85614, "s": 85457, "text": "In order to add items in a TreeStore, use the append() method. The append() method has two parameters, parent and row. To add toplevel item, parent is None." }, { "code": null, "e": 85651, "s": 85614, "text": "row1 = store.append(None, ['row1'])\n" }, { "code": null, "e": 85707, "s": 85651, "text": "You need to repeat this statement to add multiple rows." }, { "code": null, "e": 85802, "s": 85707, "text": "In order to add child rows, pass the toplevel row as parent parameter to the append() method −" }, { "code": null, "e": 85845, "s": 85802, "text": "childrow = store.append(row1, ['child1'])\n" }, { "code": null, "e": 85907, "s": 85845, "text": "You need to repeat this statement to add multiple child rows." }, { "code": null, "e": 85982, "s": 85907, "text": "Now, create a TreeView widget and use the above TreeStore object as model." }, { "code": null, "e": 86014, "s": 85982, "text": "treeview = gtk.TreeView(store)\n" }, { "code": null, "e": 86226, "s": 86014, "text": "We now have to create TreeViewColumn to display store data. The object of gtk.TreeViewColumn manages header and the cells using gtk.CelRenderer. TreeViewColumn object is created using the following constructor −" }, { "code": null, "e": 86272, "s": 86226, "text": "gtk.TreeViewColumn(title, cell_renderer,...)\n" }, { "code": null, "e": 86518, "s": 86272, "text": "In addition to title and renderer, it takes zero or more attribute=column pairs to specify from which tree model column the attribute's value is to be retrieved. These parameters can also be set using methods of TreeViewColumn class given below." }, { "code": null, "e": 86698, "s": 86518, "text": "A gtk.CellRenderer is a base class for a set of objects for rendering different types of data. The derived classes are CellRendererText, CellRendererPixBuf and CellRendererToggle." }, { "code": null, "e": 86783, "s": 86698, "text": "The following methods of the TreeViewColumn class are used to configure its object −" }, { "code": null, "e": 86989, "s": 86783, "text": "TreeViewColumn.pack_start(cell, expand = True) − This method packs the CellRenderer object into the beginning column. If expand parameter is set to True, columns entire allocated space is assigned to cell." }, { "code": null, "e": 87195, "s": 86989, "text": "TreeViewColumn.pack_start(cell, expand = True) − This method packs the CellRenderer object into the beginning column. If expand parameter is set to True, columns entire allocated space is assigned to cell." }, { "code": null, "e": 87365, "s": 87195, "text": "TreeViewColumn.add_attribute(cell, attribute, column) − This method adds an attribute mapping to the list in the tree column. The column is the column of the tree model." }, { "code": null, "e": 87535, "s": 87365, "text": "TreeViewColumn.add_attribute(cell, attribute, column) − This method adds an attribute mapping to the list in the tree column. The column is the column of the tree model." }, { "code": null, "e": 87661, "s": 87535, "text": "TreeViewColumn.set_attributes() − This method sets the attribute locations of the renderer using the attribute = column pairs" }, { "code": null, "e": 87787, "s": 87661, "text": "TreeViewColumn.set_attributes() − This method sets the attribute locations of the renderer using the attribute = column pairs" }, { "code": null, "e": 87858, "s": 87787, "text": "TreeViewColumn.set_visible() − If True, the treeview column is visible" }, { "code": null, "e": 87929, "s": 87858, "text": "TreeViewColumn.set_visible() − If True, the treeview column is visible" }, { "code": null, "e": 88020, "s": 87929, "text": "TreeViewColumn.set_title() − This method sets the \"title\" property to the value specified." }, { "code": null, "e": 88111, "s": 88020, "text": "TreeViewColumn.set_title() − This method sets the \"title\" property to the value specified." }, { "code": null, "e": 88211, "s": 88111, "text": "TreeViewColumn.set_lickable() − If set to True, the header can take keyboard focus, and be clicked." }, { "code": null, "e": 88311, "s": 88211, "text": "TreeViewColumn.set_lickable() − If set to True, the header can take keyboard focus, and be clicked." }, { "code": null, "e": 88416, "s": 88311, "text": "TreeViewColumn.set_alignment(xalign) − This method sets the \"alignment\" property to the value of xalign." }, { "code": null, "e": 88521, "s": 88416, "text": "TreeViewColumn.set_alignment(xalign) − This method sets the \"alignment\" property to the value of xalign." }, { "code": null, "e": 88611, "s": 88521, "text": "The \"clicked\" signal is emitted when the user clicks on the treeviewcolumn header button." }, { "code": null, "e": 88731, "s": 88611, "text": "After having configured the TreeViewColumn object, it is added to the TreeView widget using the append_column() method." }, { "code": null, "e": 88795, "s": 88731, "text": "The following are the important methods of the TreeView class −" }, { "code": null, "e": 89012, "s": 88795, "text": "TreevVew.set_model() − This sets the \"model\" property for the treeview. If the treeview already has a model set, this method will remove it before setting the new model. If model is None, it will unset the old model." }, { "code": null, "e": 89229, "s": 89012, "text": "TreevVew.set_model() − This sets the \"model\" property for the treeview. If the treeview already has a model set, this method will remove it before setting the new model. If model is None, it will unset the old model." }, { "code": null, "e": 89320, "s": 89229, "text": "TreeView.set_header_clickable() − If set to True, the column title buttons can be clicked." }, { "code": null, "e": 89411, "s": 89320, "text": "TreeView.set_header_clickable() − If set to True, the column title buttons can be clicked." }, { "code": null, "e": 89504, "s": 89411, "text": "TreeView.append_column() − This appends the specified TreeViewColumn to the list of columns." }, { "code": null, "e": 89597, "s": 89504, "text": "TreeView.append_column() − This appends the specified TreeViewColumn to the list of columns." }, { "code": null, "e": 89677, "s": 89597, "text": "TreeView.remove_column() − This removes the specified column from the treeview." }, { "code": null, "e": 89757, "s": 89677, "text": "TreeView.remove_column() − This removes the specified column from the treeview." }, { "code": null, "e": 89875, "s": 89757, "text": "TreeView.insert_column() − This inserts the specified column into the treeview at the location specified by position." }, { "code": null, "e": 89993, "s": 89875, "text": "TreeView.insert_column() − This inserts the specified column into the treeview at the location specified by position." }, { "code": null, "e": 90043, "s": 89993, "text": "The TreeView widget emits the following signals −" }, { "code": null, "e": 90161, "s": 90043, "text": "Two examples of the TreeView widget are given below. The first example uses a ListStore to produce a simple ListView." }, { "code": null, "e": 90291, "s": 90161, "text": "Here a ListStore object is created and string items are added to it. This ListStore object is used as model for TreeView object −" }, { "code": null, "e": 90372, "s": 90291, "text": "store = gtk.ListStore(str)\n\ntreeView = gtk.TreeView()\ntreeView.set_model(store)\n" }, { "code": null, "e": 90470, "s": 90372, "text": "Then a CellRendererText is added to a TreeViewColumn object and the same is appended to TreeView." }, { "code": null, "e": 90600, "s": 90470, "text": "rendererText = gtk.CellRendererText()\ncolumn = gtk.TreeViewColumn(\"Name\", rendererText, text = 0)\ntreeView.append_column(column)\n" }, { "code": null, "e": 90684, "s": 90600, "text": "TreeView Object is placed on the toplevel window by adding it to a Fixed container." }, { "code": null, "e": 90713, "s": 90684, "text": "Observe the following code −" }, { "code": null, "e": 92086, "s": 90713, "text": "import pygtk\npygtk.require('2.0')\nimport gtk\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"TreeView with ListStore\")\n self.set_default_size(250, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n store = gtk.ListStore(str)\n store.append ([\"PyQt\"])\n store.append ([\"Tkinter\"])\n store.append ([\"WxPython\"])\n store.append ([\"PyGTK\"])\n store.append ([\"PySide\"])\n \n treeView = gtk.TreeView()\n treeView.set_model(store)\n\t\t\n rendererText = gtk.CellRendererText()\n column = gtk.TreeViewColumn(\"Python GUI Libraries\", rendererText, text=0)\n treeView.append_column(column)\n \n fixed = gtk.Fixed()\n lbl = gtk.Label(\"select a GUI toolkit\")\n fixed.put(lbl, 25,75)\n fixed.put(treeView, 125,15)\n\t\t\n lbl2 = gtk.Label(\"Your choice is:\")\n fixed.put(lbl2, 25,175)\n self.label = gtk.Label(\"\")\n\t\t\n fixed.put(self.label, 125,175)\n self.add(fixed)\n \n treeView.connect(\"row-activated\", self.on_activated)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def on_activated(self, widget, row, col):\n \n\t model = widget.get_model()\n text = model[row][0]\n self.label.set_text(text)\n\t\t\ndef main():\n gtk.main()\n return\n\nif __name__ == \"__main__\":\n bcb = PyApp()\n main()" }, { "code": null, "e": 92204, "s": 92086, "text": "The item selected by the user is displayed on a label in the window as the on_activated callback function is invoked." }, { "code": null, "e": 92425, "s": 92204, "text": "The second example builds a hierarchical TreeView from a TreeStore. This program follows the same sequence of building the store, setting it as model for TreeView, designing a TreeViewColumn and appending it to TreeView." }, { "code": null, "e": 93619, "s": 92425, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"TreeView with TreeStore\")\n self.set_size_request(400,200)\n self.set_position(gtk.WIN_POS_CENTER)\n vbox = gtk.VBox(False, 5)\n \n # create a TreeStore with one string column to use as the model\n store = gtk.TreeStore(str)\n \n # add row\n row1 = store.append(None, ['JAVA'])\n \n #add child rows\n store.append(row1,['AWT'])\n store.append(row1,['Swing'])\n store.append(row1,['JSF'])\n \n # add another row\n row2 = store.append(None, ['Python'])\n store.append(row2,['PyQt'])\n store.append(row2,['WxPython'])\n store.append(row2,['PyGTK'])\n \n # create the TreeView using treestore\n treeview = gtk.TreeView(store)\n tvcolumn = gtk.TreeViewColumn('GUI Toolkits')\n treeview.append_column(tvcolumn)\n\t\t\n cell = gtk.CellRendererText()\n tvcolumn.pack_start(cell, True)\n tvcolumn.add_attribute(cell, 'text', 0)\n vbox.add(treeview)\n\t\t\n self.add(vbox)\n \n\t self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 93670, "s": 93619, "text": "The following TreeView is displayed as an output −" }, { "code": null, "e": 93883, "s": 93670, "text": "Paned class is the base class for widgets which can display two adjustable panes either horizontally (gtk.Hpaned) or vertically (gtk.Vpaned). Child widgets to panes are added by using pack1() and pack2() methods." }, { "code": null, "e": 94120, "s": 93883, "text": "Paned widget draws a separator slider between two panes and provides a handle to adjust their relative width/height. If the resize property of child widget inside a pane is set to True, it will resize according to the size of the panes." }, { "code": null, "e": 94193, "s": 94120, "text": "The following methods are available for HPaned as well as VPaned class −" }, { "code": null, "e": 94277, "s": 94193, "text": "Paned.add1(child) − This adds the widget specified by child to the top or left pane" }, { "code": null, "e": 94361, "s": 94277, "text": "Paned.add1(child) − This adds the widget specified by child to the top or left pane" }, { "code": null, "e": 94450, "s": 94361, "text": "Paned.add2(child) − This adds the widget specified by child to the bottom or right pane." }, { "code": null, "e": 94539, "s": 94450, "text": "Paned.add2(child) − This adds the widget specified by child to the bottom or right pane." }, { "code": null, "e": 94814, "s": 94539, "text": "Paned.pack1(child, resize, shrink) − This adds the widget specified by child to the top or left pane with the parameters. If resize is True, child should be resized when the paned widget is resized. If shrink is True, child can be made smaller than its minimum size request." }, { "code": null, "e": 95089, "s": 94814, "text": "Paned.pack1(child, resize, shrink) − This adds the widget specified by child to the top or left pane with the parameters. If resize is True, child should be resized when the paned widget is resized. If shrink is True, child can be made smaller than its minimum size request." }, { "code": null, "e": 95187, "s": 95089, "text": "Paned.pack2(child, resize, shrink) − This sets the position of the divider between the two panes." }, { "code": null, "e": 95285, "s": 95187, "text": "Paned.pack2(child, resize, shrink) − This sets the position of the divider between the two panes." }, { "code": null, "e": 95342, "s": 95285, "text": "Both types of Paned widgets emit the following signals −" }, { "code": null, "e": 95687, "s": 95342, "text": "The following example uses a gtk.Hpaned widget. In the left pane, a TreeView widget is added, and in the right pane, there is a TextView widget. When any row in TreeView is selected, it will emit row_activated signal which is connected to a callback function. The on_activated()function retrieves row's text and displays in the text view panel." }, { "code": null, "e": 95706, "s": 95687, "text": "Observe the code −" }, { "code": null, "e": 97289, "s": 95706, "text": "import gtk, gobject\n\nclass PyApp(gtk.Window):\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"HPaned widget Demo\")\n self.set_default_size(250, 200)\n vp = gtk.HPaned()\n sw = gtk.ScrolledWindow()\n sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) \n\t\t\n tree = gtk.TreeView()\n languages = gtk.TreeViewColumn()\n languages.set_title(\"GUI Toolkits\")\n cell = gtk.CellRendererText()\n languages.pack_start(cell, True)\n languages.add_attribute(cell, \"text\", 0)\n treestore = gtk.TreeStore(str)\n it = treestore.append(None, [\"Python\"])\n\t\t\n treestore.append(it, [\"PyQt\"])\n treestore.append(it, [\"wxPython\"])\n treestore.append(it, [\"PyGTK\"])\n treestore.append(it, [\"Pydide\"])\n\t\t\n it = treestore.append(None, [\"Java\"])\n treestore.append(it, [\"AWT\"])\n treestore.append(it, [\"Swing\"])\n treestore.append(it, [\"JSF\"])\n treestore.append(it, [\"SWT\"])\n\t\t\n tree.append_column(languages)\n tree.set_model(treestore)\n\t\t\n vp.add1(tree)\n self.tv = gtk.TextView()\n vp.add2(self.tv)\n vp.set_position(100)\n self.add(vp)\n\t\t\n tree.connect(\"row-activated\", self.on_activated)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def on_activated(self, widget, row, col):\n model = widget.get_model()\n text = model[row][0]\n print text\n\t\t\n buffer = gtk.TextBuffer()\n buffer.set_text(text+\" is selected\")\n self.tv.set_buffer(buffer)\n\nif __name__ == '__main__':\n PyApp()\n gtk.main()" }, { "code": null, "e": 97341, "s": 97289, "text": "The above code will generate the following output −" }, { "code": null, "e": 97542, "s": 97341, "text": "A notification area, usually at the bottom of a window is called the status bar. Any type of status change message can be displayed on the status bar. It also has a grip using which it can be resized." }, { "code": null, "e": 97799, "s": 97542, "text": "The gtk.Statusbar widget maintains a stack of messages. Hence, new message gets displayed on top of the current message. If it is popped, earlier message will be visible again. Source of the message must be identified by context_id to identify it uniquely." }, { "code": null, "e": 97862, "s": 97799, "text": "The following is the constructor of the gtk.Statusbar widget −" }, { "code": null, "e": 97885, "s": 97862, "text": "bar = gtk.Statusbar()\n" }, { "code": null, "e": 97944, "s": 97885, "text": "The following are the methods of the gtk.Statusbar class −" }, { "code": null, "e": 98031, "s": 97944, "text": "Statusbar.push(context_id, text) − This pushes a new message onto a statusbar's stack." }, { "code": null, "e": 98118, "s": 98031, "text": "Statusbar.push(context_id, text) − This pushes a new message onto a statusbar's stack." }, { "code": null, "e": 98233, "s": 98118, "text": "Statusbar.pop(context_id) − This removes the top message with the specified context_id from the statusbar's stack." }, { "code": null, "e": 98348, "s": 98233, "text": "Statusbar.pop(context_id) − This removes the top message with the specified context_id from the statusbar's stack." }, { "code": null, "e": 98408, "s": 98348, "text": "The following signals are emitted by the Statusbar widget −" }, { "code": null, "e": 98665, "s": 98408, "text": "The following example demonstrates the functioning of Statusbar. Toplevel window contains a VBox with two rows. Upper row has a Fixed widget in which a label, an Entry widget and a button is put. Whereas, in the bottom row, a gtk.Statusbar widget is added." }, { "code": null, "e": 98741, "s": 98665, "text": "In order to send message to status bar, its context_id needs to be fetched." }, { "code": null, "e": 98785, "s": 98741, "text": "id1 = self.bar.get_context_id(\"Statusbar\")\n" }, { "code": null, "e": 99051, "s": 98785, "text": "The 'clicked' signal of the Button object is connected to a callback function through which a message is pushed in the status bar. And, the 'activate' signal is emitted when Enter key is pressed inside the Entry widget. This widget is connected to another callback." }, { "code": null, "e": 99143, "s": 99051, "text": "btn.connect(\"clicked\", self.on_clicked, id1)\ntxt.connect(\"activate\", self.on_entered, id1)\n" }, { "code": null, "e": 99223, "s": 99143, "text": "Both callbacks use push() method to flash the message in the notification area." }, { "code": null, "e": 99252, "s": 99223, "text": "Observe the following code −" }, { "code": null, "e": 100258, "s": 99252, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Statusbar demo\")\n self.set_size_request(400,200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox()\n fix = gtk.Fixed()\n lbl = gtk.Label(\"Enter name\")\n\t\t\n fix.put(lbl, 175, 50)\n txt = gtk.Entry()\n fix.put(txt, 150, 100)\n\t\t\n btn = gtk.Button(\"ok\")\n fix.put(btn, 200,150)\n\t\t\n vbox.add(fix)\n self.bar = gtk.Statusbar()\n vbox.pack_start(self.bar, True, False, 0)\n\t\t\n id1 = self.bar.get_context_id(\"Statusbar\")\n btn.connect(\"clicked\", self.on_clicked, id1)\n txt.connect(\"activate\", self.on_entered, id1)\n\t\t\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def on_clicked(self, widget, data=None):\n self.bar.push(data, \"Button clicked\n\t\t\n def on_entered(self, widget, data):\n self.bar.push(data, \"text entered\")\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 100325, "s": 100258, "text": "Upon execution, the above code will display the following output −" }, { "code": null, "e": 100417, "s": 100325, "text": "Try typing in the text box and press Enter to see the 'text entered' message in status bar." }, { "code": null, "e": 100591, "s": 100417, "text": "Progress bars are used to give user the visual indication of a long running process. The gtk.ProgressBar widget can be used in two modes — percentage mode and activity mode." }, { "code": null, "e": 101013, "s": 100591, "text": "When it is possible to accurately estimate how much of work is pending to be completed, the progress bar can be used in percentage mode, and the user sees an incremental bar showing percentage of completed job. If on the other hand, the amount of work to be completed can be accurately determined, the progress bar is used in activity mode in which, the bar shows the activity by displaying a block moving back and forth." }, { "code": null, "e": 101093, "s": 101013, "text": "The following constructor initializes the widget of the gtk.ProgressBar class −" }, { "code": null, "e": 101117, "s": 101093, "text": "pb = gtk.ProgressBar()\n" }, { "code": null, "e": 101186, "s": 101117, "text": "gtk.ProgressBar uses the following methods to manage functionality −" }, { "code": null, "e": 101416, "s": 101186, "text": "ProgressBar.pulse() − This nudges the progressbar to indicate that some progress has been made, but you don't know how much. This method also changes the progress bar mode to \"activity mode,\" where a block bounces back and forth." }, { "code": null, "e": 101646, "s": 101416, "text": "ProgressBar.pulse() − This nudges the progressbar to indicate that some progress has been made, but you don't know how much. This method also changes the progress bar mode to \"activity mode,\" where a block bounces back and forth." }, { "code": null, "e": 101824, "s": 101646, "text": "ProgressBar.set_fraction(fraction) − This causes the progress bar to \"fill in\" the portion of the bar specified by fraction. The value of fraction should be between 0.0 and 1.0." }, { "code": null, "e": 102002, "s": 101824, "text": "ProgressBar.set_fraction(fraction) − This causes the progress bar to \"fill in\" the portion of the bar specified by fraction. The value of fraction should be between 0.0 and 1.0." }, { "code": null, "e": 102177, "s": 102002, "text": "ProgressBar.set_pulse_setup() − This sets the portion (specified by fraction) of the total progress bar length to move the bouncing block for each call to the pulse() method." }, { "code": null, "e": 102352, "s": 102177, "text": "ProgressBar.set_pulse_setup() − This sets the portion (specified by fraction) of the total progress bar length to move the bouncing block for each call to the pulse() method." }, { "code": null, "e": 102590, "s": 102352, "text": "ProgressBar.set_orientation() − This sets the orientation of the progress bar. It may be set to one of the following constants:\n\ngtk.PROGRESS_LEFT_TO_RIGHT\ngtk.PROGRESS_RIGHT_TO_LEFT\ngtk.PROGRESS_BOTTOM_TO_TOP\ngtk.PROGRESS_TOP_TO_BOTTOM\n" }, { "code": null, "e": 102718, "s": 102590, "text": "ProgressBar.set_orientation() − This sets the orientation of the progress bar. It may be set to one of the following constants:" }, { "code": null, "e": 102745, "s": 102718, "text": "gtk.PROGRESS_LEFT_TO_RIGHT" }, { "code": null, "e": 102772, "s": 102745, "text": "gtk.PROGRESS_LEFT_TO_RIGHT" }, { "code": null, "e": 102799, "s": 102772, "text": "gtk.PROGRESS_RIGHT_TO_LEFT" }, { "code": null, "e": 102826, "s": 102799, "text": "gtk.PROGRESS_RIGHT_TO_LEFT" }, { "code": null, "e": 102853, "s": 102826, "text": "gtk.PROGRESS_BOTTOM_TO_TOP" }, { "code": null, "e": 102880, "s": 102853, "text": "gtk.PROGRESS_BOTTOM_TO_TOP" }, { "code": null, "e": 102907, "s": 102880, "text": "gtk.PROGRESS_TOP_TO_BOTTOM" }, { "code": null, "e": 102934, "s": 102907, "text": "gtk.PROGRESS_TOP_TO_BOTTOM" }, { "code": null, "e": 103097, "s": 102934, "text": "In the following program, the gtk.ProgressBar widget is used in activity mode. Hence, the initial position of progress is set to 0.0 by the set_fraction() method." }, { "code": null, "e": 103181, "s": 103097, "text": "self.pb = gtk.ProgressBar()\nself.pb.set_text(\"Progress\")\nself.pb.set_fraction(0.0)\n" }, { "code": null, "e": 103384, "s": 103181, "text": "In order to increment the progress by 1 percent after 100 milliseconds, a timer object is declared and a callback function is set up to be invoked after every 100 ms so that the progress bar is updated." }, { "code": null, "e": 103448, "s": 103384, "text": "self.timer = gobject.timeout_add (100, progress_timeout, self)\n" }, { "code": null, "e": 103644, "s": 103448, "text": "Here, progress_timeout() is the callback function. It increments the parameter of the set_fraction() method by 1 percent and updates the text in progress bar to show the percentage of completion." }, { "code": null, "e": 103821, "s": 103644, "text": "def progress_timeout(pbobj):\n new_val = pbobj.pb.get_fraction() + 0.01\n pbobj.pb.set_fraction(new_val)\n pbobj.pb.set_text(str(new_val*100)+\" % completed\")\n return True\n" }, { "code": null, "e": 103850, "s": 103821, "text": "Observe the following code −" }, { "code": null, "e": 104597, "s": 103850, "text": "import gtk, gobject\n \ndef progress_timeout(pbobj):\n new_val = pbobj.pb.get_fraction() + 0.01\n pbobj.pb.set_fraction(new_val)\n pbobj.pb.set_text(str(new_val*100)+\" % completed\")\n return True\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Progressbar demo\")\n self.set_size_request(300,200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n fix = gtk.Fixed()\n self.pb = gtk.ProgressBar()\n self.pb.set_text(\"Progress\")\n self.pb.set_fraction(0.0)\n\t\t\n fix.put(self.pb,80,100)\n self.add(fix)\n self.timer = gobject.timeout_add (100, progress_timeout, self)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\nPyApp()\ngtk.main()" }, { "code": null, "e": 104649, "s": 104597, "text": "The above code will generate the following output −" }, { "code": null, "e": 104743, "s": 104649, "text": "To use the progress bar in activity mode, change callback function to the following and run −" }, { "code": null, "e": 104808, "s": 104743, "text": "def progress_timeout(pbobj):\n pbobj.pb.pulse()\n return True\n" }, { "code": null, "e": 104911, "s": 104808, "text": "The back and forth movement of a block inside the Progress bar will show the progress of the activity." }, { "code": null, "e": 105345, "s": 104911, "text": "If a widget has an area larger than that of the toplevel window, it is associated with a ViewPort container. A gtk.Viewport widget provides adjustment capability to be used in a ScrolledWindow. A Label widget for instance, doesn't have any adjustments. Hence it needs a Viewport. Some widgets have a native scrolling support. But a Label or a gtk.Table widget doesn't have an in-built scrolling support. Hence they must use Viewport." }, { "code": null, "e": 105392, "s": 105345, "text": "ViewPort class has the following constructor −" }, { "code": null, "e": 105418, "s": 105392, "text": "gtk.Viewport(hadj, vadj)\n" }, { "code": null, "e": 105495, "s": 105418, "text": "Here, hadj and vadj are the adjustment objects associated with the viewport." }, { "code": null, "e": 105543, "s": 105495, "text": "gtk.ViewPort class uses the following methods −" }, { "code": null, "e": 105609, "s": 105543, "text": "Viewport.set_hadjustment() − This sets the \"hadjustment\" property" }, { "code": null, "e": 105675, "s": 105609, "text": "Viewport.set_hadjustment() − This sets the \"hadjustment\" property" }, { "code": null, "e": 105741, "s": 105675, "text": "Viewport.set_vadjustment() − This sets the \"vadjustment\" property" }, { "code": null, "e": 105807, "s": 105741, "text": "Viewport.set_vadjustment() − This sets the \"vadjustment\" property" }, { "code": null, "e": 106020, "s": 105807, "text": "Viewport.set_shadow_type() − This sets the \"shadow-type\" property to the value of type. The value of type must be one of −\n\ngtk.SHADOW_NONE\ngtk.SHADOW_IN\ngtk.SHADOW_OUT\ngtk.SHADOW_ETCHED_IN\ngtk.SHADOW_ETCHED_OUT\n" }, { "code": null, "e": 106143, "s": 106020, "text": "Viewport.set_shadow_type() − This sets the \"shadow-type\" property to the value of type. The value of type must be one of −" }, { "code": null, "e": 106159, "s": 106143, "text": "gtk.SHADOW_NONE" }, { "code": null, "e": 106175, "s": 106159, "text": "gtk.SHADOW_NONE" }, { "code": null, "e": 106189, "s": 106175, "text": "gtk.SHADOW_IN" }, { "code": null, "e": 106203, "s": 106189, "text": "gtk.SHADOW_IN" }, { "code": null, "e": 106218, "s": 106203, "text": "gtk.SHADOW_OUT" }, { "code": null, "e": 106233, "s": 106218, "text": "gtk.SHADOW_OUT" }, { "code": null, "e": 106254, "s": 106233, "text": "gtk.SHADOW_ETCHED_IN" }, { "code": null, "e": 106275, "s": 106254, "text": "gtk.SHADOW_ETCHED_IN" }, { "code": null, "e": 106297, "s": 106275, "text": "gtk.SHADOW_ETCHED_OUT" }, { "code": null, "e": 106319, "s": 106297, "text": "gtk.SHADOW_ETCHED_OUT" }, { "code": null, "e": 106466, "s": 106319, "text": "The gtk.Viewport object emits the set-scroll-adjustments signal when one or both of the horizontal and vertical gtk.Adjustment objects is changed." }, { "code": null, "e": 106690, "s": 106466, "text": "Scrolled window is created to access other widget of area larger than parent window. Some widgets like TreeView and TextView of native support for scrolling. For others such as Label or Table, a Viewport should be provided." }, { "code": null, "e": 106773, "s": 106690, "text": "The following syntax is used for the constructor of the gtk.ScrolledWindow class −" }, { "code": null, "e": 106810, "s": 106773, "text": "sw = gtk.ScrolledWindow(hadj, vadj)\n" }, { "code": null, "e": 106874, "s": 106810, "text": "The following are the methods of the gtk.ScrolledWindow class −" }, { "code": null, "e": 106972, "s": 106874, "text": "ScrolledWindow.set_hadjustment() − This sets the horizontal adjustment to a gtk.Adjustment object" }, { "code": null, "e": 107070, "s": 106972, "text": "ScrolledWindow.set_hadjustment() − This sets the horizontal adjustment to a gtk.Adjustment object" }, { "code": null, "e": 107166, "s": 107070, "text": "ScrolledWindow.set_vadjustment() − This sets the vertical adjustment to a gtk.Adjustment object" }, { "code": null, "e": 107262, "s": 107166, "text": "ScrolledWindow.set_vadjustment() − This sets the vertical adjustment to a gtk.Adjustment object" }, { "code": null, "e": 107644, "s": 107262, "text": "ScrolledWindow.set_Policy (hpolicy, vpolicy) − This sets the \"hscrollbar_policy\" and \"vscrollbar_policy\" properties. One of the following predefined constants are used −\n\ngtk.POLICY_ALWAYS − The scrollbar is always present\ngtk.POLICY_AUTOMATIC − The scrollbar is present only if needed i.e. the contents are larget than the window\ngtk.POLICY_NEVER − The scrollbar is never present\n" }, { "code": null, "e": 107814, "s": 107644, "text": "ScrolledWindow.set_Policy (hpolicy, vpolicy) − This sets the \"hscrollbar_policy\" and \"vscrollbar_policy\" properties. One of the following predefined constants are used −" }, { "code": null, "e": 107866, "s": 107814, "text": "gtk.POLICY_ALWAYS − The scrollbar is always present" }, { "code": null, "e": 107918, "s": 107866, "text": "gtk.POLICY_ALWAYS − The scrollbar is always present" }, { "code": null, "e": 108026, "s": 107918, "text": "gtk.POLICY_AUTOMATIC − The scrollbar is present only if needed i.e. the contents are larget than the window" }, { "code": null, "e": 108134, "s": 108026, "text": "gtk.POLICY_AUTOMATIC − The scrollbar is present only if needed i.e. the contents are larget than the window" }, { "code": null, "e": 108184, "s": 108134, "text": "gtk.POLICY_NEVER − The scrollbar is never present" }, { "code": null, "e": 108234, "s": 108184, "text": "gtk.POLICY_NEVER − The scrollbar is never present" }, { "code": null, "e": 108529, "s": 108234, "text": "ScrolledWindow.add_with_viewport(child) − This method is used to add a widget (specified by child) without native scrolling capabilities to the scrolled window. This is a convenience function that is equivalent to adding child to a gtk.Viewport, then adding the viewport to the scrolled window." }, { "code": null, "e": 108824, "s": 108529, "text": "ScrolledWindow.add_with_viewport(child) − This method is used to add a widget (specified by child) without native scrolling capabilities to the scrolled window. This is a convenience function that is equivalent to adding child to a gtk.Viewport, then adding the viewport to the scrolled window." }, { "code": null, "e": 109009, "s": 108824, "text": "The following code adds a scrolled window around a gtk.Table object with 10 by 10 dimensions. Since a Table object doesn't support adjustments automatically, it is added in a Viewport." }, { "code": null, "e": 109061, "s": 109009, "text": "sw = gtk.ScrolledWindow()\ntable = gtk.Table(10,10)\n" }, { "code": null, "e": 109166, "s": 109061, "text": "Two nested loops are used to add 10 rows of 10 columns each. A gtk.Button widget is placed in each cell." }, { "code": null, "e": 109322, "s": 109166, "text": "for i in range(1,11):\n for j in range(1,11):\n caption = \"Btn\"+str(j)+str(i)\n btn = gtk.Button(caption)\n table.attach(btn, i, i+1, j, j+1)\n" }, { "code": null, "e": 109405, "s": 109322, "text": "This large enough table is now added in the scrolled window along with a viewport." }, { "code": null, "e": 109434, "s": 109405, "text": "sw.add_with_viewport(table)\n" }, { "code": null, "e": 109463, "s": 109434, "text": "Observe the following code −" }, { "code": null, "e": 110158, "s": 109463, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"ScrolledWindow and Viewport\")\n self.set_size_request(400,300)\n self.set_position(gtk.WIN_POS_CENTER)\n sw = gtk.ScrolledWindow()\n table = gtk.Table(10,10)\n table.set_row_spacings(10)\n table.set_col_spacings(10)\n for i in range(1,11):\n for j in range(1,11):\n caption = \"Btn\"+str(j)+str(i)\n btn = gtk.Button(caption)\n table.attach(btn, i, i+1, j, j+1)\n sw.add_with_viewport(table)\n self.add(sw)\n \n\t self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 110210, "s": 110158, "text": "The above code will generate the following output −" }, { "code": null, "e": 110442, "s": 110210, "text": "The gtk.Arrow object is used to draw simple arrow pointing towards four cardinal directions. This class is inherited from the gtk.Misc class and the object will occupy any space allocated it, for instance, a Label or Button widget." }, { "code": null, "e": 110511, "s": 110442, "text": "Typically, Arrow object is created using the following constructor −" }, { "code": null, "e": 110553, "s": 110511, "text": "Arr = gtk.Arrow(arrow_type, shadow_type)\n" }, { "code": null, "e": 110595, "s": 110553, "text": "The predefined arrow_type constants are −" }, { "code": null, "e": 110608, "s": 110595, "text": "gtk.ARROW_UP" }, { "code": null, "e": 110623, "s": 110608, "text": "gtk.ARROW_DOWN" }, { "code": null, "e": 110638, "s": 110623, "text": "gtk.ARROW_LEFT" }, { "code": null, "e": 110654, "s": 110638, "text": "gtk.ARROW_RIGHT" }, { "code": null, "e": 110727, "s": 110654, "text": "The predefined shadow_type constants are listed in the following table −" }, { "code": null, "e": 111002, "s": 110727, "text": "In the following example, four Button widgets are added to an Hbox. On top of each button, a gtk.Arrow object pointing UP, DOWN, LEFT and RIGHT respectively is placed. The HBOX container is placed at the bottom of the toplevel window with the help of an Alignment container." }, { "code": null, "e": 111021, "s": 111002, "text": "Observe the code −" }, { "code": null, "e": 112108, "s": 111021, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Arrow Demo\")\n self.set_size_request(300, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox(False, 5)\n hbox = gtk.HBox(True, 3)\n valign = gtk.Alignment(0, 1, 0, 0)\n vbox.pack_start(valign)\n\t\t\n arr1 = gtk.Arrow(gtk.ARROW_UP, gtk.SHADOW_NONE)\n arr2 = gtk.Arrow(gtk.ARROW_DOWN, gtk.SHADOW_NONE)\n arr3 = gtk.Arrow(gtk.ARROW_LEFT, gtk.SHADOW_NONE)\n arr4 = gtk.Arrow(gtk.ARROW_RIGHT, gtk.SHADOW_NONE)\n\t\t\n btn1 = gtk.Button()\n btn1.add(arr1)\n btn2 = gtk.Button()\n btn2.add(arr2)\n btn3 = gtk.Button()\n btn3.add(arr3)\n btn4 = gtk.Button()\n btn4.add(arr4)\n\t\t\n hbox.add(btn1)\n hbox.add(btn2)\n hbox.add(btn3)\n hbox.add(btn4)\n\t\t\n halign = gtk.Alignment(0.5, 0.5, 0, 0)\n halign.add(hbox)\n\t\t\n vbox.pack_start(halign, False, True, 10)\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 112160, "s": 112108, "text": "The above code will generate the following output −" }, { "code": null, "e": 112485, "s": 112160, "text": "This class is also inherited from the gtk.Misc class. The object of the gtk.Image class displays an image. Usually, the image is to be loaded from a file in a pixel buffer representing gtk.gdk.Pixbuf class. Instead a convenience function set_from_file() is commonly used to display image data from file in a gk.Image widget." }, { "code": null, "e": 112570, "s": 112485, "text": "The easiest way to create the gtk.Image object is to use the following constructor −" }, { "code": null, "e": 112589, "s": 112570, "text": "img = gtk.Image()\n" }, { "code": null, "e": 112644, "s": 112589, "text": "The following are the methods of the gtk.Image class −" }, { "code": null, "e": 112724, "s": 112644, "text": "Image.set_from_file() − This sets the image data from the contents of the file." }, { "code": null, "e": 112804, "s": 112724, "text": "Image.set_from_file() − This sets the image data from the contents of the file." }, { "code": null, "e": 112929, "s": 112804, "text": "Image.set_from_pixbuf() − This sets the image data from pixmap in which the image data is loaded for offscreen manipulation." }, { "code": null, "e": 113054, "s": 112929, "text": "Image.set_from_pixbuf() − This sets the image data from pixmap in which the image data is loaded for offscreen manipulation." }, { "code": null, "e": 113210, "s": 113054, "text": "Image.set_from_pixbuf() − This sets the image data using pixbuf which is an object containing the data that describes an image using client side resources." }, { "code": null, "e": 113366, "s": 113210, "text": "Image.set_from_pixbuf() − This sets the image data using pixbuf which is an object containing the data that describes an image using client side resources." }, { "code": null, "e": 113460, "s": 113366, "text": "Image.set_from_stock() − This sets the image data from the stock item identified by stock_id." }, { "code": null, "e": 113554, "s": 113460, "text": "Image.set_from_stock() − This sets the image data from the stock item identified by stock_id." }, { "code": null, "e": 113602, "s": 113554, "text": "Image.clear() − This removes the current image." }, { "code": null, "e": 113650, "s": 113602, "text": "Image.clear() − This removes the current image." }, { "code": null, "e": 113838, "s": 113650, "text": "Image.set_from_image() − This sets the image data from a client-side image buffer in the pixel format of the current display. If the image is None, the current image data will be removed." }, { "code": null, "e": 114026, "s": 113838, "text": "Image.set_from_image() − This sets the image data from a client-side image buffer in the pixel format of the current display. If the image is None, the current image data will be removed." }, { "code": null, "e": 114149, "s": 114026, "text": "In the following program, the gtk.Image object is obtained from an image file. It is further added in the toplevel window." }, { "code": null, "e": 114562, "s": 114149, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"PyGtk Image demo\")\n self.set_size_request(300, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n \n\t image1 = gtk.Image()\n image1.set_from_file(\"python.png\")\n self.add(image1)\n \n\t self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 114614, "s": 114562, "text": "The above code will generate the following output −" }, { "code": null, "e": 114755, "s": 114614, "text": "The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn." }, { "code": null, "e": 115110, "s": 114755, "text": "PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files." }, { "code": null, "e": 115433, "s": 115110, "text": "In order to perform different drawing operations, we must fetch the device on text of the target output object. In this case, since the drawing is appearing on gtk.DrawingArea widget, the device context of gdk.Window contained inside it is obtained. This class has a cairo-create() method which returns the device context." }, { "code": null, "e": 115491, "s": 115433, "text": "area = gtk.DrawingArea()\ndc = area.window.cairo_create()\n" }, { "code": null, "e": 115595, "s": 115491, "text": "The DrawingArea widget can be connected to the callbacks based on the following signals emitted by it −" }, { "code": null, "e": 115710, "s": 115595, "text": "The Mouse and Keyboard events can also be used to invoke callbacks by add_events() method of the gtk.Widget class." }, { "code": null, "e": 116043, "s": 115710, "text": "Of particular interest is the expose-event signal which is emitted when the DrawingArea canvas first comes up. The different methods for drawing 2D objects, that are defined in the Cairo library are called from this callback connected to the expose-event signal. These methods draw corresponding objects on the Cairo device context." }, { "code": null, "e": 116093, "s": 116043, "text": "The following are the available drawing methods −" }, { "code": null, "e": 116212, "s": 116093, "text": "dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height." }, { "code": null, "e": 116331, "s": 116212, "text": "dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height." }, { "code": null, "e": 116413, "s": 116331, "text": "dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles." }, { "code": null, "e": 116495, "s": 116413, "text": "dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles." }, { "code": null, "e": 116573, "s": 116495, "text": "dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates." }, { "code": null, "e": 116651, "s": 116573, "text": "dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates." }, { "code": null, "e": 116722, "s": 116651, "text": "dc.line_to(x,y) − This draws a line from the current position to (x,y)" }, { "code": null, "e": 116793, "s": 116722, "text": "dc.line_to(x,y) − This draws a line from the current position to (x,y)" }, { "code": null, "e": 116853, "s": 116793, "text": "dc.show_text(str) − draws string at current cursor position" }, { "code": null, "e": 116913, "s": 116853, "text": "dc.show_text(str) − draws string at current cursor position" }, { "code": null, "e": 116941, "s": 116913, "text": "dc.stroke() − draws outline" }, { "code": null, "e": 116969, "s": 116941, "text": "dc.stroke() − draws outline" }, { "code": null, "e": 117012, "s": 116969, "text": "dc.fill() − fills shape with current color" }, { "code": null, "e": 117055, "s": 117012, "text": "dc.fill() − fills shape with current color" }, { "code": null, "e": 117154, "s": 117055, "text": "dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0" }, { "code": null, "e": 117253, "s": 117154, "text": "dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0" }, { "code": null, "e": 117327, "s": 117253, "text": "The following script draws different shapes and test using Cairo methods." }, { "code": null, "e": 118557, "s": 117327, "text": "import gtk\nimport math\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"Basic shapes using Cairo\")\n self.set_size_request(400, 250)\n self.set_position(gtk.WIN_POS_CENTER)\n \n\t self.connect(\"destroy\", gtk.main_quit)\n\t\t\n darea = gtk.DrawingArea()\n darea.connect(\"expose-event\", self.expose)\n\t\t\n self.add(darea)\n self.show_all()\n\t\t\n def expose(self, widget, event):\n cr = widget.window.cairo_create()\n\t\t\n cr.set_line_width(2)\n cr.set_source_rgb(0,0,1)\n cr.rectangle(10,10,100,100)\n cr.stroke()\n\t\t\n cr.set_source_rgb(1,0,0)\n cr.rectangle(10,125,100,100)\n cr.stroke()\n\t\t\n cr.set_source_rgb(0,1,0)\n cr.rectangle(125,10,100,100)\n cr.fill()\n\t\t\n cr.set_source_rgb(0.5,0.6,0.7)\n cr.rectangle(125,125,100,100)\n cr.fill()\n\t\t\n cr.arc(300, 50, 50,0, 2*math.pi)\n cr.set_source_rgb(0.2,0.2,0.2)\n cr.fill()\n\t\t\n cr.arc(300, 200, 50, math.pi,0)\n cr.set_source_rgb(0.1,0.1,0.1)\n cr.stroke()\n\t\t\n cr.move_to(50,240)\n cr.show_text(\"Hello PyGTK\")\n cr.move_to(150,240)\n cr.line_to(400,240)\n cr.stroke()\n\nPyApp()\ngtk.main() " }, { "code": null, "e": 118611, "s": 118557, "text": "The above script will generate the following output −" }, { "code": null, "e": 119003, "s": 118611, "text": "The SpinnButton widget, often called the Spinner is a gtk.Entry widget with up and down arrows on its right. A user can type in a numeric value directly in it or increment or decrement using up and down arrows. The gtk.SpinButton class is inherited from the gtk.Entry class. It uses a gtk.Adjustment object with which the range and step of the numeric value in the spinner can be restricted." }, { "code": null, "e": 119070, "s": 119003, "text": "The SpinButton widget is created using the following constructor −" }, { "code": null, "e": 119116, "s": 119070, "text": "sp = gtk.SpinButton(adj, climb_rate, digits)\n" }, { "code": null, "e": 119267, "s": 119116, "text": "Here, adj represents the gtk.Adjustment object controlling range, climb_rate is an acceleration factor and the number of decimals specified by digits." }, { "code": null, "e": 119320, "s": 119267, "text": "The gtk.SpinButton class has the following methods −" }, { "code": null, "e": 119387, "s": 119320, "text": "SpinButton.set_adjustment() − This sets the \"adjustment\" property." }, { "code": null, "e": 119454, "s": 119387, "text": "SpinButton.set_adjustment() − This sets the \"adjustment\" property." }, { "code": null, "e": 119602, "s": 119454, "text": "SpinButton.set_digits() − This sets the \"digits\" property to the value to determine the number of decimal places to be displayed by the spinbutton." }, { "code": null, "e": 119750, "s": 119602, "text": "SpinButton.set_digits() − This sets the \"digits\" property to the value to determine the number of decimal places to be displayed by the spinbutton." }, { "code": null, "e": 119952, "s": 119750, "text": "SpinButton.set_increments(step, page) − This sets the step value which has increment applied for each left mousebutton press and page value which is increment applied for each middle mousebutton press." }, { "code": null, "e": 120154, "s": 119952, "text": "SpinButton.set_increments(step, page) − This sets the step value which has increment applied for each left mousebutton press and page value which is increment applied for each middle mousebutton press." }, { "code": null, "e": 120246, "s": 120154, "text": "SpinButton.set_range() − This sets the minimum and maximum allowable values for spinbutton." }, { "code": null, "e": 120338, "s": 120246, "text": "SpinButton.set_range() − This sets the minimum and maximum allowable values for spinbutton." }, { "code": null, "e": 120422, "s": 120338, "text": "SpinButton.set_value() − This sets the spin button to a new value programmatically." }, { "code": null, "e": 120506, "s": 120422, "text": "SpinButton.set_value() − This sets the spin button to a new value programmatically." }, { "code": null, "e": 120595, "s": 120506, "text": "SpinButton.update_policy() − The valid values are gtk.UPDATE_ALWAYS and gtk.UPDATE_VALID" }, { "code": null, "e": 120684, "s": 120595, "text": "SpinButton.update_policy() − The valid values are gtk.UPDATE_ALWAYS and gtk.UPDATE_VALID" }, { "code": null, "e": 120800, "s": 120684, "text": "SpinButton.spin(direction, increment=1) − This increments or decrements Spinner's value in the specified direction." }, { "code": null, "e": 120916, "s": 120800, "text": "SpinButton.spin(direction, increment=1) − This increments or decrements Spinner's value in the specified direction." }, { "code": null, "e": 120971, "s": 120916, "text": "The following are the predefined direction constants −" }, { "code": null, "e": 121121, "s": 120971, "text": "SpinButton.set_wrap() — If wrap is True, the spin button value wraps around to the opposite limit when the upper or lower limit of the range exceeds." }, { "code": null, "e": 121271, "s": 121121, "text": "SpinButton.set_wrap() — If wrap is True, the spin button value wraps around to the opposite limit when the upper or lower limit of the range exceeds." }, { "code": null, "e": 121327, "s": 121271, "text": "The gtk.SpinButton widget emits the following signals −" }, { "code": null, "e": 121606, "s": 121327, "text": "The following example constructs a simple Date Selector by using three SpinButton widgets. The Day Selector is applied an Adjustment object to restrict value between 1—31. The second selector is for the number of months 1—12. The third selector selects the year range 2000—2020." }, { "code": null, "e": 121625, "s": 121606, "text": "Observe the code −" }, { "code": null, "e": 122791, "s": 121625, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"SpinButton Demo\")\n self.set_size_request(300, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n self.set_border_width(20)\n\t\t\n vbox = gtk.VBox(False, 5)\n hbox = gtk.HBox(True, 3)\n lbl1 = gtk.Label(\"Date\")\n hbox.add(lbl1)\n\t\t\n adj1 = gtk.Adjustment(1.0, 1.0, 31.0, 1.0, 5.0, 0.0)\n spin1 = gtk.SpinButton(adj1, 0, 0)\n spin1.set_wrap(True)\n\t\t\n hbox.add(spin1)\n lbl2 = gtk.Label(\"Month\")\n hbox.add(lbl2)\n\t\t\n adj2 = gtk.Adjustment(1.0, 1.0, 12.0, 1.0, 5.0, 0.0)\n spin2 = gtk.SpinButton(adj2, 0, 0)\n spin2.set_wrap(True)\n\t\t\n hbox.add(spin2)\n lbl3 = gtk.Label(\"Year\")\n hbox.add(lbl3)\n\t\t\n adj3 = gtk.Adjustment(1.0, 2000.0, 2020.0, 1.0, 5.0, 0.0)\n spin3 = gtk.SpinButton(adj3, 0, 0)\n spin3.set_wrap(True)\n hbox.add(spin3)\n\t\t\n frame = gtk.Frame()\n frame.add(hbox)\n frame.set_label(\"Date of Birth\")\n\t\t\n vbox.add(frame)\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\nPyApp()\ngtk.main()" }, { "code": null, "e": 122858, "s": 122791, "text": "Upon execution, the above code will produce the following output −" }, { "code": null, "e": 123076, "s": 122858, "text": "The Calendar widget in PyGTK toolkit displays a simple calendar with one month view at a time. The navigation controls to change month and year are displayed by default. The display options can be suitably configured." }, { "code": null, "e": 123170, "s": 123076, "text": "The value of month property is between 0 to 11, and that of date property is between 1 to 31." }, { "code": null, "e": 123234, "s": 123170, "text": "There is a simple constructor to create a gtk.Calendar object −" }, { "code": null, "e": 123256, "s": 123234, "text": "cal = gtk.Calendar()\n" }, { "code": null, "e": 123341, "s": 123256, "text": "The default display style shows the current month and year as well as names of days." }, { "code": null, "e": 123392, "s": 123341, "text": "The gtk.Calendar class has the following methods −" }, { "code": null, "e": 123485, "s": 123392, "text": "Calendar.select_month(mm,yy) — This changes the calendar display to the specified mm and yy." }, { "code": null, "e": 123578, "s": 123485, "text": "Calendar.select_month(mm,yy) — This changes the calendar display to the specified mm and yy." }, { "code": null, "e": 123742, "s": 123578, "text": "Calendar.select_day(dd) — This selects the specified dd on the calendar when it has a value between 1 and 31. If dd is 0 then the current day selection is removed." }, { "code": null, "e": 123906, "s": 123742, "text": "Calendar.select_day(dd) — This selects the specified dd on the calendar when it has a value between 1 and 31. If dd is 0 then the current day selection is removed." }, { "code": null, "e": 124058, "s": 123906, "text": "Calendar.display_options() — This sets the calendar display options to the value specified by flags. The possible display options are a combination of:" }, { "code": null, "e": 124210, "s": 124058, "text": "Calendar.display_options() — This sets the calendar display options to the value specified by flags. The possible display options are a combination of:" }, { "code": null, "e": 124338, "s": 124210, "text": "Calendar.get_date() — This retrieves the calendar's current year, month and selected day numbers as a tuple (year, month, day)." }, { "code": null, "e": 124466, "s": 124338, "text": "Calendar.get_date() — This retrieves the calendar's current year, month and selected day numbers as a tuple (year, month, day)." }, { "code": null, "e": 124520, "s": 124466, "text": "The gtk.Calendar widget emits the following signals −" }, { "code": null, "e": 124621, "s": 124520, "text": "In the following example, a gtk.Calendar control and four buttons are placed in the toplevel window." }, { "code": null, "e": 124716, "s": 124621, "text": "When the 'heading' button is clicked, the Calendar's display options are set to SHOW_HEADING −" }, { "code": null, "e": 124803, "s": 124716, "text": "def heading(self, widget):\n self.cal.set_display_options(gtk.CALENDAR_SHOW_HEADING)\n" }, { "code": null, "e": 124901, "s": 124803, "text": "When the user clicks the 'day name' button, the callback sets display options to SHOW_DAY_NAMES −" }, { "code": null, "e": 124987, "s": 124901, "text": "def dayname(self, widget):\nself.cal.set_display_options(gtk.CALENDAR_SHOW_DAY_NAMES)\n" }, { "code": null, "e": 125131, "s": 124987, "text": "Both the display options are enabled when 'both' button is pressed. To begin with, all flags of display options are removed by setting it to 0." }, { "code": null, "e": 125164, "s": 125131, "text": "self.cal.set_display_options(0)\n" }, { "code": null, "e": 125241, "s": 125164, "text": "The 'set' button pops up a message box displaying the currently marked date." }, { "code": null, "e": 125418, "s": 125241, "text": "tp = self.cal.get_date()\nstr1 = str(tp[0])\nstr2 = str(tp[1]+1)\nstr3 = str(tp[2])\nlabel = gtk.Label(\"Date selected:\"+str3+\"-\"+str2+\"-\"+str1)\ndialog.vbox.add(label)\nlabel.show()\n" }, { "code": null, "e": 125447, "s": 125418, "text": "Observe the following code −" }, { "code": null, "e": 127425, "s": 125447, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Calendar Demo\")\n self.set_size_request(300, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox(False, 5)\n self.cal = gtk.Calendar()\n halign1 = gtk.Alignment(0.5, 0.5, 0, 0)\n halign1.add(self.cal)\n\t\t\n self.cal.set_display_options(0)\n valign = gtk.Alignment(0, 1, 0, 0)\n vbox.pack_start(halign1)\n\t\t\n self.btn1 = gtk.Button(\"set\")\n self.btn2 = gtk.Button(\"heading\")\n self.btn3 = gtk.Button(\"day name\")\n self.btn4 = gtk.Button(\"Both\")\n\t\t\n hbox = gtk.HBox(True, 3)\n hbox.add(self.btn1)\n hbox.add(self.btn2)\n hbox.add(self.btn3)\n hbox.add(self.btn4)\n\t\t\n halign = gtk.Alignment(0.5, 0.5, 0, 0)\n halign.add(hbox)\n\t\t\n vbox.pack_start(halign, False, True, 10)\n self.add(vbox)\n\t\t\n self.btn1.connect(\"clicked\", self.selectdate)\n self.btn2.connect(\"clicked\", self.heading)\n self.btn3.connect(\"clicked\", self.dayname)\n self.btn4.connect(\"clicked\", self.bothflags)\n\t\t\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def heading(self, widget):\n self.cal.set_display_options(gtk.CALENDAR_SHOW_HEADING)\n\t\t\n def dayname(self, widget):\n self.cal.set_display_options(gtk.CALENDAR_SHOW_DAY_NAMES)\n\t\t\n def bothflags(self, widget):\n self.cal.set_display_options(gtk.CALENDAR_SHOW_HEADING|gtk.CALENDAR_SHOW_DAY_NAMES)\n def selectdate(self, widget):\n tp = self.cal.get_date()\n dialog = gtk.Dialog(\"My dialog\",\n self,\n gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,\n (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))\n\t\t\n str1 = str(tp[0])\n str2 = str(tp[1]+1)\n str3 = str(tp[2])\n\t\t\n label = gtk.Label(\"Date selected:\"+str3+\"-\"+str2+\"-\"+str1)\n dialog.vbox.add(label)\n label.show()\n res = dialog.run()\n dialog.destroy()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 127477, "s": 127425, "text": "The above code will generate the following output −" }, { "code": null, "e": 127653, "s": 127477, "text": "A Clipboard object holds shared data between two processes or two widgets of the same application. The gtk.Clipboard is a high level interface for the gtk.SelectionData class." }, { "code": null, "e": 127717, "s": 127653, "text": "The following is a prototype of the gtk.Clipboard constructor −" }, { "code": null, "e": 127750, "s": 127717, "text": "gtk.Clipboard(display,selction)\n" }, { "code": null, "e": 128011, "s": 127750, "text": "Here, the display parameter corresponds to the gtk.gdk.Display object for which the clipboard is to be created or retrieved. By default, it is the standard output device. The selection parameter defaults to CLIPBOARD, an object representing an interned string." }, { "code": null, "e": 128093, "s": 128011, "text": "PyGTK provides a convenience function to create a clipboard object with defaults." }, { "code": null, "e": 128114, "s": 128093, "text": "gtk.clipboard.get()\n" }, { "code": null, "e": 128162, "s": 128114, "text": "gtk.Clipboard class has the following methods −" }, { "code": null, "e": 128296, "s": 128162, "text": "Clipboard.store() − This stores the current clipboard data somewhere so that it will stay around even after the application has quit." }, { "code": null, "e": 128430, "s": 128296, "text": "Clipboard.store() − This stores the current clipboard data somewhere so that it will stay around even after the application has quit." }, { "code": null, "e": 128494, "s": 128430, "text": "Clipboard.clear() − This removes the contents of the clipboard." }, { "code": null, "e": 128558, "s": 128494, "text": "Clipboard.clear() − This removes the contents of the clipboard." }, { "code": null, "e": 128640, "s": 128558, "text": "Clipboard.set_text(text) − This sets the contents of the clipboard to the string." }, { "code": null, "e": 128722, "s": 128640, "text": "Clipboard.set_text(text) − This sets the contents of the clipboard to the string." }, { "code": null, "e": 129020, "s": 128722, "text": "Clipboard.request_text() − This requests the contents of the clipboard as text. When the text is later received, callback will be called with the data specified by user_data. The signature of callback is:\n\ndef callback(clipboard, text, data) − text will contain the text retrieved from clipboard.\n" }, { "code": null, "e": 129225, "s": 129020, "text": "Clipboard.request_text() − This requests the contents of the clipboard as text. When the text is later received, callback will be called with the data specified by user_data. The signature of callback is:" }, { "code": null, "e": 129316, "s": 129225, "text": "def callback(clipboard, text, data) − text will contain the text retrieved from clipboard." }, { "code": null, "e": 129407, "s": 129316, "text": "def callback(clipboard, text, data) − text will contain the text retrieved from clipboard." }, { "code": null, "e": 129623, "s": 129407, "text": "As a demonstration of clipboard, the following code uses two TextViews and two buttons on a toplevel gtk.Window. The 'Set' button calls the on_set() function which puts the text from first textView on the clipboard." }, { "code": null, "e": 129804, "s": 129623, "text": "buf = self.tv1.get_buffer()\ntext = buf.get_text(buf.get_start_iter(), buf.get_end_iter())\nself.clipboard = gtk.clipboard_get()\nself.clipboard.set_text(text)\nself.clipboard.store()\n" }, { "code": null, "e": 129919, "s": 129804, "text": "When the second button ('retrieved') is pressed, the data from clipboard is fetched by the request_text() method −" }, { "code": null, "e": 129993, "s": 129919, "text": "self.clipboard.request_text(self.readclipboard, user_data = None)\n" }, { "code": null, "e": 130098, "s": 129993, "text": "The content of user_data goes to a callback method readclipboard() which displays it on second textview." }, { "code": null, "e": 130232, "s": 130098, "text": "def readclipboard(self, clipboard, text, data):\n buffer = gtk.TextBuffer()\n buffer.set_text(text)\n self.tv2.set_buffer(buffer)\n" }, { "code": null, "e": 130291, "s": 130232, "text": "The following is the entire code for clipboard operation −" }, { "code": null, "e": 131670, "s": 130291, "text": "import gtk\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"Clipboard demo\")\n self.set_size_request(300,200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox(False, 5)\n self.tv1 = gtk.TextView()\n\t\t\n vbox.add(self.tv1)\n self.tv2 = gtk.TextView()\n\t\t\n vbox.add(self.tv2)\n hbox = gtk.HBox(True, 3)\n\t\t\n Set = gtk.Button(\"set\")\n Set.set_size_request(70, 30)\n\t\t\n retrieve = gtk.Button(\"retrieve\")\n hbox.add(Set)\n hbox.add(retrieve)\n halign = gtk.Alignment(1, 0, 0, 0)\n halign.add(hbox)\n\t\t\n vbox.pack_start(halign, False, False, 3)\n self.add(vbox)\n Set.connect(\"clicked\", self.on_set)\n retrieve.connect(\"clicked\", self.on_retrieve)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def on_set(self, widget):\n buf = self.tv1.get_buffer()\n text = buf.get_text(buf.get_start_iter(), buf.get_end_iter())\n self.clipboard = gtk.clipboard_get()\n self.clipboard.set_text(text)\n self.clipboard.store()\n\t\t\n def on_retrieve(self, widget):\n self.clipboard.request_text(self.readclipboard, user_data=None)\n\t\t\n def readclipboard(self, clipboard, text, data):\n buffer = gtk.TextBuffer()\n buffer.set_text(text)\n self.tv2.set_buffer(buffer)\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 131722, "s": 131670, "text": "The above code will generate the following output −" }, { "code": null, "e": 131929, "s": 131722, "text": "This is a base class for horizontal (gtk.Hruler) and vertical (gtk.Vruler) rulers that are useful to show mouse pointer's position in window. A small triangle in the ruler indicates the location of pointer." }, { "code": null, "e": 131992, "s": 131929, "text": "Ruler objects are created with their respective constructors −" }, { "code": null, "e": 132035, "s": 131992, "text": "hrule = gtk.Hruler()\nvrule = gtk.Vruler()\n" }, { "code": null, "e": 132118, "s": 132035, "text": "The following gtk.Ruler class methods are available for both the derived classes −" }, { "code": null, "e": 132261, "s": 132118, "text": "Ruler.set_metric() − This sets the measurement unit. The predefined metric constants are: gtk.PIXELS (default), gtk.INCHES and gtk.CENTIMETERS" }, { "code": null, "e": 132404, "s": 132261, "text": "Ruler.set_metric() − This sets the measurement unit. The predefined metric constants are: gtk.PIXELS (default), gtk.INCHES and gtk.CENTIMETERS" }, { "code": null, "e": 132498, "s": 132404, "text": "Ruler.set_range() − This sets the lower and upper bounds, position and maximum size of ruler." }, { "code": null, "e": 132592, "s": 132498, "text": "Ruler.set_range() − This sets the lower and upper bounds, position and maximum size of ruler." }, { "code": null, "e": 132714, "s": 132592, "text": "In the example given below, the horizontal and vertical rulers are placed above and to the left of a gtk.TextView widget." }, { "code": null, "e": 132868, "s": 132714, "text": "The measurement of horizontal ruler is in pixels. Its minimum and maximum values are 0 and 400 respectively. It is placed in the upper row of a gtk.VBox." }, { "code": null, "e": 132970, "s": 132868, "text": "hrule = gtk.HRuler()\nhrule.set_metric(gtk.PIXELS)\nhrule.set_range(0, 4,0,0.5)\nvbox.pack_start(hrule)\n" }, { "code": null, "e": 133104, "s": 132970, "text": "The lower row of Vbox contains an HBox. A vertical ruler and a TextView widget, in which a multi-line text can be entered, is packed." }, { "code": null, "e": 133207, "s": 133104, "text": "vrule=gtk.VRuler()\nvrule.set_metric(gtk.PIXELS)\nvrule.set_range(0, 4, 10, 0.5)\nhbox.pack_start(vrule)\n" }, { "code": null, "e": 133236, "s": 133207, "text": "Observe the following code −" }, { "code": null, "e": 134080, "s": 133236, "text": "import gtk\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"Ruler demo\")\n self.set_size_request(400,400)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox()\n tv = gtk.TextView()\n tv.set_size_request(350,350)\n\t\t\n hrule = gtk.HRuler()\n hrule.set_metric(gtk.PIXELS)\n hrule.set_range(0, 4,0,0.5)\n\t\t\n vbox.pack_start(hrule)\n hbox = gtk.HBox()\n vrule = gtk.VRuler()\n\t\t\n vrule.set_metric(gtk.PIXELS)\n vrule.set_range(0, 4, 10, 0.5)\n\t\t\n hbox.pack_start(vrule)\n halign = gtk.Alignment(0.5, 0.5, 0, 0)\n halign.add(tv)\n\t\t\n hbox.pack_start(halign, False, True, 10)\n vbox.add(hbox)\n\t\t\n self.add(vbox)\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 134154, "s": 134080, "text": "The output generated by the above program resembles an MS Word document −" }, { "code": null, "e": 134275, "s": 134154, "text": "The gobject module of the PyGTK API has a useful function to create a timeout function that will be called periodically." }, { "code": null, "e": 134333, "s": 134275, "text": "source_id = gobject.timeout_add(interval, function, ...)\n" }, { "code": null, "e": 134548, "s": 134333, "text": "The second argument is the callback function you wish to have called after every millisecond which is the value of the first argument – interval. Additional arguments may be passed to the callback as function data." }, { "code": null, "e": 134653, "s": 134548, "text": "The return value of this function is source_id. Using it, the callback function is stopped from calling." }, { "code": null, "e": 134687, "s": 134653, "text": "gobject.source_remove(source_id)\n" }, { "code": null, "e": 134803, "s": 134687, "text": "The callback function must return True in order to keep repeating. Therefore, it can be stopped by returning False." }, { "code": null, "e": 135024, "s": 134803, "text": "Two buttons and two labels are put on a toplevel window in the following program. One label displays an incrementing number. The btn1 calls on_click which sets the timeout function with an interval of 1000 ms (1 second)." }, { "code": null, "e": 135154, "s": 135024, "text": "btn1.connect(\"clicked\", self.on_click)\n\ndef on_click(self, widget):\n self.source_id = gobject.timeout_add(1000, counter, self)\n" }, { "code": null, "e": 135256, "s": 135154, "text": "The timeout function is named as counter(). It increments the number on a label after every 1 second." }, { "code": null, "e": 135370, "s": 135256, "text": "def counter(timer):\n c=timer.count+1\n print c\n timer.count=c\n timer.lbl.set_label(str(c))\n return True\n" }, { "code": null, "e": 135434, "s": 135370, "text": "The Callback on the second button removes the timeout function." }, { "code": null, "e": 135538, "s": 135434, "text": "btn2.connect(\"clicked\", self.on_stop)\ndef on_stop(self, widget):\ngobject.source_remove(self.source_id)\n" }, { "code": null, "e": 135599, "s": 135538, "text": "The following is the complete code for the Timeout example −" }, { "code": null, "e": 136940, "s": 135599, "text": "import gtk, gobject\n\ndef counter(timer):\n c = timer.count+1\n print c\n timer.count = c\n timer.lbl.set_label(str(c))\n return True\n class PyApp(gtk.Window):\n\t\t\n def __init__(self):\n super(PyApp, self).__init__()\n self.set_title(\"Timeout Demo\")\n self.set_size_request(300, 200)\n self.set_position(gtk.WIN_POS_CENTER)\n\t\t\n vbox = gtk.VBox(False, 5)\n hbox = gtk.HBox(True, 3)\n\t\t\n hb = gtk.HBox()\n lbl1 = gtk.Label(\"Counter: \")\n\t\t\n hb.add(lbl1)\n self.lbl = gtk.Label(\"\")\n hb.add(self.lbl)\n valign = gtk.Alignment(0.5, 0.5, 0, 0)\n valign.add(hb)\n vbox.pack_start(valign, True, True, 10)\n\t\t\n btn1 = gtk.Button(\"start\")\n btn2 = gtk.Button(\"stop\")\n\t\t\n self.count = 0\n self.source_id = 0\n\t\t\n hbox.add(btn1)\n hbox.add(btn2)\n\t\t\n halign = gtk.Alignment(0.5, 0.5, 0, 0)\n halign.add(hbox)\n\t\t\n vbox.pack_start(halign, False, True, 10)\n self.add(vbox)\n\t\t\n btn1.connect(\"clicked\", self.on_click)\n btn2.connect(\"clicked\", self.on_stop)\n\t\t\n self.connect(\"destroy\", gtk.main_quit)\n self.show_all()\n\t\t\n def on_click(self, widget):\n self.source_id = gobject.timeout_add(1000, counter, self)\n\t\t\n def on_stop(self, widget):\n gobject.source_remove(self.source_id)\n\nPyApp()\ngtk.main()" }, { "code": null, "e": 137153, "s": 136940, "text": "When executed, the window shows two buttons at the bottom. The number on the label will increment periodically when the Start button is clicked on and it will stop incrementing when the Stop button is clicked on." }, { "code": null, "e": 137174, "s": 137153, "text": "Observe the output −" }, { "code": null, "e": 137469, "s": 137174, "text": "Widgets having associated X Window are capable of drag and drop. In the program, a widget as a source and/or destination for drag-and-drop must first be designated. The widget defined as source can send out the dragged data. The destination widget accepts it when dragged data is dropped on it." }, { "code": null, "e": 137554, "s": 137469, "text": "The following steps are involved in setting up a drag-and-drop enabled application −" }, { "code": null, "e": 137591, "s": 137554, "text": "Step 1 − Setting up a source widget." }, { "code": null, "e": 137679, "s": 137591, "text": "Step 2 − The drag_source_set() method specifies the target types for a drag operation −" }, { "code": null, "e": 137737, "s": 137679, "text": "widget.drag_source_set(start_button_mask, targets, info)\n" }, { "code": null, "e": 137840, "s": 137737, "text": "Step 3 − The start_button_mask argument specifies a bitmask of buttons that starts the drag operation." }, { "code": null, "e": 137909, "s": 137840, "text": "Step 4 − The target argument is a list of tuples of this structure −" }, { "code": null, "e": 137932, "s": 137909, "text": "(target, flags, info)\n" }, { "code": null, "e": 138032, "s": 137932, "text": "The target argument is a string representing drag type, for example, text/plain or image/x-xpixmap." }, { "code": null, "e": 138078, "s": 138032, "text": "Step 6 − The following flags are predefined −" }, { "code": null, "e": 138098, "s": 138078, "text": "gtk.TARGET_SAME_APP" }, { "code": null, "e": 138121, "s": 138098, "text": "gtk.TARGET_SAME_WIDGET" }, { "code": null, "e": 138183, "s": 138121, "text": "Step 7 − There will be no limitation as the flag is set to 0." }, { "code": null, "e": 138249, "s": 138183, "text": "If the widget is not required to act as source, it can be unset −" }, { "code": null, "e": 138277, "s": 138249, "text": "widget.drag_source_unset()\n" }, { "code": null, "e": 138369, "s": 138277, "text": "The source signal emits signals. The following table lists the signals and their callbacks." }, { "code": null, "e": 138445, "s": 138369, "text": "The drag_dest_set() method specifies which widget can receive dragged data." }, { "code": null, "e": 138491, "s": 138445, "text": "widget.drag_dest_set(flags, targets, action)\n" }, { "code": null, "e": 138553, "s": 138491, "text": "The flags parameter can take one of the following constants −" }, { "code": null, "e": 138710, "s": 138553, "text": "The target is a list of tuples containing target information. The actions argument is a bitmask of or a combination of one or more of the following values −" }, { "code": null, "e": 138733, "s": 138710, "text": "gtk.gdk.ACTION_DEFAULT" }, { "code": null, "e": 138753, "s": 138733, "text": "gtk.gdk.ACTION_COPY" }, { "code": null, "e": 138773, "s": 138753, "text": "gtk.gdk.ACTION_MOVE" }, { "code": null, "e": 138793, "s": 138773, "text": "gtk.gdk.ACTION_LINK" }, { "code": null, "e": 138816, "s": 138793, "text": "gtk.gdk.ACTION_PRIVATE" }, { "code": null, "e": 138835, "s": 138816, "text": "gtk.gdk.ACTION_ASK" }, { "code": null, "e": 139158, "s": 138835, "text": "The \"drag-motion\" handler must determine if the drag data is appropriate by matching the destination targets with the gtk.gdk.DragContext targets and optionally by examining the drag data by calling the drag_get_data() method. The gtk.gdk.DragContext. drag_status() method must be called to update the drag_context status." }, { "code": null, "e": 139387, "s": 139158, "text": "The \"drag-drop\" handler must determine the matching target using the drag_dest_find_target() method and then ask for the drag data using the drag_get_data() method. The data will be available in the \"drag-data-received\" handler." }, { "code": null, "e": 139394, "s": 139387, "text": " Print" }, { "code": null, "e": 139405, "s": 139394, "text": " Add Notes" } ]
Andrew Ng’s Machine Learning Course in Python (Neural Networks) | by Benjamin Lau | Towards Data Science
This article will look at both programming assignment 3 and 4 on neural networks from Andrew Ng’s Machine Learning Course. This is also the first complex non-linear algorithms we have encounter so far in the course. I do not know about you but there is definitely a steep learning curve for this assignment for me. Neural Network forms the basis of deep learning which has a widespread application such as computer vision or natural language processing. As such, it is important to get the fundamental right and coding these assignments in python is one way to ensure that. Before getting into neural networks, let’s complete the last section for logistic regression — Multi-class Logistic Regression. This series of exercise make use of a handwritten digits dataset that consists of 5000 training examples, where each example is a 20 pixel by 20 pixel grayscale image of the digit. Loading the dataset import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom scipy.io import loadmat# Use loadmat to load matlab filesmat=loadmat("ex3data1.mat")X=mat["X"]y=mat["y"] Since the dataset was given in .mat format instead of the usual .txt format, I had to make use of scipy loadmat function for the job. The official documentation can be found here. Since loadmat load .mat files as a dictionary with variable names as keys, assigning X and y is as simple as accessing the dict with the variables’ keys. X.shape, y.shape To better understand the dataset, having the shape of the data tells us the dimension of the data. X has a shape of 5000,400 which corresponds to 5000 training examples, each with 400 features from its 20 X 20 pixel. y has a shape of 5000,1 , in which each training example has a label ranging from 1 to 10 (‘0’ digit is labeled as ‘10’ in this dataset). Visualizing the data import matplotlib.image as mpimgfig, axis = plt.subplots(10,10,figsize=(8,8))for i in range(10): for j in range(10): axis[i,j].imshow(X[np.random.randint(0,5001),:].reshape(20,20,order="F"), cmap="hot") #reshape back to 20 pixel by 20 pixel axis[i,j].axis("off") The code block above construct 100 subplots and randomly visualize 100 out of the 5000 training examples using plt.imshow. Take note we have to reshape the training example back to 20 X 20 pixel before we can visualize it and adding order="F" as a parameter into the reshape function ensure that the orientation of the image is upright. Computing the cost function and gradient def sigmoid(z): """ return the sigmoid of z """ return 1/ (1 + np.exp(-z))def lrCostFunction(theta, X, y, Lambda): """ Takes in numpy array of theta, X, y, and float lambda to compute the regularized logistic cost function """ m=len(y) predictions = sigmoid(X @ theta) error = (-y * np.log(predictions)) - ((1-y)*np.log(1-predictions)) cost = 1/m * sum(error) regCost= cost + Lambda/(2*m) * sum(theta[1:]**2) # compute gradient j_0= 1/m * (X.transpose() @ (predictions - y))[0] j_1 = 1/m * (X.transpose() @ (predictions - y))[1:] + (Lambda/m)* theta[1:] grad= np.vstack((j_0[:,np.newaxis],j_1)) return regCost[0], grad This is similar to the cost function we used back in the Logistic Regression assignment. theta_t = np.array([-2,-1,1,2]).reshape(4,1)X_t =np.array([np.linspace(0.1,1.5,15)]).reshape(3,5).TX_t = np.hstack((np.ones((5,1)), X_t))y_t = np.array([1,0,1,0,1]).reshape(5,1)J, grad = lrCostFunction(theta_t, X_t, y_t, 3)print("Cost:",J,"Expected cost: 2.534819")print("Gradients:\n",grad,"\nExpected gradients:\n 0.146561\n -0.548558\n 0.724722\n 1.398003") Now for the classification task. Since we have more than one class, we will have to train multiple logistic regression classifiers using one-vs-all classification method (one classifier for each class). def gradientDescent(X,y,theta,alpha,num_iters,Lambda): """ Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration """ m=len(y) J_history =[] for i in range(num_iters): cost, grad = lrCostFunction(theta,X,y,Lambda) theta = theta - (alpha * grad) J_history.append(cost) return theta , J_historydef oneVsAll(X, y, num_labels, Lambda): """ Takes in numpy array of X,y, int num_labels and float lambda to train multiple logistic regression classifiers depending on the number of num_labels using gradient descent. Returns a matrix of theta, where the i-th row corresponds to the classifier for label i """ m, n = X.shape[0], X.shape[1] initial_theta = np.zeros((n+1,1)) all_theta = [] all_J=[] # add intercept terms X = np.hstack((np.ones((m,1)),X)) for i in range(1,num_labels+1): theta , J_history = gradientDescent(X,np.where(y==i,1,0),initial_theta,1,300,Lambda) all_theta.extend(theta) all_J.extend(J_history) return np.array(all_theta).reshape(num_labels,n+1), all_J The gradientDescent function is the usual optimizing function that we had implemented previously. As for oneVsAll , it iterates through all the classes and trained a set of theta for each class using gradient descent ( fmincg function was used in the assignment). all_theta then captures all the optimized theta in a list and return as a numpy array, reshaped into a matrix of theta where the i-th row corresponds to the classifier for label i. np.where comes in handy here to get a vector of y with 1/0 for each class to conduct our binary classification task within each iteration. Plotting of the cost function just to ensure gradient descent works as intended plt.plot(all_J[0:300])plt.xlabel("Iteration")plt.ylabel("$J(\Theta)$")plt.title("Cost function using Gradient Descent") In order to make a prediction, the probability of x(i) for each class was computed and the prediction is the class with the highest probability def predictOneVsAll(all_theta, X): """ Using all_theta, compute the probability of X(i) for each class and predict the label return a vector of prediction """ m= X.shape[0] X = np.hstack((np.ones((m,1)),X)) predictions = X @ all_theta.T return np.argmax(predictions,axis=1)+1pred = predictOneVsAll(all_theta, X)print("Training Set Accuracy:",sum(pred[:,np.newaxis]==y)[0]/5000*100,"%") The print statement print: Training Set Accuracy: 91.46 % Finally, time for neural networks. With the same dataset, we aimed to achieve higher accuracy using a more complex algorithm such as the neural network. For the first part of the exercise, the optimized theta values were given to us and we are supposed to implement feedforward propagation to obtain the prediction and model accuracy. Loading of the optimized theta mat2=loadmat("ex3weights.mat")Theta1=mat2["Theta1"] # Theta1 has size 25 x 401Theta2=mat2["Theta2"] # Theta2 has size 10 x 26 Using feedforward propagation for prediction def predict(Theta1, Theta2, X): """ Predict the label of an input given a trained neural network """ m= X.shape[0] X = np.hstack((np.ones((m,1)),X)) a1 = sigmoid(X @ Theta1.T) a1 = np.hstack((np.ones((m,1)), a1)) # hidden layer a2 = sigmoid(a1 @ Theta2.T) # output layer return np.argmax(a2,axis=1)+1pred2 = predict(Theta1, Theta2, X)print("Training Set Accuracy:",sum(pred2[:,np.newaxis]==y)[0]/5000*100,"%") The print statement print: Training Set Accuracy: 97.52 % . A much higher accuracy as compared to multi-class logistic regression! In assignment 4, we worked towards implementing a neural network from scratch. We start off by computing the cost function and gradient of theta. def sigmoidGradient(z): """ computes the gradient of the sigmoid function """ sigmoid = 1/(1 + np.exp(-z)) return sigmoid *(1-sigmoid)def nnCostFunction(nn_params,input_layer_size, hidden_layer_size, num_labels,X, y,Lambda): """ nn_params contains the parameters unrolled into a vector compute the cost and gradient of the neural network """ # Reshape nn_params back into the parameters Theta1 and Theta2 Theta1 = nn_params[:((input_layer_size+1) * hidden_layer_size)].reshape(hidden_layer_size,input_layer_size+1) Theta2 = nn_params[((input_layer_size +1)* hidden_layer_size ):].reshape(num_labels,hidden_layer_size+1) m = X.shape[0] J=0 X = np.hstack((np.ones((m,1)),X)) y10 = np.zeros((m,num_labels)) a1 = sigmoid(X @ Theta1.T) a1 = np.hstack((np.ones((m,1)), a1)) # hidden layer a2 = sigmoid(a1 @ Theta2.T) # output layer for i in range(1,num_labels+1): y10[:,i-1][:,np.newaxis] = np.where(y==i,1,0) for j in range(num_labels): J = J + sum(-y10[:,j] * np.log(a2[:,j]) - (1-y10[:,j])*np.log(1-a2[:,j])) cost = 1/m* J reg_J = cost + Lambda/(2*m) * (np.sum(Theta1[:,1:]**2) + np.sum(Theta2[:,1:]**2)) # Implement the backpropagation algorithm to compute the gradients grad1 = np.zeros((Theta1.shape)) grad2 = np.zeros((Theta2.shape)) for i in range(m): xi= X[i,:] # 1 X 401 a1i = a1[i,:] # 1 X 26 a2i =a2[i,:] # 1 X 10 d2 = a2i - y10[i,:] d1 = Theta2.T @ d2.T * sigmoidGradient(np.hstack((1,xi @ Theta1.T))) grad1= grad1 + d1[1:][:,np.newaxis] @ xi[:,np.newaxis].T grad2 = grad2 + d2.T[:,np.newaxis] @ a1i[:,np.newaxis].T grad1 = 1/m * grad1 grad2 = 1/m*grad2 grad1_reg = grad1 + (Lambda/m) * np.hstack((np.zeros((Theta1.shape[0],1)),Theta1[:,1:])) grad2_reg = grad2 + (Lambda/m) * np.hstack((np.zeros((Theta2.shape[0],1)),Theta2[:,1:])) return cost, grad1, grad2,reg_J, grad1_reg,grad2_reg The assignment walks through the whole process step by step, computing the cost first, followed by regularized cost, gradient, and finally regularized gradient. If you want to follow along, I modified the code such that it returns values for the intermediary steps as long as you use the right indexing. input_layer_size = 400hidden_layer_size = 25num_labels = 10nn_params = np.append(Theta1.flatten(),Theta2.flatten())J,reg_J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, 1)[0:4:3]print("Cost at parameters (non-regularized):",J,"\nCost at parameters (Regularized):",reg_J) flatten() function here collapsed the array into one dimension and np.append “unroll” the parameters into a vector. The issue of symmetry for initial theta was discussed in the lecture. To break off such symmetry, random initialization is needed. def randInitializeWeights(L_in, L_out): """ randomly initializes the weights of a layer with L_in incoming connections and L_out outgoing connections. """ epi = (6**1/2) / (L_in + L_out)**1/2 W = np.random.rand(L_out,L_in +1) *(2*epi) -epi return Winitial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size)initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels)initial_nn_params = np.append(initial_Theta1.flatten(),initial_Theta2.flatten()) Finally, it's our turn to optimize the theta values using feedforward propagation and backpropagation. The optimizing algorithm I am using is once again the same old gradient descent. def gradientDescentnn(X,y,initial_nn_params,alpha,num_iters,Lambda,input_layer_size, hidden_layer_size, num_labels): """ Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration """ Theta1 = initial_nn_params[:((input_layer_size+1) * hidden_layer_size)].reshape(hidden_layer_size,input_layer_size+1) Theta2 = initial_nn_params[((input_layer_size +1)* hidden_layer_size ):].reshape(num_labels,hidden_layer_size+1) m=len(y) J_history =[] for i in range(num_iters): nn_params = np.append(Theta1.flatten(),Theta2.flatten()) cost, grad1, grad2 = nnCostFunction(nn_params,input_layer_size, hidden_layer_size, num_labels,X, y,Lambda)[3:] Theta1 = Theta1 - (alpha * grad1) Theta2 = Theta2 - (alpha * grad2) J_history.append(cost) nn_paramsFinal = np.append(Theta1.flatten(),Theta2.flatten()) return nn_paramsFinal , J_historynnTheta, nnJ_history = gradientDescentnn(X,y,initial_nn_params,0.8,800,1,input_layer_size, hidden_layer_size, num_labels)Theta1 = nnTheta[:((input_layer_size+1) * hidden_layer_size)].reshape(hidden_layer_size,input_layer_size+1)Theta2 = nnTheta[((input_layer_size +1)* hidden_layer_size ):].reshape(num_labels,hidden_layer_size+1) A warning to those executing the code. It will take a fair bit of time to compute depending on your computing power, and even longer if you are optimizing your alpha and num_iters values. I use 0.8 for alpha and 800 for num_iters but I believe it can get better accuracy with more tunning. pred3 = predict(Theta1, Theta2, X)print("Training Set Accuracy:",sum(pred3[:,np.newaxis]==y)[0]/5000*100,"%") With this, I am halfway through the series. The Jupyter notebook will be uploaded to my GitHub at (https://github.com/Benlau93/Machine-Learning-by-Andrew-Ng-in-Python). For other python implementation in the series, Linear Regression Logistic Regression Regularized Logistic Regression Support Vector Machines Unsupervised Learning Anomaly Detection Thank you for reading.
[ { "code": null, "e": 746, "s": 172, "text": "This article will look at both programming assignment 3 and 4 on neural networks from Andrew Ng’s Machine Learning Course. This is also the first complex non-linear algorithms we have encounter so far in the course. I do not know about you but there is definitely a steep learning curve for this assignment for me. Neural Network forms the basis of deep learning which has a widespread application such as computer vision or natural language processing. As such, it is important to get the fundamental right and coding these assignments in python is one way to ensure that." }, { "code": null, "e": 874, "s": 746, "text": "Before getting into neural networks, let’s complete the last section for logistic regression — Multi-class Logistic Regression." }, { "code": null, "e": 1055, "s": 874, "text": "This series of exercise make use of a handwritten digits dataset that consists of 5000 training examples, where each example is a 20 pixel by 20 pixel grayscale image of the digit." }, { "code": null, "e": 1075, "s": 1055, "text": "Loading the dataset" }, { "code": null, "e": 1253, "s": 1075, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom scipy.io import loadmat# Use loadmat to load matlab filesmat=loadmat(\"ex3data1.mat\")X=mat[\"X\"]y=mat[\"y\"]" }, { "code": null, "e": 1587, "s": 1253, "text": "Since the dataset was given in .mat format instead of the usual .txt format, I had to make use of scipy loadmat function for the job. The official documentation can be found here. Since loadmat load .mat files as a dictionary with variable names as keys, assigning X and y is as simple as accessing the dict with the variables’ keys." }, { "code": null, "e": 1604, "s": 1587, "text": "X.shape, y.shape" }, { "code": null, "e": 1959, "s": 1604, "text": "To better understand the dataset, having the shape of the data tells us the dimension of the data. X has a shape of 5000,400 which corresponds to 5000 training examples, each with 400 features from its 20 X 20 pixel. y has a shape of 5000,1 , in which each training example has a label ranging from 1 to 10 (‘0’ digit is labeled as ‘10’ in this dataset)." }, { "code": null, "e": 1980, "s": 1959, "text": "Visualizing the data" }, { "code": null, "e": 2260, "s": 1980, "text": "import matplotlib.image as mpimgfig, axis = plt.subplots(10,10,figsize=(8,8))for i in range(10): for j in range(10): axis[i,j].imshow(X[np.random.randint(0,5001),:].reshape(20,20,order=\"F\"), cmap=\"hot\") #reshape back to 20 pixel by 20 pixel axis[i,j].axis(\"off\")" }, { "code": null, "e": 2597, "s": 2260, "text": "The code block above construct 100 subplots and randomly visualize 100 out of the 5000 training examples using plt.imshow. Take note we have to reshape the training example back to 20 X 20 pixel before we can visualize it and adding order=\"F\" as a parameter into the reshape function ensure that the orientation of the image is upright." }, { "code": null, "e": 2638, "s": 2597, "text": "Computing the cost function and gradient" }, { "code": null, "e": 3321, "s": 2638, "text": "def sigmoid(z): \"\"\" return the sigmoid of z \"\"\" return 1/ (1 + np.exp(-z))def lrCostFunction(theta, X, y, Lambda): \"\"\" Takes in numpy array of theta, X, y, and float lambda to compute the regularized logistic cost function \"\"\" m=len(y) predictions = sigmoid(X @ theta) error = (-y * np.log(predictions)) - ((1-y)*np.log(1-predictions)) cost = 1/m * sum(error) regCost= cost + Lambda/(2*m) * sum(theta[1:]**2) # compute gradient j_0= 1/m * (X.transpose() @ (predictions - y))[0] j_1 = 1/m * (X.transpose() @ (predictions - y))[1:] + (Lambda/m)* theta[1:] grad= np.vstack((j_0[:,np.newaxis],j_1)) return regCost[0], grad" }, { "code": null, "e": 3410, "s": 3321, "text": "This is similar to the cost function we used back in the Logistic Regression assignment." }, { "code": null, "e": 3771, "s": 3410, "text": "theta_t = np.array([-2,-1,1,2]).reshape(4,1)X_t =np.array([np.linspace(0.1,1.5,15)]).reshape(3,5).TX_t = np.hstack((np.ones((5,1)), X_t))y_t = np.array([1,0,1,0,1]).reshape(5,1)J, grad = lrCostFunction(theta_t, X_t, y_t, 3)print(\"Cost:\",J,\"Expected cost: 2.534819\")print(\"Gradients:\\n\",grad,\"\\nExpected gradients:\\n 0.146561\\n -0.548558\\n 0.724722\\n 1.398003\")" }, { "code": null, "e": 3974, "s": 3771, "text": "Now for the classification task. Since we have more than one class, we will have to train multiple logistic regression classifiers using one-vs-all classification method (one classifier for each class)." }, { "code": null, "e": 5208, "s": 3974, "text": "def gradientDescent(X,y,theta,alpha,num_iters,Lambda): \"\"\" Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration \"\"\" m=len(y) J_history =[] for i in range(num_iters): cost, grad = lrCostFunction(theta,X,y,Lambda) theta = theta - (alpha * grad) J_history.append(cost) return theta , J_historydef oneVsAll(X, y, num_labels, Lambda): \"\"\" Takes in numpy array of X,y, int num_labels and float lambda to train multiple logistic regression classifiers depending on the number of num_labels using gradient descent. Returns a matrix of theta, where the i-th row corresponds to the classifier for label i \"\"\" m, n = X.shape[0], X.shape[1] initial_theta = np.zeros((n+1,1)) all_theta = [] all_J=[] # add intercept terms X = np.hstack((np.ones((m,1)),X)) for i in range(1,num_labels+1): theta , J_history = gradientDescent(X,np.where(y==i,1,0),initial_theta,1,300,Lambda) all_theta.extend(theta) all_J.extend(J_history) return np.array(all_theta).reshape(num_labels,n+1), all_J" }, { "code": null, "e": 5792, "s": 5208, "text": "The gradientDescent function is the usual optimizing function that we had implemented previously. As for oneVsAll , it iterates through all the classes and trained a set of theta for each class using gradient descent ( fmincg function was used in the assignment). all_theta then captures all the optimized theta in a list and return as a numpy array, reshaped into a matrix of theta where the i-th row corresponds to the classifier for label i. np.where comes in handy here to get a vector of y with 1/0 for each class to conduct our binary classification task within each iteration." }, { "code": null, "e": 5872, "s": 5792, "text": "Plotting of the cost function just to ensure gradient descent works as intended" }, { "code": null, "e": 5992, "s": 5872, "text": "plt.plot(all_J[0:300])plt.xlabel(\"Iteration\")plt.ylabel(\"$J(\\Theta)$\")plt.title(\"Cost function using Gradient Descent\")" }, { "code": null, "e": 6136, "s": 5992, "text": "In order to make a prediction, the probability of x(i) for each class was computed and the prediction is the class with the highest probability" }, { "code": null, "e": 6554, "s": 6136, "text": "def predictOneVsAll(all_theta, X): \"\"\" Using all_theta, compute the probability of X(i) for each class and predict the label return a vector of prediction \"\"\" m= X.shape[0] X = np.hstack((np.ones((m,1)),X)) predictions = X @ all_theta.T return np.argmax(predictions,axis=1)+1pred = predictOneVsAll(all_theta, X)print(\"Training Set Accuracy:\",sum(pred[:,np.newaxis]==y)[0]/5000*100,\"%\")" }, { "code": null, "e": 6612, "s": 6554, "text": "The print statement print: Training Set Accuracy: 91.46 %" }, { "code": null, "e": 6947, "s": 6612, "text": "Finally, time for neural networks. With the same dataset, we aimed to achieve higher accuracy using a more complex algorithm such as the neural network. For the first part of the exercise, the optimized theta values were given to us and we are supposed to implement feedforward propagation to obtain the prediction and model accuracy." }, { "code": null, "e": 6978, "s": 6947, "text": "Loading of the optimized theta" }, { "code": null, "e": 7104, "s": 6978, "text": "mat2=loadmat(\"ex3weights.mat\")Theta1=mat2[\"Theta1\"] # Theta1 has size 25 x 401Theta2=mat2[\"Theta2\"] # Theta2 has size 10 x 26" }, { "code": null, "e": 7149, "s": 7104, "text": "Using feedforward propagation for prediction" }, { "code": null, "e": 7594, "s": 7149, "text": "def predict(Theta1, Theta2, X): \"\"\" Predict the label of an input given a trained neural network \"\"\" m= X.shape[0] X = np.hstack((np.ones((m,1)),X)) a1 = sigmoid(X @ Theta1.T) a1 = np.hstack((np.ones((m,1)), a1)) # hidden layer a2 = sigmoid(a1 @ Theta2.T) # output layer return np.argmax(a2,axis=1)+1pred2 = predict(Theta1, Theta2, X)print(\"Training Set Accuracy:\",sum(pred2[:,np.newaxis]==y)[0]/5000*100,\"%\")" }, { "code": null, "e": 7725, "s": 7594, "text": "The print statement print: Training Set Accuracy: 97.52 % . A much higher accuracy as compared to multi-class logistic regression!" }, { "code": null, "e": 7871, "s": 7725, "text": "In assignment 4, we worked towards implementing a neural network from scratch. We start off by computing the cost function and gradient of theta." }, { "code": null, "e": 9874, "s": 7871, "text": "def sigmoidGradient(z): \"\"\" computes the gradient of the sigmoid function \"\"\" sigmoid = 1/(1 + np.exp(-z)) return sigmoid *(1-sigmoid)def nnCostFunction(nn_params,input_layer_size, hidden_layer_size, num_labels,X, y,Lambda): \"\"\" nn_params contains the parameters unrolled into a vector compute the cost and gradient of the neural network \"\"\" # Reshape nn_params back into the parameters Theta1 and Theta2 Theta1 = nn_params[:((input_layer_size+1) * hidden_layer_size)].reshape(hidden_layer_size,input_layer_size+1) Theta2 = nn_params[((input_layer_size +1)* hidden_layer_size ):].reshape(num_labels,hidden_layer_size+1) m = X.shape[0] J=0 X = np.hstack((np.ones((m,1)),X)) y10 = np.zeros((m,num_labels)) a1 = sigmoid(X @ Theta1.T) a1 = np.hstack((np.ones((m,1)), a1)) # hidden layer a2 = sigmoid(a1 @ Theta2.T) # output layer for i in range(1,num_labels+1): y10[:,i-1][:,np.newaxis] = np.where(y==i,1,0) for j in range(num_labels): J = J + sum(-y10[:,j] * np.log(a2[:,j]) - (1-y10[:,j])*np.log(1-a2[:,j])) cost = 1/m* J reg_J = cost + Lambda/(2*m) * (np.sum(Theta1[:,1:]**2) + np.sum(Theta2[:,1:]**2)) # Implement the backpropagation algorithm to compute the gradients grad1 = np.zeros((Theta1.shape)) grad2 = np.zeros((Theta2.shape)) for i in range(m): xi= X[i,:] # 1 X 401 a1i = a1[i,:] # 1 X 26 a2i =a2[i,:] # 1 X 10 d2 = a2i - y10[i,:] d1 = Theta2.T @ d2.T * sigmoidGradient(np.hstack((1,xi @ Theta1.T))) grad1= grad1 + d1[1:][:,np.newaxis] @ xi[:,np.newaxis].T grad2 = grad2 + d2.T[:,np.newaxis] @ a1i[:,np.newaxis].T grad1 = 1/m * grad1 grad2 = 1/m*grad2 grad1_reg = grad1 + (Lambda/m) * np.hstack((np.zeros((Theta1.shape[0],1)),Theta1[:,1:])) grad2_reg = grad2 + (Lambda/m) * np.hstack((np.zeros((Theta2.shape[0],1)),Theta2[:,1:])) return cost, grad1, grad2,reg_J, grad1_reg,grad2_reg" }, { "code": null, "e": 10178, "s": 9874, "text": "The assignment walks through the whole process step by step, computing the cost first, followed by regularized cost, gradient, and finally regularized gradient. If you want to follow along, I modified the code such that it returns values for the intermediary steps as long as you use the right indexing." }, { "code": null, "e": 10487, "s": 10178, "text": "input_layer_size = 400hidden_layer_size = 25num_labels = 10nn_params = np.append(Theta1.flatten(),Theta2.flatten())J,reg_J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, 1)[0:4:3]print(\"Cost at parameters (non-regularized):\",J,\"\\nCost at parameters (Regularized):\",reg_J)" }, { "code": null, "e": 10603, "s": 10487, "text": "flatten() function here collapsed the array into one dimension and np.append “unroll” the parameters into a vector." }, { "code": null, "e": 10734, "s": 10603, "text": "The issue of symmetry for initial theta was discussed in the lecture. To break off such symmetry, random initialization is needed." }, { "code": null, "e": 11237, "s": 10734, "text": "def randInitializeWeights(L_in, L_out): \"\"\" randomly initializes the weights of a layer with L_in incoming connections and L_out outgoing connections. \"\"\" epi = (6**1/2) / (L_in + L_out)**1/2 W = np.random.rand(L_out,L_in +1) *(2*epi) -epi return Winitial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size)initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels)initial_nn_params = np.append(initial_Theta1.flatten(),initial_Theta2.flatten())" }, { "code": null, "e": 11421, "s": 11237, "text": "Finally, it's our turn to optimize the theta values using feedforward propagation and backpropagation. The optimizing algorithm I am using is once again the same old gradient descent." }, { "code": null, "e": 12783, "s": 11421, "text": "def gradientDescentnn(X,y,initial_nn_params,alpha,num_iters,Lambda,input_layer_size, hidden_layer_size, num_labels): \"\"\" Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration \"\"\" Theta1 = initial_nn_params[:((input_layer_size+1) * hidden_layer_size)].reshape(hidden_layer_size,input_layer_size+1) Theta2 = initial_nn_params[((input_layer_size +1)* hidden_layer_size ):].reshape(num_labels,hidden_layer_size+1) m=len(y) J_history =[] for i in range(num_iters): nn_params = np.append(Theta1.flatten(),Theta2.flatten()) cost, grad1, grad2 = nnCostFunction(nn_params,input_layer_size, hidden_layer_size, num_labels,X, y,Lambda)[3:] Theta1 = Theta1 - (alpha * grad1) Theta2 = Theta2 - (alpha * grad2) J_history.append(cost) nn_paramsFinal = np.append(Theta1.flatten(),Theta2.flatten()) return nn_paramsFinal , J_historynnTheta, nnJ_history = gradientDescentnn(X,y,initial_nn_params,0.8,800,1,input_layer_size, hidden_layer_size, num_labels)Theta1 = nnTheta[:((input_layer_size+1) * hidden_layer_size)].reshape(hidden_layer_size,input_layer_size+1)Theta2 = nnTheta[((input_layer_size +1)* hidden_layer_size ):].reshape(num_labels,hidden_layer_size+1)" }, { "code": null, "e": 13073, "s": 12783, "text": "A warning to those executing the code. It will take a fair bit of time to compute depending on your computing power, and even longer if you are optimizing your alpha and num_iters values. I use 0.8 for alpha and 800 for num_iters but I believe it can get better accuracy with more tunning." }, { "code": null, "e": 13183, "s": 13073, "text": "pred3 = predict(Theta1, Theta2, X)print(\"Training Set Accuracy:\",sum(pred3[:,np.newaxis]==y)[0]/5000*100,\"%\")" }, { "code": null, "e": 13352, "s": 13183, "text": "With this, I am halfway through the series. The Jupyter notebook will be uploaded to my GitHub at (https://github.com/Benlau93/Machine-Learning-by-Andrew-Ng-in-Python)." }, { "code": null, "e": 13399, "s": 13352, "text": "For other python implementation in the series," }, { "code": null, "e": 13417, "s": 13399, "text": "Linear Regression" }, { "code": null, "e": 13437, "s": 13417, "text": "Logistic Regression" }, { "code": null, "e": 13469, "s": 13437, "text": "Regularized Logistic Regression" }, { "code": null, "e": 13493, "s": 13469, "text": "Support Vector Machines" }, { "code": null, "e": 13515, "s": 13493, "text": "Unsupervised Learning" }, { "code": null, "e": 13533, "s": 13515, "text": "Anomaly Detection" } ]
What’s new in YOLO v3?. A review of the YOLO v3 object... | by Ayoosh Kathuria | Towards Data Science
You only look once, or YOLO, is one of the faster object detection algorithms out there. Though it is no longer the most accurate object detection algorithm, it is a very good choice when you need real-time detection, without loss of too much accuracy. A few weeks back, the third version of YOLO came out, and this post aims at explaining the changes introduced in YOLO v3. This is not going to be a post explaining what YOLO is from the ground up. I assume you know how YOLO v2 works. If that is not the case, I recommend you to check out the following papers by Joseph Redmon et all, to get a hang of how YOLO works. YOLO v1YOLO v2A nice blog post on YOLO YOLO v1 YOLO v2 A nice blog post on YOLO The official title of YOLO v2 paper seemed if YOLO was a milk-based health drink for kids rather than a object detection algorithm. It was named “YOLO9000: Better, Faster, Stronger”. For it’s time YOLO 9000 was the fastest, and also one of the most accurate algorithm. However, a couple of years down the line and it’s no longer the most accurate with algorithms like RetinaNet, and SSD outperforming it in terms of accuracy. It still, however, was one of the fastest. But that speed has been traded off for boosts in accuracy in YOLO v3. While the earlier variant ran on 45 FPS on a Titan X, the current version clocks about 30 FPS. This has to do with the increase in complexity of underlying architecture called Darknet. YOLO v2 used a custom deep architecture darknet-19, an originally 19-layer network supplemented with 11 more layers for object detection. With a 30-layer architecture, YOLO v2 often struggled with small object detections. This was attributed to loss of fine-grained features as the layers downsampled the input. To remedy this, YOLO v2 used an identity mapping, concatenating feature maps from from a previous layer to capture low level features. However, YOLO v2’s architecture was still lacking some of the most important elements that are now staple in most of state-of-the art algorithms. No residual blocks, no skip connections and no upsampling. YOLO v3 incorporates all of these. First, YOLO v3 uses a variant of Darknet, which originally has 53 layer network trained on Imagenet. For the task of detection, 53 more layers are stacked onto it, giving us a 106 layer fully convolutional underlying architecture for YOLO v3. This is the reason behind the slowness of YOLO v3 compared to YOLO v2. Here is how the architecture of YOLO now looks like. The newer architecture boasts of residual skip connections, and upsampling. The most salient feature of v3 is that it makes detections at three different scales. YOLO is a fully convolutional network and its eventual output is generated by applying a 1 x 1 kernel on a feature map. In YOLO v3, the detection is done by applying 1 x 1 detection kernels on feature maps of three different sizes at three different places in the network. The shape of the detection kernel is 1 x 1 x (B x (5 + C) ). Here B is the number of bounding boxes a cell on the feature map can predict, “5” is for the 4 bounding box attributes and one object confidence, and C is the number of classes. In YOLO v3 trained on COCO, B = 3 and C = 80, so the kernel size is 1 x 1 x 255. The feature map produced by this kernel has identical height and width of the previous feature map, and has detection attributes along the depth as described above. Before we go further, I’d like to point out that stride of the network, or a layer is defined as the ratio by which it downsamples the input. In the following examples, I will assume we have an input image of size 416 x 416. YOLO v3 makes prediction at three scales, which are precisely given by downsampling the dimensions of the input image by 32, 16 and 8 respectively. The first detection is made by the 82nd layer. For the first 81 layers, the image is down sampled by the network, such that the 81st layer has a stride of 32. If we have an image of 416 x 416, the resultant feature map would be of size 13 x 13. One detection is made here using the 1 x 1 detection kernel, giving us a detection feature map of 13 x 13 x 255. Then, the feature map from layer 79 is subjected to a few convolutional layers before being up sampled by 2x to dimensions of 26 x 26. This feature map is then depth concatenated with the feature map from layer 61. Then the combined feature maps is again subjected a few 1 x 1 convolutional layers to fuse the features from the earlier layer (61). Then, the second detection is made by the 94th layer, yielding a detection feature map of 26 x 26 x 255. A similar procedure is followed again, where the feature map from layer 91 is subjected to few convolutional layers before being depth concatenated with a feature map from layer 36. Like before, a few 1 x 1 convolutional layers follow to fuse the information from the previous layer (36). We make the final of the 3 at 106th layer, yielding feature map of size 52 x 52 x 255. Detections at different layers helps address the issue of detecting small objects, a frequent complaint with YOLO v2. The upsampled layers concatenated with the previous layers help preserve the fine grained features which help in detecting small objects. The 13 x 13 layer is responsible for detecting large objects, whereas the 52 x 52 layer detects the smaller objects, with the 26 x 26 layer detecting medium objects. Here is a comparative analysis of different objects picked in the same object by different layers. YOLO v3, in total uses 9 anchor boxes. Three for each scale. If you’re training YOLO on your own dataset, you should go about using K-Means clustering to generate 9 anchors. Then, arrange the anchors is descending order of a dimension. Assign the three biggest anchors for the first scale , the next three for the second scale, and the last three for the third. For an input image of same size, YOLO v3 predicts more bounding boxes than YOLO v2. For instance, at it’s native resolution of 416 x 416, YOLO v2 predicted 13 x 13 x 5 = 845 boxes. At each grid cell, 5 boxes were detected using 5 anchors. On the other hand YOLO v3 predicts boxes at 3 different scales. For the same image of 416 x 416, the number of predicted boxes are 10,647. This means that YOLO v3 predicts 10x the number of boxes predicted by YOLO v2. You could easily imagine why it’s slower than YOLO v2. At each scale, every grid can predict 3 boxes using 3 anchors. Since there are three scales, the number of anchor boxes used in total are 9, 3 for each scale. Earlier, YOLO v2’s loss function looked like this. I know this is intimidating, but notice the last three terms. Of them, the first one penalizes the objectness score prediction for bounding boxes responsible for predicting objects (the scores for these should ideally be 1), the second one for bounding boxes having no objects, (the scores should ideally be zero), and the last one penalises the class prediction for the bounding box which predicts the objects. The last three terms in YOLO v2 are the squared errors, whereas in YOLO v3, they’ve been replaced by cross-entropy error terms. In other words, object confidence and class predictions in YOLO v3 are now predicted through logistic regression. While we are training the detector, for each ground truth box, we assign a bounding box, whose anchor has the maximum overlap with the ground truth box. YOLO v3 now performs multilabel classification for objects detected in images. Earlier in YOLO, authors used to softmax the class scores and take the class with maximum score to be the class of the object contained in the bounding box. This has been modified in YOLO v3. Softmaxing classes rests on the assumption that classes are mutually exclusive, or in simple words, if an object belongs to one class, then it cannot belong to the other. This works fine in COCO dataset. However, when we have classes like Person and Women in a dataset, then the above assumption fails. This is the reason why the authors of YOLO have refrained from softmaxing the classes. Instead, each class score is predicted using logistic regression and a threshold is used to predict multiple labels for an object. Classes with scores higher than this threshold are assigned to the box. YOLO v3 performs at par with other state of art detectors like RetinaNet, while being considerably faster, at COCO mAP 50 benchmark. It is also better than SSD and it’s variants. Here’s a comparison of performances right from the paper. But, but and but, YOLO looses out on COCO benchmarks with a higher value of IoU used to reject a detection. I’m not going to explain how the COCO benchmark works as it’s beyond the scope of the work, but the 50 in COCO 50 benchmark is a measure of how well do the predicted bounding boxes align the the ground truth boxes of the object. 50 here corresponds to 0.5 IoU. If the IoU between the prediction and the ground truth box is less than 0.5, the prediction is classified as a mislocalisation and marked a false positive. In benchmarks, where this number is higher (say, COCO 75), the boxes need to be aligned more perfectly to be not rejected by the evaluation metric. Here is where YOLO is outdone by RetinaNet, as it’s bounding boxes are not aligned as well as of RetinaNet. Here’s a detailed table for a wider variety of benchmarks. You can run the detector on either images or video by using the code provided in this Github repo. The code requires PyTorch 0.3+, OpenCV 3 and Python 3.5. Setup the repo, and you can run various experiments on it. Here is a look at what the different detection layers pick up. python detect.py --scales 1 --images imgs/img3.jpg python detect.py --scales 2 --images imgs/img3.jpg python detect.py --scales 3 --images imgs/img3.jpg python detect.py --reso 320 --images imgs/imgs4.jpg python detect.py --reso 416 --images imgs/imgs4.jpg python detect.py --reso 608 --images imgs/imgs4.jpg python detect.py --reso 960 --images imgs/imgs4.jpg Larger input resolutions don’t help much in our case, but they might help in detection of images with small objects. On the other hand, larger input resolutions add to inference time. This is a hyper parameter that needs to be tuned depending upon application. You can experiment with other metrics such as batch size, objectness confidence, and NMS threshold by going to the repo. Everything has been mentioned in the ReadMe file. If you want to implement a YOLO v3 detector by yourself in PyTorch, here’s a series of tutorials I wrote to do the same over at Paperspace. Now, I’d expect you to have basic familiarity with PyTorch if you wanna have a go at this tutorial. If you’re someone who’s looking from moving from a beginner PyTorch user to an intermediate one, this tutorial is just about right. YOLO v3: An incremental improvementHow is mAP calculated? YOLO v3: An incremental improvement How is mAP calculated?
[ { "code": null, "e": 425, "s": 172, "text": "You only look once, or YOLO, is one of the faster object detection algorithms out there. Though it is no longer the most accurate object detection algorithm, it is a very good choice when you need real-time detection, without loss of too much accuracy." }, { "code": null, "e": 792, "s": 425, "text": "A few weeks back, the third version of YOLO came out, and this post aims at explaining the changes introduced in YOLO v3. This is not going to be a post explaining what YOLO is from the ground up. I assume you know how YOLO v2 works. If that is not the case, I recommend you to check out the following papers by Joseph Redmon et all, to get a hang of how YOLO works." }, { "code": null, "e": 831, "s": 792, "text": "YOLO v1YOLO v2A nice blog post on YOLO" }, { "code": null, "e": 839, "s": 831, "text": "YOLO v1" }, { "code": null, "e": 847, "s": 839, "text": "YOLO v2" }, { "code": null, "e": 872, "s": 847, "text": "A nice blog post on YOLO" }, { "code": null, "e": 1055, "s": 872, "text": "The official title of YOLO v2 paper seemed if YOLO was a milk-based health drink for kids rather than a object detection algorithm. It was named “YOLO9000: Better, Faster, Stronger”." }, { "code": null, "e": 1341, "s": 1055, "text": "For it’s time YOLO 9000 was the fastest, and also one of the most accurate algorithm. However, a couple of years down the line and it’s no longer the most accurate with algorithms like RetinaNet, and SSD outperforming it in terms of accuracy. It still, however, was one of the fastest." }, { "code": null, "e": 1596, "s": 1341, "text": "But that speed has been traded off for boosts in accuracy in YOLO v3. While the earlier variant ran on 45 FPS on a Titan X, the current version clocks about 30 FPS. This has to do with the increase in complexity of underlying architecture called Darknet." }, { "code": null, "e": 2043, "s": 1596, "text": "YOLO v2 used a custom deep architecture darknet-19, an originally 19-layer network supplemented with 11 more layers for object detection. With a 30-layer architecture, YOLO v2 often struggled with small object detections. This was attributed to loss of fine-grained features as the layers downsampled the input. To remedy this, YOLO v2 used an identity mapping, concatenating feature maps from from a previous layer to capture low level features." }, { "code": null, "e": 2283, "s": 2043, "text": "However, YOLO v2’s architecture was still lacking some of the most important elements that are now staple in most of state-of-the art algorithms. No residual blocks, no skip connections and no upsampling. YOLO v3 incorporates all of these." }, { "code": null, "e": 2650, "s": 2283, "text": "First, YOLO v3 uses a variant of Darknet, which originally has 53 layer network trained on Imagenet. For the task of detection, 53 more layers are stacked onto it, giving us a 106 layer fully convolutional underlying architecture for YOLO v3. This is the reason behind the slowness of YOLO v3 compared to YOLO v2. Here is how the architecture of YOLO now looks like." }, { "code": null, "e": 3085, "s": 2650, "text": "The newer architecture boasts of residual skip connections, and upsampling. The most salient feature of v3 is that it makes detections at three different scales. YOLO is a fully convolutional network and its eventual output is generated by applying a 1 x 1 kernel on a feature map. In YOLO v3, the detection is done by applying 1 x 1 detection kernels on feature maps of three different sizes at three different places in the network." }, { "code": null, "e": 3570, "s": 3085, "text": "The shape of the detection kernel is 1 x 1 x (B x (5 + C) ). Here B is the number of bounding boxes a cell on the feature map can predict, “5” is for the 4 bounding box attributes and one object confidence, and C is the number of classes. In YOLO v3 trained on COCO, B = 3 and C = 80, so the kernel size is 1 x 1 x 255. The feature map produced by this kernel has identical height and width of the previous feature map, and has detection attributes along the depth as described above." }, { "code": null, "e": 3795, "s": 3570, "text": "Before we go further, I’d like to point out that stride of the network, or a layer is defined as the ratio by which it downsamples the input. In the following examples, I will assume we have an input image of size 416 x 416." }, { "code": null, "e": 3943, "s": 3795, "text": "YOLO v3 makes prediction at three scales, which are precisely given by downsampling the dimensions of the input image by 32, 16 and 8 respectively." }, { "code": null, "e": 4301, "s": 3943, "text": "The first detection is made by the 82nd layer. For the first 81 layers, the image is down sampled by the network, such that the 81st layer has a stride of 32. If we have an image of 416 x 416, the resultant feature map would be of size 13 x 13. One detection is made here using the 1 x 1 detection kernel, giving us a detection feature map of 13 x 13 x 255." }, { "code": null, "e": 4754, "s": 4301, "text": "Then, the feature map from layer 79 is subjected to a few convolutional layers before being up sampled by 2x to dimensions of 26 x 26. This feature map is then depth concatenated with the feature map from layer 61. Then the combined feature maps is again subjected a few 1 x 1 convolutional layers to fuse the features from the earlier layer (61). Then, the second detection is made by the 94th layer, yielding a detection feature map of 26 x 26 x 255." }, { "code": null, "e": 5130, "s": 4754, "text": "A similar procedure is followed again, where the feature map from layer 91 is subjected to few convolutional layers before being depth concatenated with a feature map from layer 36. Like before, a few 1 x 1 convolutional layers follow to fuse the information from the previous layer (36). We make the final of the 3 at 106th layer, yielding feature map of size 52 x 52 x 255." }, { "code": null, "e": 5386, "s": 5130, "text": "Detections at different layers helps address the issue of detecting small objects, a frequent complaint with YOLO v2. The upsampled layers concatenated with the previous layers help preserve the fine grained features which help in detecting small objects." }, { "code": null, "e": 5651, "s": 5386, "text": "The 13 x 13 layer is responsible for detecting large objects, whereas the 52 x 52 layer detects the smaller objects, with the 26 x 26 layer detecting medium objects. Here is a comparative analysis of different objects picked in the same object by different layers." }, { "code": null, "e": 5825, "s": 5651, "text": "YOLO v3, in total uses 9 anchor boxes. Three for each scale. If you’re training YOLO on your own dataset, you should go about using K-Means clustering to generate 9 anchors." }, { "code": null, "e": 6013, "s": 5825, "text": "Then, arrange the anchors is descending order of a dimension. Assign the three biggest anchors for the first scale , the next three for the second scale, and the last three for the third." }, { "code": null, "e": 6252, "s": 6013, "text": "For an input image of same size, YOLO v3 predicts more bounding boxes than YOLO v2. For instance, at it’s native resolution of 416 x 416, YOLO v2 predicted 13 x 13 x 5 = 845 boxes. At each grid cell, 5 boxes were detected using 5 anchors." }, { "code": null, "e": 6684, "s": 6252, "text": "On the other hand YOLO v3 predicts boxes at 3 different scales. For the same image of 416 x 416, the number of predicted boxes are 10,647. This means that YOLO v3 predicts 10x the number of boxes predicted by YOLO v2. You could easily imagine why it’s slower than YOLO v2. At each scale, every grid can predict 3 boxes using 3 anchors. Since there are three scales, the number of anchor boxes used in total are 9, 3 for each scale." }, { "code": null, "e": 6735, "s": 6684, "text": "Earlier, YOLO v2’s loss function looked like this." }, { "code": null, "e": 7147, "s": 6735, "text": "I know this is intimidating, but notice the last three terms. Of them, the first one penalizes the objectness score prediction for bounding boxes responsible for predicting objects (the scores for these should ideally be 1), the second one for bounding boxes having no objects, (the scores should ideally be zero), and the last one penalises the class prediction for the bounding box which predicts the objects." }, { "code": null, "e": 7389, "s": 7147, "text": "The last three terms in YOLO v2 are the squared errors, whereas in YOLO v3, they’ve been replaced by cross-entropy error terms. In other words, object confidence and class predictions in YOLO v3 are now predicted through logistic regression." }, { "code": null, "e": 7542, "s": 7389, "text": "While we are training the detector, for each ground truth box, we assign a bounding box, whose anchor has the maximum overlap with the ground truth box." }, { "code": null, "e": 7621, "s": 7542, "text": "YOLO v3 now performs multilabel classification for objects detected in images." }, { "code": null, "e": 7813, "s": 7621, "text": "Earlier in YOLO, authors used to softmax the class scores and take the class with maximum score to be the class of the object contained in the bounding box. This has been modified in YOLO v3." }, { "code": null, "e": 8017, "s": 7813, "text": "Softmaxing classes rests on the assumption that classes are mutually exclusive, or in simple words, if an object belongs to one class, then it cannot belong to the other. This works fine in COCO dataset." }, { "code": null, "e": 8406, "s": 8017, "text": "However, when we have classes like Person and Women in a dataset, then the above assumption fails. This is the reason why the authors of YOLO have refrained from softmaxing the classes. Instead, each class score is predicted using logistic regression and a threshold is used to predict multiple labels for an object. Classes with scores higher than this threshold are assigned to the box." }, { "code": null, "e": 8643, "s": 8406, "text": "YOLO v3 performs at par with other state of art detectors like RetinaNet, while being considerably faster, at COCO mAP 50 benchmark. It is also better than SSD and it’s variants. Here’s a comparison of performances right from the paper." }, { "code": null, "e": 9168, "s": 8643, "text": "But, but and but, YOLO looses out on COCO benchmarks with a higher value of IoU used to reject a detection. I’m not going to explain how the COCO benchmark works as it’s beyond the scope of the work, but the 50 in COCO 50 benchmark is a measure of how well do the predicted bounding boxes align the the ground truth boxes of the object. 50 here corresponds to 0.5 IoU. If the IoU between the prediction and the ground truth box is less than 0.5, the prediction is classified as a mislocalisation and marked a false positive." }, { "code": null, "e": 9483, "s": 9168, "text": "In benchmarks, where this number is higher (say, COCO 75), the boxes need to be aligned more perfectly to be not rejected by the evaluation metric. Here is where YOLO is outdone by RetinaNet, as it’s bounding boxes are not aligned as well as of RetinaNet. Here’s a detailed table for a wider variety of benchmarks." }, { "code": null, "e": 9698, "s": 9483, "text": "You can run the detector on either images or video by using the code provided in this Github repo. The code requires PyTorch 0.3+, OpenCV 3 and Python 3.5. Setup the repo, and you can run various experiments on it." }, { "code": null, "e": 9761, "s": 9698, "text": "Here is a look at what the different detection layers pick up." }, { "code": null, "e": 9812, "s": 9761, "text": "python detect.py --scales 1 --images imgs/img3.jpg" }, { "code": null, "e": 9863, "s": 9812, "text": "python detect.py --scales 2 --images imgs/img3.jpg" }, { "code": null, "e": 9914, "s": 9863, "text": "python detect.py --scales 3 --images imgs/img3.jpg" }, { "code": null, "e": 9966, "s": 9914, "text": "python detect.py --reso 320 --images imgs/imgs4.jpg" }, { "code": null, "e": 10018, "s": 9966, "text": "python detect.py --reso 416 --images imgs/imgs4.jpg" }, { "code": null, "e": 10070, "s": 10018, "text": "python detect.py --reso 608 --images imgs/imgs4.jpg" }, { "code": null, "e": 10123, "s": 10070, "text": "python detect.py --reso 960 --images imgs/imgs4.jpg " }, { "code": null, "e": 10384, "s": 10123, "text": "Larger input resolutions don’t help much in our case, but they might help in detection of images with small objects. On the other hand, larger input resolutions add to inference time. This is a hyper parameter that needs to be tuned depending upon application." }, { "code": null, "e": 10555, "s": 10384, "text": "You can experiment with other metrics such as batch size, objectness confidence, and NMS threshold by going to the repo. Everything has been mentioned in the ReadMe file." }, { "code": null, "e": 10927, "s": 10555, "text": "If you want to implement a YOLO v3 detector by yourself in PyTorch, here’s a series of tutorials I wrote to do the same over at Paperspace. Now, I’d expect you to have basic familiarity with PyTorch if you wanna have a go at this tutorial. If you’re someone who’s looking from moving from a beginner PyTorch user to an intermediate one, this tutorial is just about right." }, { "code": null, "e": 10985, "s": 10927, "text": "YOLO v3: An incremental improvementHow is mAP calculated?" }, { "code": null, "e": 11021, "s": 10985, "text": "YOLO v3: An incremental improvement" } ]
Tryit Editor v3.7
Tryit: Responsive framework: W3.CSS
[]
Nth element of the Fibonacci series JavaScript
We are required to write a JavaScript function that takes in a single number as the first and the only argument, let’s call that number n. The function should return the nth element of the Fibonacci series. For example − fibonacci(10) should return 55 fibonacci(3) should return 2 fibonacci(6) should return 8 fibonacci(2) should return 1 const fibonacci = (num = 1) => { const series = [1, 1]; for (let i = 2; i < num; i++) { const a = series[i - 1]; const b = series[i - 2]; series.push(a + b); }; return series[num - 1]; }; console.log(fibonacci(10)); console.log(fibonacci(6)); console.log(fibonacci(3)); console.log(fibonacci(2)); And the output in the console will be − 55 8 2 1
[ { "code": null, "e": 1201, "s": 1062, "text": "We are required to write a JavaScript function that takes in a single number as the first and the only argument, let’s call that number n." }, { "code": null, "e": 1269, "s": 1201, "text": "The function should return the nth element of the Fibonacci series." }, { "code": null, "e": 1283, "s": 1269, "text": "For example −" }, { "code": null, "e": 1401, "s": 1283, "text": "fibonacci(10) should return 55\nfibonacci(3) should return 2\nfibonacci(6) should return 8\nfibonacci(2) should return 1" }, { "code": null, "e": 1728, "s": 1401, "text": "const fibonacci = (num = 1) => {\n const series = [1, 1];\n for (let i = 2; i < num; i++) {\n const a = series[i - 1];\n const b = series[i - 2];\n series.push(a + b);\n };\n return series[num - 1];\n};\nconsole.log(fibonacci(10));\nconsole.log(fibonacci(6));\nconsole.log(fibonacci(3));\nconsole.log(fibonacci(2));" }, { "code": null, "e": 1768, "s": 1728, "text": "And the output in the console will be −" }, { "code": null, "e": 1777, "s": 1768, "text": "55\n8\n2\n1" } ]
Print Postorder traversal from given Inorder and Preorder traversals
Given with inorder and preorder of a tree program must find the postroder traversal and print the same Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal post[] = {4, 5, 2, 6, 3, 1} START Step 1 -> declare function as find_value(int p, int in_order[], int n) Loop For i=0 and i<n and ++i IF in_order[i]==p Return i End IF End Step 2 -> declare function as postorder(int pre_order[], int in_order[], int n) Declare int variable as root = find_value(pre_order[0], in_order, n) IF root!=0 Call postorder(pre_order+1, in_order, root) End IF root !=n-1 Call postorder(pre_order+root+1, in_order+root+1,n-root-1) End Print pre_order[0] End Step 3 -> goto main() Declare int pre_order[] = {1, 2, 4, 5, 3, 6} Declare int in_order[] = {4, 2, 5, 1, 3, 6} Declare int size = sizeof(pre_order)/sizeof(pre_order[0]) Call postorder(pre_order, in_order, size) STOP #include <stdio.h> int find_value(int p, int in_order[], int n) { for (int i = 0; i < n; ++i) { if (in_order[i] == p) { return i; } } return -1; } int postorder(int pre_order[], int in_order[], int n) { int root = find_value(pre_order[0], in_order, n); if(root !=0 ) postorder(pre_order+1, in_order, root); if (root != n-1) postorder(pre_order+root+1, in_order+root+1, n-root-1); printf("%d ", pre_order[0]); } int main(int argc, char const *argv[]) { int pre_order[] = {1, 2, 4, 5, 3, 6}; int in_order[] = {4, 2, 5, 1, 3, 6}; int size = sizeof(pre_order)/sizeof(pre_order[0]); postorder(pre_order, in_order, size); return 0; } if we run the above program then it will generate the following output 4 5 2 6 3 1
[ { "code": null, "e": 1165, "s": 1062, "text": "Given with inorder and preorder of a tree program must find the postroder traversal and print the same" }, { "code": null, "e": 1318, "s": 1165, "text": "Input:\nInorder traversal in[] = {4, 2, 5, 1, 3, 6}\nPreorder traversal pre[] = {1, 2, 4, 5, 3, 6}\nOutput:\nPostorder traversal post[] = {4, 5, 2, 6, 3, 1}" }, { "code": null, "e": 2055, "s": 1318, "text": "START\nStep 1 -> declare function as find_value(int p, int in_order[], int n)\n Loop For i=0 and i<n and ++i\n IF in_order[i]==p\n Return i\n End IF\n End\nStep 2 -> declare function as postorder(int pre_order[], int in_order[], int n)\n Declare int variable as root = find_value(pre_order[0], in_order, n)\n IF root!=0\n Call postorder(pre_order+1, in_order, root)\n End\n IF root !=n-1\n Call postorder(pre_order+root+1, in_order+root+1,n-root-1)\n End\n Print pre_order[0]\nEnd\nStep 3 -> goto main()\n Declare int pre_order[] = {1, 2, 4, 5, 3, 6}\n Declare int in_order[] = {4, 2, 5, 1, 3, 6}\n Declare int size = sizeof(pre_order)/sizeof(pre_order[0])\n Call postorder(pre_order, in_order, size)\nSTOP" }, { "code": null, "e": 2752, "s": 2055, "text": "#include <stdio.h>\nint find_value(int p, int in_order[], int n) {\n for (int i = 0; i < n; ++i) {\n if (in_order[i] == p) {\n return i;\n }\n }\n return -1;\n}\nint postorder(int pre_order[], int in_order[], int n) {\n int root = find_value(pre_order[0], in_order, n);\n if(root !=0 )\n postorder(pre_order+1, in_order, root);\n if (root != n-1)\n postorder(pre_order+root+1, in_order+root+1, n-root-1);\n printf(\"%d \", pre_order[0]);\n}\nint main(int argc, char const *argv[]) {\n int pre_order[] = {1, 2, 4, 5, 3, 6};\n int in_order[] = {4, 2, 5, 1, 3, 6};\n int size = sizeof(pre_order)/sizeof(pre_order[0]);\n postorder(pre_order, in_order, size);\n return 0;\n}" }, { "code": null, "e": 2823, "s": 2752, "text": "if we run the above program then it will generate the following output" }, { "code": null, "e": 2835, "s": 2823, "text": "4 5 2 6 3 1" } ]
new and delete operators in C++ - GeeksQuiz
29 Jul, 2020 int **arr = new int *[10]; Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies How to set background images in ReactJS ? Microsoft Interview Experience for Internship (Via Engage) Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Alter Multiple Columns at Once in SQL Server? How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File
[ { "code": null, "e": 27610, "s": 27582, "text": "\n29 Jul, 2020" }, { "code": null, "e": 27638, "s": 27610, "text": "int **arr = new int *[10]; " }, { "code": null, "e": 27736, "s": 27638, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 27745, "s": 27736, "text": "Comments" }, { "code": null, "e": 27758, "s": 27745, "text": "Old Comments" }, { "code": null, "e": 27811, "s": 27758, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 27853, "s": 27811, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27912, "s": 27853, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27973, "s": 27912, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28011, "s": 27973, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28064, "s": 28011, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 28122, "s": 28064, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 28184, "s": 28122, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28264, "s": 28184, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" } ]
Comb Sort - GeeksforGeeks
18 Jan, 2022 Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]Although, it works better than Bubble Sort on average, worst case remains O(n2).Below is the implementation. C++ Java Python3 C# Javascript // C++ implementation of Comb Sort#include<bits/stdc++.h>using namespace std; // To find gap between elementsint getNextGap(int gap){ // Shrink gap by Shrink factor gap = (gap*10)/13; if (gap < 1) return 1; return gap;} // Function to sort a[0..n-1] using Comb Sortvoid combSort(int a[], int n){ // Initialize gap int gap = n; // Initialize swapped as true to make sure that // loop runs bool swapped = true; // Keep running while gap is more than 1 and last // iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (int i=0; i<n-gap; i++) { if (a[i] > a[i+gap]) { swap(a[i], a[i+gap]); swapped = true; } } }} // Driver programint main(){ int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; int n = sizeof(a)/sizeof(a[0]); combSort(a, n); printf("Sorted array: \n"); for (int i=0; i<n; i++) printf("%d ", a[i]); return 0;} // Java program for implementation of Comb Sortclass CombSort{ // To find gap between elements int getNextGap(int gap) { // Shrink gap by Shrink factor gap = (gap*10)/13; if (gap < 1) return 1; return gap; } // Function to sort arr[] using Comb Sort void sort(int arr[]) { int n = arr.length; // initialize gap int gap = n; // Initialize swapped as true to make sure that // loop runs boolean swapped = true; // Keep running while gap is more than 1 and last // iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (int i=0; i<n-gap; i++) { if (arr[i] > arr[i+gap]) { // Swap arr[i] and arr[i+gap] int temp = arr[i]; arr[i] = arr[i+gap]; arr[i+gap] = temp; // Set swapped swapped = true; } } } } // Driver method public static void main(String args[]) { CombSort ob = new CombSort(); int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; ob.sort(arr); System.out.println("sorted array"); for (int i=0; i<arr.length; ++i) System.out.print(arr[i] + " "); }}/* This code is contributed by Rajat Mishra */ # Python program for implementation of CombSort # To find next gap from currentdef getNextGap(gap): # Shrink gap by Shrink factor gap = (gap * 10)//13 if gap < 1: return 1 return gap # Function to sort arr[] using Comb Sortdef combSort(arr): n = len(arr) # Initialize gap gap = n # Initialize swapped as true to make sure that # loop runs swapped = True # Keep running while gap is more than 1 and last # iteration caused a swap while gap !=1 or swapped == 1: # Find next gap gap = getNextGap(gap) # Initialize swapped as false so that we can # check if swap happened or not swapped = False # Compare all elements with current gap for i in range(0, n-gap): if arr[i] > arr[i + gap]: arr[i], arr[i + gap]=arr[i + gap], arr[i] swapped = True # Driver code to test abovearr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]combSort(arr) print ("Sorted array:")for i in range(len(arr)): print (arr[i],end=" ") # This code is contributed by Mohit Kumra // C# program for implementation of Comb Sortusing System; class GFG{ // To find gap between elements static int getNextGap(int gap) { // Shrink gap by Shrink factor gap = (gap*10)/13; if (gap < 1) return 1; return gap; } // Function to sort arr[] using Comb Sort static void sort(int []arr) { int n = arr.Length; // initialize gap int gap = n; // Initialize swapped as true to // make sure that loop runs bool swapped = true; // Keep running while gap is more than // 1 and last iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (int i=0; i<n-gap; i++) { if (arr[i] > arr[i+gap]) { // Swap arr[i] and arr[i+gap] int temp = arr[i]; arr[i] = arr[i+gap]; arr[i+gap] = temp; // Set swapped swapped = true; } } } } // Driver method public static void Main() { int []arr = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; sort(arr); Console.WriteLine("sorted array"); for (int i=0; i<arr.Length; ++i) Console.Write(arr[i] + " "); }} // This code is contributed by Sam007 <script> // Javascript program for implementation of Comb Sort // To find gap between elements function getNextGap(gap) { // Shrink gap by Shrink factor gap = parseInt((gap*10)/13, 10); if (gap < 1) return 1; return gap; } // Function to sort arr[] using Comb Sort function sort(arr) { let n = arr.length; // initialize gap let gap = n; // Initialize swapped as true to // make sure that loop runs let swapped = true; // Keep running while gap is more than // 1 and last iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (let i=0; i<n-gap; i++) { if (arr[i] > arr[i+gap]) { // Swap arr[i] and arr[i+gap] let temp = arr[i]; arr[i] = arr[i+gap]; arr[i+gap] = temp; // Set swapped swapped = true; } } } } let arr = [8, 4, 1, 56, 3, -44, 23, -6, 28, 0]; sort(arr); document.write("sorted array" + "</br>"); for (let i=0; i<arr.length; ++i) document.write(arr[i] + " "); // This code is contributed by decode2207</script> Output : Sorted array: -44 -6 0 1 3 4 8 23 28 56 Illustration: Let the array elements be 8, 4, 1, 56, 3, -44, 23, -6, 28, 0 Initially gap value = 10 After shrinking gap value => 10/1.3 = 7; 8 4 1 56 3 -44 23 -6 28 0 -6 4 1 56 3 -44 23 8 28 0 -6 4 0 56 3 -44 23 8 28 1 New gap value => 7/1.3 = 5; -44 4 0 56 3 -6 23 8 28 1 -44 4 0 28 3 -6 23 8 56 1 -44 4 0 28 1 -6 23 8 56 3 New gap value => 5/1.3 = 3; -44 1 0 28 4 -6 23 8 56 3 -44 1 -6 28 4 0 23 8 56 3 -44 1 -6 23 4 0 28 8 56 3 -44 1 -6 23 4 0 3 8 56 28 New gap value => 3/1.3 = 2; -44 1 -6 0 4 23 3 8 56 28 -44 1 -6 0 3 23 4 8 56 28 -44 1 -6 0 3 8 4 23 56 28 New gap value => 2/1.3 = 1; -44 -6 1 0 3 8 4 23 56 28 -44 -6 0 1 3 8 4 23 56 28 -44 -6 0 1 3 4 8 23 56 28 -44 -6 0 1 3 4 8 23 28 56 no more swaps required (Array sorted) Time Complexity: Average case time complexity of the algorithm is Ω(N2/2p), where p is the number of increments. The worst-case complexity of this algorithm is O(n2) and the Best Case complexity is O(nlogn). Auxiliary Space : O(1). This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Snapshots: Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Pigeonhole SortPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 lakshaygupta2807 Captain_JackSparrow decode2207 amartyaghoshgfg Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array Count Inversions in an array | Set 1 (Using Merge Sort) Python Program for QuickSort sort() in Python
[ { "code": null, "e": 23828, "s": 23800, "text": "\n18 Jan, 2022" }, { "code": null, "e": 24484, "s": 23828, "text": "Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]Although, it works better than Bubble Sort on average, worst case remains O(n2).Below is the implementation." }, { "code": null, "e": 24488, "s": 24484, "text": "C++" }, { "code": null, "e": 24493, "s": 24488, "text": "Java" }, { "code": null, "e": 24501, "s": 24493, "text": "Python3" }, { "code": null, "e": 24504, "s": 24501, "text": "C#" }, { "code": null, "e": 24515, "s": 24504, "text": "Javascript" }, { "code": "// C++ implementation of Comb Sort#include<bits/stdc++.h>using namespace std; // To find gap between elementsint getNextGap(int gap){ // Shrink gap by Shrink factor gap = (gap*10)/13; if (gap < 1) return 1; return gap;} // Function to sort a[0..n-1] using Comb Sortvoid combSort(int a[], int n){ // Initialize gap int gap = n; // Initialize swapped as true to make sure that // loop runs bool swapped = true; // Keep running while gap is more than 1 and last // iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (int i=0; i<n-gap; i++) { if (a[i] > a[i+gap]) { swap(a[i], a[i+gap]); swapped = true; } } }} // Driver programint main(){ int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; int n = sizeof(a)/sizeof(a[0]); combSort(a, n); printf(\"Sorted array: \\n\"); for (int i=0; i<n; i++) printf(\"%d \", a[i]); return 0;}", "e": 25731, "s": 24515, "text": null }, { "code": "// Java program for implementation of Comb Sortclass CombSort{ // To find gap between elements int getNextGap(int gap) { // Shrink gap by Shrink factor gap = (gap*10)/13; if (gap < 1) return 1; return gap; } // Function to sort arr[] using Comb Sort void sort(int arr[]) { int n = arr.length; // initialize gap int gap = n; // Initialize swapped as true to make sure that // loop runs boolean swapped = true; // Keep running while gap is more than 1 and last // iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (int i=0; i<n-gap; i++) { if (arr[i] > arr[i+gap]) { // Swap arr[i] and arr[i+gap] int temp = arr[i]; arr[i] = arr[i+gap]; arr[i+gap] = temp; // Set swapped swapped = true; } } } } // Driver method public static void main(String args[]) { CombSort ob = new CombSort(); int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; ob.sort(arr); System.out.println(\"sorted array\"); for (int i=0; i<arr.length; ++i) System.out.print(arr[i] + \" \"); }}/* This code is contributed by Rajat Mishra */", "e": 27385, "s": 25731, "text": null }, { "code": "# Python program for implementation of CombSort # To find next gap from currentdef getNextGap(gap): # Shrink gap by Shrink factor gap = (gap * 10)//13 if gap < 1: return 1 return gap # Function to sort arr[] using Comb Sortdef combSort(arr): n = len(arr) # Initialize gap gap = n # Initialize swapped as true to make sure that # loop runs swapped = True # Keep running while gap is more than 1 and last # iteration caused a swap while gap !=1 or swapped == 1: # Find next gap gap = getNextGap(gap) # Initialize swapped as false so that we can # check if swap happened or not swapped = False # Compare all elements with current gap for i in range(0, n-gap): if arr[i] > arr[i + gap]: arr[i], arr[i + gap]=arr[i + gap], arr[i] swapped = True # Driver code to test abovearr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]combSort(arr) print (\"Sorted array:\")for i in range(len(arr)): print (arr[i],end=\" \") # This code is contributed by Mohit Kumra", "e": 28467, "s": 27385, "text": null }, { "code": "// C# program for implementation of Comb Sortusing System; class GFG{ // To find gap between elements static int getNextGap(int gap) { // Shrink gap by Shrink factor gap = (gap*10)/13; if (gap < 1) return 1; return gap; } // Function to sort arr[] using Comb Sort static void sort(int []arr) { int n = arr.Length; // initialize gap int gap = n; // Initialize swapped as true to // make sure that loop runs bool swapped = true; // Keep running while gap is more than // 1 and last iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (int i=0; i<n-gap; i++) { if (arr[i] > arr[i+gap]) { // Swap arr[i] and arr[i+gap] int temp = arr[i]; arr[i] = arr[i+gap]; arr[i+gap] = temp; // Set swapped swapped = true; } } } } // Driver method public static void Main() { int []arr = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; sort(arr); Console.WriteLine(\"sorted array\"); for (int i=0; i<arr.Length; ++i) Console.Write(arr[i] + \" \"); }} // This code is contributed by Sam007", "e": 30074, "s": 28467, "text": null }, { "code": "<script> // Javascript program for implementation of Comb Sort // To find gap between elements function getNextGap(gap) { // Shrink gap by Shrink factor gap = parseInt((gap*10)/13, 10); if (gap < 1) return 1; return gap; } // Function to sort arr[] using Comb Sort function sort(arr) { let n = arr.length; // initialize gap let gap = n; // Initialize swapped as true to // make sure that loop runs let swapped = true; // Keep running while gap is more than // 1 and last iteration caused a swap while (gap != 1 || swapped == true) { // Find next gap gap = getNextGap(gap); // Initialize swapped as false so that we can // check if swap happened or not swapped = false; // Compare all elements with current gap for (let i=0; i<n-gap; i++) { if (arr[i] > arr[i+gap]) { // Swap arr[i] and arr[i+gap] let temp = arr[i]; arr[i] = arr[i+gap]; arr[i+gap] = temp; // Set swapped swapped = true; } } } } let arr = [8, 4, 1, 56, 3, -44, 23, -6, 28, 0]; sort(arr); document.write(\"sorted array\" + \"</br>\"); for (let i=0; i<arr.length; ++i) document.write(arr[i] + \" \"); // This code is contributed by decode2207</script>", "e": 31629, "s": 30074, "text": null }, { "code": null, "e": 31639, "s": 31629, "text": "Output : " }, { "code": null, "e": 31681, "s": 31639, "text": "Sorted array: \n-44 -6 0 1 3 4 8 23 28 56 " }, { "code": null, "e": 31722, "s": 31681, "text": "Illustration: Let the array elements be " }, { "code": null, "e": 31757, "s": 31722, "text": "8, 4, 1, 56, 3, -44, 23, -6, 28, 0" }, { "code": null, "e": 31824, "s": 31757, "text": "Initially gap value = 10 After shrinking gap value => 10/1.3 = 7; " }, { "code": null, "e": 31905, "s": 31824, "text": " 8 4 1 56 3 -44 23 -6 28 0\n-6 4 1 56 3 -44 23 8 28 0\n-6 4 0 56 3 -44 23 8 28 1" }, { "code": null, "e": 31935, "s": 31905, "text": "New gap value => 7/1.3 = 5; " }, { "code": null, "e": 32013, "s": 31935, "text": "-44 4 0 56 3 -6 23 8 28 1\n-44 4 0 28 3 -6 23 8 56 1\n-44 4 0 28 1 -6 23 8 56 3" }, { "code": null, "e": 32042, "s": 32013, "text": "New gap value => 5/1.3 = 3; " }, { "code": null, "e": 32151, "s": 32042, "text": "-44 1 0 28 4 -6 23 8 56 3\n-44 1 -6 28 4 0 23 8 56 3\n-44 1 -6 23 4 0 28 8 56 3\n-44 1 -6 23 4 0 3 8 56 28" }, { "code": null, "e": 32181, "s": 32151, "text": "New gap value => 3/1.3 = 2; " }, { "code": null, "e": 32259, "s": 32181, "text": "-44 1 -6 0 4 23 3 8 56 28\n-44 1 -6 0 3 23 4 8 56 28\n-44 1 -6 0 3 8 4 23 56 28" }, { "code": null, "e": 32289, "s": 32259, "text": "New gap value => 2/1.3 = 1; " }, { "code": null, "e": 32433, "s": 32289, "text": "-44 -6 1 0 3 8 4 23 56 28\n-44 -6 0 1 3 8 4 23 56 28\n-44 -6 0 1 3 4 8 23 56 28\n-44 -6 0 1 3 4 8 23 28 56 \n\nno more swaps required (Array sorted)" }, { "code": null, "e": 32666, "s": 32433, "text": "Time Complexity: Average case time complexity of the algorithm is Ω(N2/2p), where p is the number of increments. The worst-case complexity of this algorithm is O(n2) and the Best Case complexity is O(nlogn). Auxiliary Space : O(1). " }, { "code": null, "e": 32935, "s": 32666, "text": "This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 32948, "s": 32935, "text": "Snapshots: " }, { "code": null, "e": 33271, "s": 32948, "text": "Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Pigeonhole SortPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33278, "s": 33271, "text": "Sam007" }, { "code": null, "e": 33295, "s": 33278, "text": "lakshaygupta2807" }, { "code": null, "e": 33315, "s": 33295, "text": "Captain_JackSparrow" }, { "code": null, "e": 33326, "s": 33315, "text": "decode2207" }, { "code": null, "e": 33342, "s": 33326, "text": "amartyaghoshgfg" }, { "code": null, "e": 33350, "s": 33342, "text": "Sorting" }, { "code": null, "e": 33358, "s": 33350, "text": "Sorting" }, { "code": null, "e": 33456, "s": 33358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33465, "s": 33456, "text": "Comments" }, { "code": null, "e": 33478, "s": 33465, "text": "Old Comments" }, { "code": null, "e": 33501, "s": 33478, "text": "std::sort() in C++ STL" }, { "code": null, "e": 33545, "s": 33501, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 33556, "s": 33545, "text": "Radix Sort" }, { "code": null, "e": 33580, "s": 33556, "text": "Merge two sorted arrays" }, { "code": null, "e": 33611, "s": 33580, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 33655, "s": 33611, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 33711, "s": 33655, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 33740, "s": 33711, "text": "Python Program for QuickSort" } ]
Python Program to Implement Shell Sort
When it is required to implement shell sort, a function is defined, and this takes a list and the length of the list as arguments. This list is sorted up to a specific number of elements, wherein the number of elements is the largest value. This is done until the number of elements has the smallest value. This is done for all sub-lists in the list, and all these sub-lists are sorted. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). Below is a demonstration of the same − Live Demo def shell_sort(my_list, list_len): interval = list_len // 2 while interval > 0: for i in range(interval, list_len): temp = my_list[i] j = i while j >= interval and my_list[j - interval] > temp: my_list[j] = my_list[j - interval] j -= interval my_list[j] = temp interval //= 2 my_list = [ 45, 31, 62, 12, 89, 5, 9, 8] list_len = len(my_list) print ("The list before sorting is :") print(my_list) shell_sort(my_list, list_len) print ("\nThe list after performing shell sorting is :") print(my_list) The list before sorting is : [45, 31, 62, 12, 89, 5, 9, 8] The list after performing shell sorting is : [5, 8, 9, 12, 31, 45, 62, 89] A method named 'shell_sort' is defined, that takes the list, and the length of the list as arguments. The 'interval' variable is defined by using the '//' bitwise operator. It performs floor division. It rounds down the value to the nearest whole number. The list is iterated over, and a temporary variable is created. The 'interval' variable is compared with every index of the list, and every element in the list is compared to the temporary variable. The 'interval' variable is again used to perform floor division. The list is defined, and is displayed on the console. The method is called by passing this list, and its length. The output is displayed on the console.
[ { "code": null, "e": 1369, "s": 1062, "text": "When it is required to implement shell sort, a function is defined, and this takes a list and the length of the list as arguments. This list is sorted up to a specific number of elements, wherein the number of elements is the largest value. This is done until the number of elements has the smallest value." }, { "code": null, "e": 1449, "s": 1369, "text": "This is done for all sub-lists in the list, and all these sub-lists are sorted." }, { "code": null, "e": 1576, "s": 1449, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)." }, { "code": null, "e": 1615, "s": 1576, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1625, "s": 1615, "text": "Live Demo" }, { "code": null, "e": 2201, "s": 1625, "text": "def shell_sort(my_list, list_len):\n interval = list_len // 2\n while interval > 0:\n for i in range(interval, list_len):\n temp = my_list[i]\n j = i\n while j >= interval and my_list[j - interval] > temp:\n my_list[j] = my_list[j - interval]\n j -= interval\n my_list[j] = temp\n interval //= 2\n\nmy_list = [ 45, 31, 62, 12, 89, 5, 9, 8]\nlist_len = len(my_list)\nprint (\"The list before sorting is :\")\nprint(my_list)\nshell_sort(my_list, list_len)\nprint (\"\\nThe list after performing shell sorting is :\")\nprint(my_list)" }, { "code": null, "e": 2336, "s": 2201, "text": "The list before sorting is :\n[45, 31, 62, 12, 89, 5, 9, 8]\n\nThe list after performing shell sorting is :\n[5, 8, 9, 12, 31, 45, 62, 89]" }, { "code": null, "e": 2438, "s": 2336, "text": "A method named 'shell_sort' is defined, that takes the list, and the length of the list as arguments." }, { "code": null, "e": 2509, "s": 2438, "text": "The 'interval' variable is defined by using the '//' bitwise operator." }, { "code": null, "e": 2537, "s": 2509, "text": "It performs floor division." }, { "code": null, "e": 2591, "s": 2537, "text": "It rounds down the value to the nearest whole number." }, { "code": null, "e": 2655, "s": 2591, "text": "The list is iterated over, and a temporary variable is created." }, { "code": null, "e": 2790, "s": 2655, "text": "The 'interval' variable is compared with every index of the list, and every element in the list is compared to the temporary variable." }, { "code": null, "e": 2855, "s": 2790, "text": "The 'interval' variable is again used to perform floor division." }, { "code": null, "e": 2909, "s": 2855, "text": "The list is defined, and is displayed on the console." }, { "code": null, "e": 2968, "s": 2909, "text": "The method is called by passing this list, and its length." }, { "code": null, "e": 3008, "s": 2968, "text": "The output is displayed on the console." } ]
Node.js Debugging
07 Oct, 2021 Node.js Debugging: Debugging is a concept to identify and remove errors from software applications. In this article, we will learn about the technique to debug a Node.js application. Why not to use console.log()?Using console.log to debug the code generally dives into an infinite loop of “stopping the app and adding a console.log, and start the app again” operations. Besides slowing down the development of the app, it also makes the writing dirty and creates unnecessary code. Finally, trying to log out variables alongside with the noise of other potential logging operations, may make the process of debugging difficult when attempting to find the values you are debugging. How to debug?Mostly we used console.log() but as mentioned above, it is not always a good practice. We can use a V8 inspector for it. Steps for debugging: Write the following code in the terminal window as shown below:node --inspect-brk-filename.jsOpen your Chrome browser and write inspect as shown below:Now click on Open Dedicated DevTools for Node.Now, click on the Node.js icon. The terminal will show the following message: Write the following code in the terminal window as shown below:node --inspect-brk-filename.js node --inspect-brk-filename.js Open your Chrome browser and write inspect as shown below: Now click on Open Dedicated DevTools for Node. Now, click on the Node.js icon. The terminal will show the following message: Other tools to help launch a DevTools window: june07.com/nim github.com/jaridmargolin/inspect-process github.com/darcyclarke/rawkit Additional Debugging APIs: Debugging an existing Node process:process._debugProcess(pid);</pre GDB-like CLI Debugger: node inspect filename.js Drive with DevTools Protocol via WS port:const dp = require('chrome-remote-interface'); async function test() {const client = await dp();const {Profiler, Runtime} = client; await Profiler.enable();await Profiler.setSamplingInterval({interval: 500}); await Profiler.start();await Runtime.evaluate({expression: 'startTest();'});await sleep(800); const data = await Profiler.stop();require('fs').writeFileSync('data.cpuprofile', JSON.stringify(data.profile));}; test().then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);});DevTools Protocol via require('inspector'):const inspector = require('inspector');const fs = require('fs');const session = new inspector.Session(); session.connect();session.post('Profiler.enable');session.post('Profiler.start'); setTimeout( function() { session.post('Profiler.stop', function(err, data) { fs.writeFileSync('data.cpuprofile', JSON.stringify(data.profile)); });}, 8000); Debugging an existing Node process:process._debugProcess(pid);</pre process._debugProcess(pid);</pre GDB-like CLI Debugger: node inspect filename.js node inspect filename.js Drive with DevTools Protocol via WS port:const dp = require('chrome-remote-interface'); async function test() {const client = await dp();const {Profiler, Runtime} = client; await Profiler.enable();await Profiler.setSamplingInterval({interval: 500}); await Profiler.start();await Runtime.evaluate({expression: 'startTest();'});await sleep(800); const data = await Profiler.stop();require('fs').writeFileSync('data.cpuprofile', JSON.stringify(data.profile));}; test().then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);}); const dp = require('chrome-remote-interface'); async function test() {const client = await dp();const {Profiler, Runtime} = client; await Profiler.enable();await Profiler.setSamplingInterval({interval: 500}); await Profiler.start();await Runtime.evaluate({expression: 'startTest();'});await sleep(800); const data = await Profiler.stop();require('fs').writeFileSync('data.cpuprofile', JSON.stringify(data.profile));}; test().then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);}); DevTools Protocol via require('inspector'):const inspector = require('inspector');const fs = require('fs');const session = new inspector.Session(); session.connect();session.post('Profiler.enable');session.post('Profiler.start'); setTimeout( function() { session.post('Profiler.stop', function(err, data) { fs.writeFileSync('data.cpuprofile', JSON.stringify(data.profile)); });}, 8000); const inspector = require('inspector');const fs = require('fs');const session = new inspector.Session(); session.connect();session.post('Profiler.enable');session.post('Profiler.start'); setTimeout( function() { session.post('Profiler.stop', function(err, data) { fs.writeFileSync('data.cpuprofile', JSON.stringify(data.profile)); });}, 8000); Another awesome thing in using Chrome as a debugging tool is that you can debug both your front-end and back-end JavaScript code with the same interface. Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Oct, 2021" }, { "code": null, "e": 237, "s": 54, "text": "Node.js Debugging: Debugging is a concept to identify and remove errors from software applications. In this article, we will learn about the technique to debug a Node.js application." }, { "code": null, "e": 734, "s": 237, "text": "Why not to use console.log()?Using console.log to debug the code generally dives into an infinite loop of “stopping the app and adding a console.log, and start the app again” operations. Besides slowing down the development of the app, it also makes the writing dirty and creates unnecessary code. Finally, trying to log out variables alongside with the noise of other potential logging operations, may make the process of debugging difficult when attempting to find the values you are debugging." }, { "code": null, "e": 868, "s": 734, "text": "How to debug?Mostly we used console.log() but as mentioned above, it is not always a good practice. We can use a V8 inspector for it." }, { "code": null, "e": 889, "s": 868, "text": "Steps for debugging:" }, { "code": null, "e": 1164, "s": 889, "text": "Write the following code in the terminal window as shown below:node --inspect-brk-filename.jsOpen your Chrome browser and write inspect as shown below:Now click on Open Dedicated DevTools for Node.Now, click on the Node.js icon. The terminal will show the following message:" }, { "code": null, "e": 1258, "s": 1164, "text": "Write the following code in the terminal window as shown below:node --inspect-brk-filename.js" }, { "code": null, "e": 1289, "s": 1258, "text": "node --inspect-brk-filename.js" }, { "code": null, "e": 1348, "s": 1289, "text": "Open your Chrome browser and write inspect as shown below:" }, { "code": null, "e": 1395, "s": 1348, "text": "Now click on Open Dedicated DevTools for Node." }, { "code": null, "e": 1473, "s": 1395, "text": "Now, click on the Node.js icon. The terminal will show the following message:" }, { "code": null, "e": 1519, "s": 1473, "text": "Other tools to help launch a DevTools window:" }, { "code": null, "e": 1606, "s": 1519, "text": "june07.com/nim\ngithub.com/jaridmargolin/inspect-process\ngithub.com/darcyclarke/rawkit\n" }, { "code": null, "e": 1633, "s": 1606, "text": "Additional Debugging APIs:" }, { "code": null, "e": 2749, "s": 1633, "text": "Debugging an existing Node process:process._debugProcess(pid);</pre\n\n\nGDB-like CLI Debugger:\nnode inspect filename.js\nDrive with DevTools Protocol via WS port:const dp = require('chrome-remote-interface'); async function test() {const client = await dp();const {Profiler, Runtime} = client; await Profiler.enable();await Profiler.setSamplingInterval({interval: 500}); await Profiler.start();await Runtime.evaluate({expression: 'startTest();'});await sleep(800); const data = await Profiler.stop();require('fs').writeFileSync('data.cpuprofile', JSON.stringify(data.profile));}; test().then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);});DevTools Protocol via require('inspector'):const inspector = require('inspector');const fs = require('fs');const session = new inspector.Session(); session.connect();session.post('Profiler.enable');session.post('Profiler.start'); setTimeout( function() { session.post('Profiler.stop', function(err, data) { fs.writeFileSync('data.cpuprofile', JSON.stringify(data.profile)); });}, 8000);" }, { "code": null, "e": 2818, "s": 2749, "text": "Debugging an existing Node process:process._debugProcess(pid);</pre\n" }, { "code": null, "e": 2852, "s": 2818, "text": "process._debugProcess(pid);</pre\n" }, { "code": null, "e": 2902, "s": 2852, "text": "\nGDB-like CLI Debugger:\nnode inspect filename.js\n" }, { "code": null, "e": 2928, "s": 2902, "text": "node inspect filename.js\n" }, { "code": null, "e": 3500, "s": 2928, "text": "Drive with DevTools Protocol via WS port:const dp = require('chrome-remote-interface'); async function test() {const client = await dp();const {Profiler, Runtime} = client; await Profiler.enable();await Profiler.setSamplingInterval({interval: 500}); await Profiler.start();await Runtime.evaluate({expression: 'startTest();'});await sleep(800); const data = await Profiler.stop();require('fs').writeFileSync('data.cpuprofile', JSON.stringify(data.profile));}; test().then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);});" }, { "code": "const dp = require('chrome-remote-interface'); async function test() {const client = await dp();const {Profiler, Runtime} = client; await Profiler.enable();await Profiler.setSamplingInterval({interval: 500}); await Profiler.start();await Runtime.evaluate({expression: 'startTest();'});await sleep(800); const data = await Profiler.stop();require('fs').writeFileSync('data.cpuprofile', JSON.stringify(data.profile));}; test().then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);});", "e": 4031, "s": 3500, "text": null }, { "code": null, "e": 4458, "s": 4031, "text": "DevTools Protocol via require('inspector'):const inspector = require('inspector');const fs = require('fs');const session = new inspector.Session(); session.connect();session.post('Profiler.enable');session.post('Profiler.start'); setTimeout( function() { session.post('Profiler.stop', function(err, data) { fs.writeFileSync('data.cpuprofile', JSON.stringify(data.profile)); });}, 8000);" }, { "code": "const inspector = require('inspector');const fs = require('fs');const session = new inspector.Session(); session.connect();session.post('Profiler.enable');session.post('Profiler.start'); setTimeout( function() { session.post('Profiler.stop', function(err, data) { fs.writeFileSync('data.cpuprofile', JSON.stringify(data.profile)); });}, 8000);", "e": 4842, "s": 4458, "text": null }, { "code": null, "e": 4996, "s": 4842, "text": "Another awesome thing in using Chrome as a debugging tool is that you can debug both your front-end and back-end JavaScript code with the same interface." }, { "code": null, "e": 5011, "s": 4996, "text": "Node.js-Basics" }, { "code": null, "e": 5018, "s": 5011, "text": "Picked" }, { "code": null, "e": 5026, "s": 5018, "text": "Node.js" }, { "code": null, "e": 5043, "s": 5026, "text": "Web Technologies" } ]
Introduction to Arrays
05 Jul, 2022 An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index 0 and the difference between the two indexes is the offset.For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Remember: “Location of next index depends on the data type we use”. The above image can be looked at as a top-level view of a staircase where you are at the base of the staircase. Each element can be uniquely identified by its index in the array (in a similar way as you could identify your friends by the step on which they were on in the above example). Array’s size In C language, the array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you can’t shrink it nor can you expand it. The reason was that for expanding if we change the size we can’t be sure ( it’s not possible every time) that we get the next memory location to us for free. The shrinking will not work because the array, when declared, gets memory statically allocated, and thus compiler is the only one that can destroy it.Types of indexing in an array: 0 (zero-based indexing): The first element of the array is indexed by a subscript of 0. 1 (one-based indexing): The first element of the array is indexed by the subscript of 1. n (N-based indexing): The base index of an array can be freely chosen. Usually, programming languages allowing n-based indexing also allow negative index values, and other scalar data types like enumerations, or characters may be used as an array index. C++ C Java #include <iostream>using namespace std; int main(){ // Creating an integer array // named arr of size 10. int arr[10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 5; // access and print value at 0 // index we get the output as 5. cout << arr[0]; return 0;} #include <stdio.h> int main(){ // Creating an integer array // named arr of size 10. int arr[10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 5; // access and print value at 0 // index we get the output as 5. printf("%d", arr[0]); return 0;} class GFG{ public static void main (String[] args) { // Creating an integer array // named arr of size 10. int[] arr = new int[10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 5; // access and print value at 0 // index we get the output as 5. System.out.println(arr[0]); }} // This code is contributed by muditj148. 5 Here the value 5 is printed because the first element has index zero and at the zeroth index, we already assigned the value 5. Types of arrays : One dimensional array (1-D arrays)Multidimensional array One dimensional array (1-D arrays) Multidimensional array Advantages of using arrays: Arrays allow random access to elements. This makes accessing elements by position faster. Arrays have better cache locality which makes a pretty big difference in performance. Arrays represent multiple data items of the same type using a single name. Disadvantages of using arrays: You can’t change the size i.e. once you have declared the array you can’t change its size because of static memory allocation. Here Insertion(s) and deletion(s) are difficult as the elements are stored in consecutive memory locations and the shifting operation is costly too.Now if take an example of the implementation of data structure Stack using array there are some obvious flaws. Let’s take the POP operation of the stack. The algorithm would go something like this. Check for the stack underflowDecrement the top by 1 Check for the stack underflow Decrement the top by 1 What we are doing here is, that the pointer to the topmost element is decremented, which means we are just bounding our view, and actually that element stays there taking up the memory space. If you have an array (as a Stack) of any primitive data type then it might be ok. But in the case of an array of Objects, it would take a lot of memory. Examples – // A character array in C/C++/Javachar arr1[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’}; // An Integer array in C/C++/Javaint arr2[] = {10, 20, 30, 40, 50}; // Item at i’th index in array is typically accessed as “arr[i]”. For example:arr1[0] gives us ‘g’arr2[3] gives us 40 Usually, an array of characters is called a ‘string’, whereas an array of ints or floats is simply called an array. Applications on Array Array stores data elements of the same data type. Arrays are used when the size of the data set is known. Used in solving matrix problems. Applied as a lookup table in computer. Databases records are also implemented by the array. Helps in implementing sorting algorithm. The different variables of the same type can be saved under one name. Arrays can be used for CPU scheduling. Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc. 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 if you want to share more information about the topic discussed above. Shubhamlamichane EmperorFlames AayushDiwan mishraakshat2610 gupta_shrinath soumyasambitkunda surabhiraj amanandaman007 ayush933as aishasartaj1 pragalbhmishra12 shapnesht vishwa_63 Angad hrithikmanoj000 guptavivek0503 muditj148 mohitmjaisingh aayushi2402 Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Arrays in C/C++ Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Subset Sum Problem | DP-25
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Jul, 2022" }, { "code": null, "e": 798, "s": 53, "text": "An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index 0 and the difference between the two indexes is the offset.For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Remember: “Location of next index depends on the data type we use”. " }, { "code": null, "e": 1087, "s": 798, "text": "The above image can be looked at as a top-level view of a staircase where you are at the base of the staircase. Each element can be uniquely identified by its index in the array (in a similar way as you could identify your friends by the step on which they were on in the above example). " }, { "code": null, "e": 1100, "s": 1087, "text": "Array’s size" }, { "code": null, "e": 1589, "s": 1100, "text": "In C language, the array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you can’t shrink it nor can you expand it. The reason was that for expanding if we change the size we can’t be sure ( it’s not possible every time) that we get the next memory location to us for free. The shrinking will not work because the array, when declared, gets memory statically allocated, and thus compiler is the only one that can destroy it.Types of indexing in an array: " }, { "code": null, "e": 1677, "s": 1589, "text": "0 (zero-based indexing): The first element of the array is indexed by a subscript of 0." }, { "code": null, "e": 1766, "s": 1677, "text": "1 (one-based indexing): The first element of the array is indexed by the subscript of 1." }, { "code": null, "e": 2020, "s": 1766, "text": "n (N-based indexing): The base index of an array can be freely chosen. Usually, programming languages allowing n-based indexing also allow negative index values, and other scalar data types like enumerations, or characters may be used as an array index." }, { "code": null, "e": 2024, "s": 2020, "text": "C++" }, { "code": null, "e": 2026, "s": 2024, "text": "C" }, { "code": null, "e": 2031, "s": 2026, "text": "Java" }, { "code": "#include <iostream>using namespace std; int main(){ // Creating an integer array // named arr of size 10. int arr[10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 5; // access and print value at 0 // index we get the output as 5. cout << arr[0]; return 0;}", "e": 2347, "s": 2031, "text": null }, { "code": "#include <stdio.h> int main(){ // Creating an integer array // named arr of size 10. int arr[10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 5; // access and print value at 0 // index we get the output as 5. printf(\"%d\", arr[0]); return 0;}", "e": 2652, "s": 2347, "text": null }, { "code": "class GFG{ public static void main (String[] args) { // Creating an integer array // named arr of size 10. int[] arr = new int[10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 5; // access and print value at 0 // index we get the output as 5. System.out.println(arr[0]); }} // This code is contributed by muditj148.", "e": 3095, "s": 2652, "text": null }, { "code": null, "e": 3097, "s": 3095, "text": "5" }, { "code": null, "e": 3224, "s": 3097, "text": "Here the value 5 is printed because the first element has index zero and at the zeroth index, we already assigned the value 5." }, { "code": null, "e": 3243, "s": 3224, "text": "Types of arrays : " }, { "code": null, "e": 3300, "s": 3243, "text": "One dimensional array (1-D arrays)Multidimensional array" }, { "code": null, "e": 3335, "s": 3300, "text": "One dimensional array (1-D arrays)" }, { "code": null, "e": 3358, "s": 3335, "text": "Multidimensional array" }, { "code": null, "e": 3387, "s": 3358, "text": "Advantages of using arrays: " }, { "code": null, "e": 3477, "s": 3387, "text": "Arrays allow random access to elements. This makes accessing elements by position faster." }, { "code": null, "e": 3563, "s": 3477, "text": "Arrays have better cache locality which makes a pretty big difference in performance." }, { "code": null, "e": 3638, "s": 3563, "text": "Arrays represent multiple data items of the same type using a single name." }, { "code": null, "e": 4143, "s": 3638, "text": "Disadvantages of using arrays: You can’t change the size i.e. once you have declared the array you can’t change its size because of static memory allocation. Here Insertion(s) and deletion(s) are difficult as the elements are stored in consecutive memory locations and the shifting operation is costly too.Now if take an example of the implementation of data structure Stack using array there are some obvious flaws. Let’s take the POP operation of the stack. The algorithm would go something like this. " }, { "code": null, "e": 4195, "s": 4143, "text": "Check for the stack underflowDecrement the top by 1" }, { "code": null, "e": 4225, "s": 4195, "text": "Check for the stack underflow" }, { "code": null, "e": 4248, "s": 4225, "text": "Decrement the top by 1" }, { "code": null, "e": 4593, "s": 4248, "text": "What we are doing here is, that the pointer to the topmost element is decremented, which means we are just bounding our view, and actually that element stays there taking up the memory space. If you have an array (as a Stack) of any primitive data type then it might be ok. But in the case of an array of Objects, it would take a lot of memory." }, { "code": null, "e": 4605, "s": 4593, "text": "Examples – " }, { "code": null, "e": 4680, "s": 4605, "text": "// A character array in C/C++/Javachar arr1[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’};" }, { "code": null, "e": 4748, "s": 4680, "text": "// An Integer array in C/C++/Javaint arr2[] = {10, 20, 30, 40, 50};" }, { "code": null, "e": 4867, "s": 4748, "text": "// Item at i’th index in array is typically accessed as “arr[i]”. For example:arr1[0] gives us ‘g’arr2[3] gives us 40" }, { "code": null, "e": 4983, "s": 4867, "text": "Usually, an array of characters is called a ‘string’, whereas an array of ints or floats is simply called an array." }, { "code": null, "e": 5005, "s": 4983, "text": "Applications on Array" }, { "code": null, "e": 5055, "s": 5005, "text": "Array stores data elements of the same data type." }, { "code": null, "e": 5111, "s": 5055, "text": "Arrays are used when the size of the data set is known." }, { "code": null, "e": 5144, "s": 5111, "text": "Used in solving matrix problems." }, { "code": null, "e": 5183, "s": 5144, "text": "Applied as a lookup table in computer." }, { "code": null, "e": 5236, "s": 5183, "text": "Databases records are also implemented by the array." }, { "code": null, "e": 5277, "s": 5236, "text": "Helps in implementing sorting algorithm." }, { "code": null, "e": 5347, "s": 5277, "text": "The different variables of the same type can be saved under one name." }, { "code": null, "e": 5386, "s": 5347, "text": "Arrays can be used for CPU scheduling." }, { "code": null, "e": 5472, "s": 5386, "text": "Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc." }, { "code": null, "e": 5852, "s": 5472, "text": "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 if you want to share more information about the topic discussed above. " }, { "code": null, "e": 5869, "s": 5852, "text": "Shubhamlamichane" }, { "code": null, "e": 5883, "s": 5869, "text": "EmperorFlames" }, { "code": null, "e": 5895, "s": 5883, "text": "AayushDiwan" }, { "code": null, "e": 5912, "s": 5895, "text": "mishraakshat2610" }, { "code": null, "e": 5927, "s": 5912, "text": "gupta_shrinath" }, { "code": null, "e": 5945, "s": 5927, "text": "soumyasambitkunda" }, { "code": null, "e": 5956, "s": 5945, "text": "surabhiraj" }, { "code": null, "e": 5971, "s": 5956, "text": "amanandaman007" }, { "code": null, "e": 5982, "s": 5971, "text": "ayush933as" }, { "code": null, "e": 5995, "s": 5982, "text": "aishasartaj1" }, { "code": null, "e": 6012, "s": 5995, "text": "pragalbhmishra12" }, { "code": null, "e": 6022, "s": 6012, "text": "shapnesht" }, { "code": null, "e": 6032, "s": 6022, "text": "vishwa_63" }, { "code": null, "e": 6038, "s": 6032, "text": "Angad" }, { "code": null, "e": 6054, "s": 6038, "text": "hrithikmanoj000" }, { "code": null, "e": 6069, "s": 6054, "text": "guptavivek0503" }, { "code": null, "e": 6079, "s": 6069, "text": "muditj148" }, { "code": null, "e": 6094, "s": 6079, "text": "mohitmjaisingh" }, { "code": null, "e": 6106, "s": 6094, "text": "aayushi2402" }, { "code": null, "e": 6113, "s": 6106, "text": "Arrays" }, { "code": null, "e": 6120, "s": 6113, "text": "Arrays" }, { "code": null, "e": 6218, "s": 6120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6233, "s": 6218, "text": "Arrays in Java" }, { "code": null, "e": 6279, "s": 6233, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6347, "s": 6279, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6391, "s": 6347, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 6423, "s": 6391, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 6439, "s": 6423, "text": "Arrays in C/C++" }, { "code": null, "e": 6471, "s": 6439, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6519, "s": 6471, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 6533, "s": 6519, "text": "Linear Search" } ]
Sum of all proper divisors of a natural number
23 Jun, 2022 Given a natural number, calculate sum of all its proper divisors. A proper divisor of a natural number is the divisor that is strictly less than the number. For example, number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.Examples : Input : num = 10 Output: 8 // proper divisors 1 + 2 + 5 = 8 Input : num = 36 Output: 55 // proper divisors 1 + 2 + 3 + 4 + 6 + 9 + 12 + 18 = 55 This problem has very simple solution, we all know that for any number ‘num’ all its divisors are always less than and equal to ‘num/2’ and all prime factors are always less than and equal to sqrt(num). So we iterate through ‘i’ till i<=sqrt(num) and for any ‘i’ if it divides ‘num’ , then we get two divisors ‘i’ and ‘num/i’ , continuously add these divisors but for some numbers divisors ‘i’ and ‘num/i’ will same in this case just add only one divisor , e.g; num=36 so for i=6 we will get (num/i)=6 , that’s why we will at 6 in the summation only once. Finally we add one as one is divisor of all natural numbers. C++ Java Python3 C# PHP Javascript // C++ program to find sum of all divisors of// a natural number#include<bits/stdc++.h>using namespace std; // Function to calculate sum of all proper divisors// num --> given natural numberint divSum(int num){ // Final result of summation of divisors int result = 0; if(num == 1) // there will be no proper divisor return result; // find all divisors which divides 'num' for (int i=2; i<=sqrt(num); i++) { // if 'i' is divisor of 'num' if (num%i==0) { // if both divisors are same then add // it only once else add both if (i==(num/i)) result += i; else result += (i + num/i); } } // Add 1 to the result as 1 is also a divisor return (result + 1);} // Driver program to run the caseint main(){ int num = 36; cout << divSum(num); return 0;} // JAVA program to find sum of all divisors// of a natural numberimport java.math.*; class GFG { // Function to calculate sum of all proper // divisors num --> given natural number static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then // add it only once else add both if (i == (num / i)) result += i; else result += (i + num / i); } } // Add 1 to the result as 1 is also // a divisor return (result + 1); } // Driver program to run the case public static void main(String[] args) { int num = 36; System.out.println(divSum(num)); }} /*This code is contributed by Nikita Tiwari*/ # PYTHON program to find sum of all# divisors of a natural numberimport math # Function to calculate sum of all proper# divisors num --> given natural numberdef divSum(num) : # Final result of summation of divisors result = 0 # find all divisors which divides 'num' i = 2 while i<= (math.sqrt(num)) : # if 'i' is divisor of 'num' if (num % i == 0) : # if both divisors are same then # add it only once else add both if (i == (num / i)) : result = result + i; else : result = result + (i + num/i); i = i + 1 # Add 1 to the result as 1 is also # a divisor return (result + 1); # Driver program to run the casenum = 36print (divSum(num)) # This code is contributed by Nikita Tiwari // C# program to find sum of all// divisorsof a natural numberusing System; class GFG { // Function to calculate sum of all proper // divisors num --> given natural number static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.Sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then // add it only once else add both if (i == (num / i)) result += i; else result += (i + num / i); } } // Add 1 to the result as 1 // is also a divisor return (result + 1); } // Driver Code public static void Main() { int num = 36; Console.Write(divSum(num)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to find sum of// all divisors of a natural number // Function to calculate sum of// all proper divisors// num --> given natural numberfunction divSum($num){ // Final result of // summation of divisors $result = 0; // find all divisors // which divides 'num' for ($i = 2; $i <= sqrt($num); $i++) { // if 'i' is divisor of 'num' if ($num % $i == 0) { // if both divisors are // same then add it only // once else add both if ($i == ($num / $i)) $result += $i; else $result += ($i + $num / $i); } } // Add 1 to the result as // 1 is also a divisor return ($result + 1);} // Driver Code$num = 36;echo(divSum($num)); // This code is contributed by Ajit.?> <script> // Javascript program to find sum of all divisors of// a natural number // Function to calculate sum of all proper divisors// num --> given natural numberfunction divSum(num){ // Final result of summation of divisors let result = 0; // find all divisors which divides 'num' for (let i=2; i<=Math.sqrt(num); i++) { // if 'i' is divisor of 'num' if (num%i==0) { // if both divisors are same then add // it only once else add both if (i==(num/i)) result += i; else result += (i + num/i); } } // Add 1 to the result as 1 is also a divisor return (result + 1);} // Driver program to run the case let num = 36; document.write(divSum(num)); // This code is contributed by Mayank Tyagi </script> Output : 55 Time Complexity: O(√n) Auxiliary Space: O(1) Please refer below post for an optimized solution and formula. Efficient solution for sum of all the factors of a numberThis article is contributed by Aarti_Rathi and Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. nitin mittal jit_t mayanktyagi1709 itshimanshu amartyaghoshgfg codewithshinchan divisors number-theory prime-factor Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 338, "s": 52, "text": "Given a natural number, calculate sum of all its proper divisors. A proper divisor of a natural number is the divisor that is strictly less than the number. For example, number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.Examples : " }, { "code": null, "e": 485, "s": 338, "text": "Input : num = 10\nOutput: 8\n// proper divisors 1 + 2 + 5 = 8 \n\nInput : num = 36\nOutput: 55\n// proper divisors 1 + 2 + 3 + 4 + 6 + 9 + 12 + 18 = 55 " }, { "code": null, "e": 1105, "s": 487, "text": "This problem has very simple solution, we all know that for any number ‘num’ all its divisors are always less than and equal to ‘num/2’ and all prime factors are always less than and equal to sqrt(num). So we iterate through ‘i’ till i<=sqrt(num) and for any ‘i’ if it divides ‘num’ , then we get two divisors ‘i’ and ‘num/i’ , continuously add these divisors but for some numbers divisors ‘i’ and ‘num/i’ will same in this case just add only one divisor , e.g; num=36 so for i=6 we will get (num/i)=6 , that’s why we will at 6 in the summation only once. Finally we add one as one is divisor of all natural numbers. " }, { "code": null, "e": 1109, "s": 1105, "text": "C++" }, { "code": null, "e": 1114, "s": 1109, "text": "Java" }, { "code": null, "e": 1122, "s": 1114, "text": "Python3" }, { "code": null, "e": 1125, "s": 1122, "text": "C#" }, { "code": null, "e": 1129, "s": 1125, "text": "PHP" }, { "code": null, "e": 1140, "s": 1129, "text": "Javascript" }, { "code": "// C++ program to find sum of all divisors of// a natural number#include<bits/stdc++.h>using namespace std; // Function to calculate sum of all proper divisors// num --> given natural numberint divSum(int num){ // Final result of summation of divisors int result = 0; if(num == 1) // there will be no proper divisor return result; // find all divisors which divides 'num' for (int i=2; i<=sqrt(num); i++) { // if 'i' is divisor of 'num' if (num%i==0) { // if both divisors are same then add // it only once else add both if (i==(num/i)) result += i; else result += (i + num/i); } } // Add 1 to the result as 1 is also a divisor return (result + 1);} // Driver program to run the caseint main(){ int num = 36; cout << divSum(num); return 0;}", "e": 2025, "s": 1140, "text": null }, { "code": "// JAVA program to find sum of all divisors// of a natural numberimport java.math.*; class GFG { // Function to calculate sum of all proper // divisors num --> given natural number static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then // add it only once else add both if (i == (num / i)) result += i; else result += (i + num / i); } } // Add 1 to the result as 1 is also // a divisor return (result + 1); } // Driver program to run the case public static void main(String[] args) { int num = 36; System.out.println(divSum(num)); }} /*This code is contributed by Nikita Tiwari*/", "e": 3074, "s": 2025, "text": null }, { "code": "# PYTHON program to find sum of all# divisors of a natural numberimport math # Function to calculate sum of all proper# divisors num --> given natural numberdef divSum(num) : # Final result of summation of divisors result = 0 # find all divisors which divides 'num' i = 2 while i<= (math.sqrt(num)) : # if 'i' is divisor of 'num' if (num % i == 0) : # if both divisors are same then # add it only once else add both if (i == (num / i)) : result = result + i; else : result = result + (i + num/i); i = i + 1 # Add 1 to the result as 1 is also # a divisor return (result + 1); # Driver program to run the casenum = 36print (divSum(num)) # This code is contributed by Nikita Tiwari", "e": 3911, "s": 3074, "text": null }, { "code": "// C# program to find sum of all// divisorsof a natural numberusing System; class GFG { // Function to calculate sum of all proper // divisors num --> given natural number static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.Sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then // add it only once else add both if (i == (num / i)) result += i; else result += (i + num / i); } } // Add 1 to the result as 1 // is also a divisor return (result + 1); } // Driver Code public static void Main() { int num = 36; Console.Write(divSum(num)); }} // This code is contributed by Nitin Mittal.", "e": 4949, "s": 3911, "text": null }, { "code": "<?php// PHP program to find sum of// all divisors of a natural number // Function to calculate sum of// all proper divisors// num --> given natural numberfunction divSum($num){ // Final result of // summation of divisors $result = 0; // find all divisors // which divides 'num' for ($i = 2; $i <= sqrt($num); $i++) { // if 'i' is divisor of 'num' if ($num % $i == 0) { // if both divisors are // same then add it only // once else add both if ($i == ($num / $i)) $result += $i; else $result += ($i + $num / $i); } } // Add 1 to the result as // 1 is also a divisor return ($result + 1);} // Driver Code$num = 36;echo(divSum($num)); // This code is contributed by Ajit.?>", "e": 5784, "s": 4949, "text": null }, { "code": "<script> // Javascript program to find sum of all divisors of// a natural number // Function to calculate sum of all proper divisors// num --> given natural numberfunction divSum(num){ // Final result of summation of divisors let result = 0; // find all divisors which divides 'num' for (let i=2; i<=Math.sqrt(num); i++) { // if 'i' is divisor of 'num' if (num%i==0) { // if both divisors are same then add // it only once else add both if (i==(num/i)) result += i; else result += (i + num/i); } } // Add 1 to the result as 1 is also a divisor return (result + 1);} // Driver program to run the case let num = 36; document.write(divSum(num)); // This code is contributed by Mayank Tyagi </script>", "e": 6624, "s": 5784, "text": null }, { "code": null, "e": 6634, "s": 6624, "text": "Output : " }, { "code": null, "e": 6637, "s": 6634, "text": "55" }, { "code": null, "e": 6682, "s": 6637, "text": "Time Complexity: O(√n) Auxiliary Space: O(1)" }, { "code": null, "e": 7257, "s": 6682, "text": "Please refer below post for an optimized solution and formula. Efficient solution for sum of all the factors of a numberThis article is contributed by Aarti_Rathi and Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 7270, "s": 7257, "text": "nitin mittal" }, { "code": null, "e": 7276, "s": 7270, "text": "jit_t" }, { "code": null, "e": 7292, "s": 7276, "text": "mayanktyagi1709" }, { "code": null, "e": 7304, "s": 7292, "text": "itshimanshu" }, { "code": null, "e": 7320, "s": 7304, "text": "amartyaghoshgfg" }, { "code": null, "e": 7337, "s": 7320, "text": "codewithshinchan" }, { "code": null, "e": 7346, "s": 7337, "text": "divisors" }, { "code": null, "e": 7360, "s": 7346, "text": "number-theory" }, { "code": null, "e": 7373, "s": 7360, "text": "prime-factor" }, { "code": null, "e": 7386, "s": 7373, "text": "Mathematical" }, { "code": null, "e": 7400, "s": 7386, "text": "number-theory" }, { "code": null, "e": 7413, "s": 7400, "text": "Mathematical" }, { "code": null, "e": 7511, "s": 7413, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7541, "s": 7511, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7584, "s": 7541, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7644, "s": 7584, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7659, "s": 7644, "text": "C++ Data Types" }, { "code": null, "e": 7683, "s": 7659, "text": "Merge two sorted arrays" }, { "code": null, "e": 7702, "s": 7683, "text": "Coin Change | DP-7" }, { "code": null, "e": 7723, "s": 7702, "text": "Operators in C / C++" }, { "code": null, "e": 7737, "s": 7723, "text": "Prime Numbers" }, { "code": null, "e": 7779, "s": 7737, "text": "Program to find GCD or HCF of two numbers" } ]
Find middle of singly linked list Recursively
21 Jun, 2021 Given a singly linked list and the task is to find the middle of the linked list. Examples: Input : 1->2->3->4->5 Output : 3 Input : 1->2->3->4->5->6 Output : 4 We have already discussed Iterative Solution. In this post iterative solution is discussed. Count total number of nodes in the list in recursive manner and do half of this, suppose this value is n. Then rolling back through recursion decrement n by one for each call. Return the node where n is zero. C++ Java Python3 C# Javascript // C++ program for Recursive approach to find// middle of singly linked list#include <iostream>using namespace std; // Tree Node Structurestruct Node{ int data; struct Node* next;}; // Create new NodeNode* newLNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Function for finding midpoint recursivelyvoid midpoint_util(Node* head, int* n, Node** mid){ // If we reached end of linked list if (head == NULL) { *n = (*n) / 2; return; } *n = *n + 1; midpoint_util(head->next, n, mid); // Rolling back, decrement n by one *n = *n - 1; if (*n == 0) { // Final answer *mid = head; }} Node* midpoint(Node* head){ Node* mid = NULL; int n = 1; midpoint_util(head, &n, &mid); return mid;} int main(){ Node* head = newLNode(1); head->next = newLNode(2); head->next->next = newLNode(3); head->next->next->next = newLNode(4); head->next->next->next->next = newLNode(5); Node* result = midpoint(head); cout << result->data << endl; return 0;} // Java program for Recursive approach to find// middle of singly linked listclass GFG{ // Tree Node Structurestatic class Node{ int data; Node next;}; // Create new Nodestatic Node newLNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} static int n;static Node mid; // Function for finding midpoint recursivelystatic void midpoint_util(Node head ){ // If we reached end of linked list if (head == null) { n = (n) / 2; return; } n = n + 1; midpoint_util(head.next); // Rolling back, decrement n by one n = n - 1; if (n == 0) { // Final answer mid = head; }} static Node midpoint(Node head){ mid = null; n = 1; midpoint_util(head); return mid;} // Driver codepublic static void main(String args[]){ Node head = newLNode(1); head.next = newLNode(2); head.next.next = newLNode(3); head.next.next.next = newLNode(4); head.next.next.next.next = newLNode(5); Node result = midpoint(head); System.out.print( result.data );}} // This code is contributed by Arnab Kundu # Python3 program for Recursive approach# to find middle of singly linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data self.next = None # Create new Nodedef newLNode(data): temp = Node(data) temp.data = data temp.next = None return temp mid = Nonen = 0 # Function for finding midpoint recursivelydef midpoint_util(head ): global n global mid # If we reached end of linked list if (head == None): n = int((n) / 2) return n = n + 1 midpoint_util(head.next) # Rolling back, decrement n by one n = n - 1 if (n == 0): # Final answer mid = head def midpoint(head): global n global mid mid = None n = 1 midpoint_util(head) return mid # Driver Codeif __name__=='__main__': head = newLNode(1) head.next = newLNode(2) head.next.next = newLNode(3) head.next.next.next = newLNode(4) head.next.next.next.next = newLNode(5) result = midpoint(head) print( result.data ) # This code is contributed by Arnab Kundu // C# program for Recursive approach to find// middle of singly linked listusing System;class GFG{ // Tree Node Structurepublic class Node{ public int data; public Node next;}; // Create new Nodestatic Node newLNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} static int n;static Node mid; // Function for finding midpoint recursivelystatic void midpoint_util(Node head ){ // If we reached end of linked list if (head == null) { n = (n) / 2; return; } n = n + 1; midpoint_util(head.next); // Rolling back, decrement n by one n = n - 1; if (n == 0) { // Final answer mid = head; }} static Node midpoint(Node head){ mid = null; n = 1; midpoint_util(head); return mid;} // Driver codepublic static void Main(){ Node head = newLNode(1); head.next = newLNode(2); head.next.next = newLNode(3); head.next.next.next = newLNode(4); head.next.next.next.next = newLNode(5); Node result = midpoint(head); Console.WriteLine( result.data );}} // This code is contributed by Rajput-Ji <script> // JavaScript program for Recursive approach to find// middle of singly linked list // Tree Node Structureclass Node{ constructor() { this.data = 0; this.next = null; }}; // Create new Nodefunction newLNode(data){ var temp = new Node(); temp.data = data; temp.next = null; return temp;} var n = 0;var mid = null;; // Function for finding midpoint recursivelyfunction midpoint_util(head){ // If we reached end of linked list if (head == null) { n = (n) / 2; return; } n = n + 1; midpoint_util(head.next); // Rolling back, decrement n by one n = n - 1; if (n == 0) { // Final answer mid = head; }} function midpoint(head){ mid = null; n = 1; midpoint_util(head); return mid;} // Driver codevar head = newLNode(1);head.next = newLNode(2);head.next.next = newLNode(3);head.next.next.next = newLNode(4);head.next.next.next.next = newLNode(5);var result = midpoint(head);document.write( result.data ); </script> Output: 3 andrew1234 Rajput-Ji noob2000 Linked List Recursion Linked List Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Rearrange a given linked list in-place. Types of Linked List Find first node of loop in a linked list Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2021" }, { "code": null, "e": 146, "s": 52, "text": "Given a singly linked list and the task is to find the middle of the linked list. Examples: " }, { "code": null, "e": 220, "s": 146, "text": "Input : 1->2->3->4->5 \nOutput : 3\n\nInput : 1->2->3->4->5->6\nOutput : 4" }, { "code": null, "e": 525, "s": 222, "text": "We have already discussed Iterative Solution. In this post iterative solution is discussed. Count total number of nodes in the list in recursive manner and do half of this, suppose this value is n. Then rolling back through recursion decrement n by one for each call. Return the node where n is zero. " }, { "code": null, "e": 529, "s": 525, "text": "C++" }, { "code": null, "e": 534, "s": 529, "text": "Java" }, { "code": null, "e": 542, "s": 534, "text": "Python3" }, { "code": null, "e": 545, "s": 542, "text": "C#" }, { "code": null, "e": 556, "s": 545, "text": "Javascript" }, { "code": "// C++ program for Recursive approach to find// middle of singly linked list#include <iostream>using namespace std; // Tree Node Structurestruct Node{ int data; struct Node* next;}; // Create new NodeNode* newLNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Function for finding midpoint recursivelyvoid midpoint_util(Node* head, int* n, Node** mid){ // If we reached end of linked list if (head == NULL) { *n = (*n) / 2; return; } *n = *n + 1; midpoint_util(head->next, n, mid); // Rolling back, decrement n by one *n = *n - 1; if (*n == 0) { // Final answer *mid = head; }} Node* midpoint(Node* head){ Node* mid = NULL; int n = 1; midpoint_util(head, &n, &mid); return mid;} int main(){ Node* head = newLNode(1); head->next = newLNode(2); head->next->next = newLNode(3); head->next->next->next = newLNode(4); head->next->next->next->next = newLNode(5); Node* result = midpoint(head); cout << result->data << endl; return 0;}", "e": 1649, "s": 556, "text": null }, { "code": "// Java program for Recursive approach to find// middle of singly linked listclass GFG{ // Tree Node Structurestatic class Node{ int data; Node next;}; // Create new Nodestatic Node newLNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} static int n;static Node mid; // Function for finding midpoint recursivelystatic void midpoint_util(Node head ){ // If we reached end of linked list if (head == null) { n = (n) / 2; return; } n = n + 1; midpoint_util(head.next); // Rolling back, decrement n by one n = n - 1; if (n == 0) { // Final answer mid = head; }} static Node midpoint(Node head){ mid = null; n = 1; midpoint_util(head); return mid;} // Driver codepublic static void main(String args[]){ Node head = newLNode(1); head.next = newLNode(2); head.next.next = newLNode(3); head.next.next.next = newLNode(4); head.next.next.next.next = newLNode(5); Node result = midpoint(head); System.out.print( result.data );}} // This code is contributed by Arnab Kundu", "e": 2766, "s": 1649, "text": null }, { "code": "# Python3 program for Recursive approach# to find middle of singly linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data self.next = None # Create new Nodedef newLNode(data): temp = Node(data) temp.data = data temp.next = None return temp mid = Nonen = 0 # Function for finding midpoint recursivelydef midpoint_util(head ): global n global mid # If we reached end of linked list if (head == None): n = int((n) / 2) return n = n + 1 midpoint_util(head.next) # Rolling back, decrement n by one n = n - 1 if (n == 0): # Final answer mid = head def midpoint(head): global n global mid mid = None n = 1 midpoint_util(head) return mid # Driver Codeif __name__=='__main__': head = newLNode(1) head.next = newLNode(2) head.next.next = newLNode(3) head.next.next.next = newLNode(4) head.next.next.next.next = newLNode(5) result = midpoint(head) print( result.data ) # This code is contributed by Arnab Kundu", "e": 3905, "s": 2766, "text": null }, { "code": "// C# program for Recursive approach to find// middle of singly linked listusing System;class GFG{ // Tree Node Structurepublic class Node{ public int data; public Node next;}; // Create new Nodestatic Node newLNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} static int n;static Node mid; // Function for finding midpoint recursivelystatic void midpoint_util(Node head ){ // If we reached end of linked list if (head == null) { n = (n) / 2; return; } n = n + 1; midpoint_util(head.next); // Rolling back, decrement n by one n = n - 1; if (n == 0) { // Final answer mid = head; }} static Node midpoint(Node head){ mid = null; n = 1; midpoint_util(head); return mid;} // Driver codepublic static void Main(){ Node head = newLNode(1); head.next = newLNode(2); head.next.next = newLNode(3); head.next.next.next = newLNode(4); head.next.next.next.next = newLNode(5); Node result = midpoint(head); Console.WriteLine( result.data );}} // This code is contributed by Rajput-Ji", "e": 5033, "s": 3905, "text": null }, { "code": "<script> // JavaScript program for Recursive approach to find// middle of singly linked list // Tree Node Structureclass Node{ constructor() { this.data = 0; this.next = null; }}; // Create new Nodefunction newLNode(data){ var temp = new Node(); temp.data = data; temp.next = null; return temp;} var n = 0;var mid = null;; // Function for finding midpoint recursivelyfunction midpoint_util(head){ // If we reached end of linked list if (head == null) { n = (n) / 2; return; } n = n + 1; midpoint_util(head.next); // Rolling back, decrement n by one n = n - 1; if (n == 0) { // Final answer mid = head; }} function midpoint(head){ mid = null; n = 1; midpoint_util(head); return mid;} // Driver codevar head = newLNode(1);head.next = newLNode(2);head.next.next = newLNode(3);head.next.next.next = newLNode(4);head.next.next.next.next = newLNode(5);var result = midpoint(head);document.write( result.data ); </script>", "e": 6061, "s": 5033, "text": null }, { "code": null, "e": 6071, "s": 6061, "text": "Output: " }, { "code": null, "e": 6073, "s": 6071, "text": "3" }, { "code": null, "e": 6086, "s": 6075, "text": "andrew1234" }, { "code": null, "e": 6096, "s": 6086, "text": "Rajput-Ji" }, { "code": null, "e": 6105, "s": 6096, "text": "noob2000" }, { "code": null, "e": 6117, "s": 6105, "text": "Linked List" }, { "code": null, "e": 6127, "s": 6117, "text": "Recursion" }, { "code": null, "e": 6139, "s": 6127, "text": "Linked List" }, { "code": null, "e": 6149, "s": 6139, "text": "Recursion" }, { "code": null, "e": 6247, "s": 6149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6279, "s": 6247, "text": "Introduction to Data Structures" }, { "code": null, "e": 6343, "s": 6279, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6383, "s": 6343, "text": "Rearrange a given linked list in-place." }, { "code": null, "e": 6404, "s": 6383, "text": "Types of Linked List" }, { "code": null, "e": 6445, "s": 6404, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 6505, "s": 6445, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6590, "s": 6505, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 6600, "s": 6590, "text": "Recursion" }, { "code": null, "e": 6627, "s": 6600, "text": "Program for Tower of Hanoi" } ]
Find strings that end with a given suffix
16 Jun, 2022 Given a set of strings S and a string P, the task is to print all strings from the set with suffix P. Examples: Input: S = {“geeks”, “geeksforgeeks”, “geek”, “newgeeks”, “friendsongeeks”, “toppergeek”} P = “geeks” Output: geeks friendsongeeks geeksforgeeks newgeeks Input: S = {“wideworld”, “webworld”, “classicword”, “world”, “worldclass”} P = “world” Output: wideworld webworld world Approach: The idea is to use Pattern Searching using a Trie of all Suffixes. Store the strings in a Trie in reverse order. Reverse the string P and search for it using standard Trie search algorithm. Check if the reversed string P is itself a word in Trie, which be checked by seeing if the last matching node has isEndWord flag set. Otherwise if the reversed string P forms a suffix, then recursively print all nodes under the subtree of last matching node. Below is the implementation of the above approach: C++ Python // C++ code to print all// strings from a given set// with suffix P#include <bits/stdc++.h>using namespace std; #define CHILD (26) // Converts key current character// into index use only 'a' through// 'z' and lower case#define CHAR_TO_INDEX(c) (int)(c - 'a') // Trie nodestruct TrieNode { struct TrieNode* children[CHILD]; // isWordEnd is true if the node // represents end of a word bool isWordEnd;}; // Function to reverse a stringstring reverseStr(string str){ int n = str.length(); // Swap character starting from // two corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); return str;} // Returns new trie nodestruct TrieNode* getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isWordEnd = false; for (int i = 0; i < CHILD; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into// trie. If the key is suffix of trie// node, just mark leaf nodevoid insert(struct TrieNode* root, const string key){ struct TrieNode* pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // Mark last node as leaf pCrawl->isWordEnd = true;} // Returns true if key presents in// the trie, else falsebool search(struct TrieNode* root, const string key){ int length = key.length(); struct TrieNode* pCrawl = root; for (int level = 0; level < length; level++) { int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isWordEnd);} // Returns 0 if current node has// a child// If all children are NULL, return 1bool isLastNode(struct TrieNode* root){ for (int i = 0; i < CHILD; i++) if (root->children[i]) return 0; return 1;} // Recursive function to print strings// having given suffixvoid printStrings(struct TrieNode* root, string currsuffix){ // If a string with currsuffix // is found if (root->isWordEnd) { cout << reverseStr(currsuffix); cout << endl; reverseStr(currsuffix); } // All children struct node // pointers are NULL if (isLastNode(root)) return; for (int i = 0; i < CHILD; i++) { if (root->children[i]) { // Append current character // to currsuffix string currsuffix.push_back(97 + i); // recur over the rest printStrings(root->children[i], currsuffix); // remove last character currsuffix.pop_back(); } }} // print strings with given suffixint printStringsWithGivenSuffix( TrieNode* root, const string query){ struct TrieNode* pCrawl = root; // Check if suffix is present // and find the node (of last // level) with last character // of given string. int level; int n = query.length(); for (level = 0; level < n; level++) { int index = CHAR_TO_INDEX(query[level]); // no string in the Trie has // this suffix if (!pCrawl->children[index]) return 0; pCrawl = pCrawl->children[index]; } // If suffix is present as a word. bool isWord = (pCrawl->isWordEnd == true); // If suffix is last node of // tree (has no children) bool isLast = isLastNode(pCrawl); // If suffix is present as a word, // but there is no subtree below // the last matching node. if (isWord && isLast) { cout << query << endl; return -1; } // If there are nodes below // last matching character. if (!isLast) { string suffix = query; printStrings(pCrawl, suffix); return 1; }} // Driver Codeint main(){ struct TrieNode* root = getNode(); vector<string> S = { "geeks", "geeksforgeeks", "geek", "newgeeks", "friendsongeeks", "toppergeek" }; for (string str : S) { insert(root, reverseStr(str)); } string P = "eek"; printStringsWithGivenSuffix( root, reverseStr(P)); return 0;} # Python3 code for the above programclass TrieNode(): def __init__(self): # Initialize one node for trie self.children = {} self.last = False def reverse(s): str = "" for i in s: str = i + str return str class Trie(): def __init__(self): # Initialize the trie structure self.root = TrieNode() self.word_list = [] def formTrie(self, keys): # Forms a trie structure # with the given set of # strings if it does not # exists already else it # merges the key into it # by extending the # structure as required for key in keys: # inserting one key # to the trie. self.insert(key) def insert(self, key): # Inserts a key into # trie if it does not # exist already. And if # the key is a suffix # of the trie node, just # marks it as leaf node. node = self.root for a in list(key): if not node.children.get(a): node.children[a] = TrieNode() node = node.children[a] node.last = True def search(self, key): # Searches the given key # in trie for a full match # and returns True on # success else returns False node = self.root found = True for a in list(key): if not node.children.get(a): found = False break node = node.children[a] return node and node.last and found def printStrings(self, node, word): # Method to recursively # traverse the trie # and return a whole word if node.last: self.word_list.append(word) for a, n in node.children.items(): self.printStrings(n, word + a) def printStringsWithGivenSuffix(self, key): # Returns all the words in # the trie whose common # suffix is the given key # thus listing out all # the strings node = self.root not_found = False temp_word = '' for a in list(key): if not node.children.get(a): not_found = True break temp_word += a node = node.children[a] if not_found: return 0 elif node.last and not node.children: return -1 self.printStrings(node, temp_word) for s in self.word_list: print(reverse(s)) return 1 # Driver Code # keys to form the trie structurekeys = [reverse("geeks"),reverse("geeksforgeeks"),reverse("geek"),reverse("newgeeks"),reverse("friendsongeeks"),reverse("toppergeek")] # keykey = "eek"status = ["Not found", "Found"] # creating trie objectt = Trie() # creating the trie structure# with the given set of stringst.formTrie(keys) # print string having suffix 'P'# our trie structurecomp = t.printStringsWithGivenSuffix(reverse(key)) geek toppergeek s simmytarika5 Suffix Trie Advanced Data Structure Pattern Searching Strings Strings Pattern Searching Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 164, "s": 52, "text": "Given a set of strings S and a string P, the task is to print all strings from the set with suffix P. Examples:" }, { "code": null, "e": 438, "s": 164, "text": "Input: S = {“geeks”, “geeksforgeeks”, “geek”, “newgeeks”, “friendsongeeks”, “toppergeek”} P = “geeks” Output: geeks friendsongeeks geeksforgeeks newgeeks Input: S = {“wideworld”, “webworld”, “classicword”, “world”, “worldclass”} P = “world” Output: wideworld webworld world" }, { "code": null, "e": 515, "s": 438, "text": "Approach: The idea is to use Pattern Searching using a Trie of all Suffixes." }, { "code": null, "e": 561, "s": 515, "text": "Store the strings in a Trie in reverse order." }, { "code": null, "e": 638, "s": 561, "text": "Reverse the string P and search for it using standard Trie search algorithm." }, { "code": null, "e": 772, "s": 638, "text": "Check if the reversed string P is itself a word in Trie, which be checked by seeing if the last matching node has isEndWord flag set." }, { "code": null, "e": 897, "s": 772, "text": "Otherwise if the reversed string P forms a suffix, then recursively print all nodes under the subtree of last matching node." }, { "code": null, "e": 949, "s": 897, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 953, "s": 949, "text": "C++" }, { "code": null, "e": 960, "s": 953, "text": "Python" }, { "code": "// C++ code to print all// strings from a given set// with suffix P#include <bits/stdc++.h>using namespace std; #define CHILD (26) // Converts key current character// into index use only 'a' through// 'z' and lower case#define CHAR_TO_INDEX(c) (int)(c - 'a') // Trie nodestruct TrieNode { struct TrieNode* children[CHILD]; // isWordEnd is true if the node // represents end of a word bool isWordEnd;}; // Function to reverse a stringstring reverseStr(string str){ int n = str.length(); // Swap character starting from // two corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); return str;} // Returns new trie nodestruct TrieNode* getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isWordEnd = false; for (int i = 0; i < CHILD; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into// trie. If the key is suffix of trie// node, just mark leaf nodevoid insert(struct TrieNode* root, const string key){ struct TrieNode* pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // Mark last node as leaf pCrawl->isWordEnd = true;} // Returns true if key presents in// the trie, else falsebool search(struct TrieNode* root, const string key){ int length = key.length(); struct TrieNode* pCrawl = root; for (int level = 0; level < length; level++) { int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isWordEnd);} // Returns 0 if current node has// a child// If all children are NULL, return 1bool isLastNode(struct TrieNode* root){ for (int i = 0; i < CHILD; i++) if (root->children[i]) return 0; return 1;} // Recursive function to print strings// having given suffixvoid printStrings(struct TrieNode* root, string currsuffix){ // If a string with currsuffix // is found if (root->isWordEnd) { cout << reverseStr(currsuffix); cout << endl; reverseStr(currsuffix); } // All children struct node // pointers are NULL if (isLastNode(root)) return; for (int i = 0; i < CHILD; i++) { if (root->children[i]) { // Append current character // to currsuffix string currsuffix.push_back(97 + i); // recur over the rest printStrings(root->children[i], currsuffix); // remove last character currsuffix.pop_back(); } }} // print strings with given suffixint printStringsWithGivenSuffix( TrieNode* root, const string query){ struct TrieNode* pCrawl = root; // Check if suffix is present // and find the node (of last // level) with last character // of given string. int level; int n = query.length(); for (level = 0; level < n; level++) { int index = CHAR_TO_INDEX(query[level]); // no string in the Trie has // this suffix if (!pCrawl->children[index]) return 0; pCrawl = pCrawl->children[index]; } // If suffix is present as a word. bool isWord = (pCrawl->isWordEnd == true); // If suffix is last node of // tree (has no children) bool isLast = isLastNode(pCrawl); // If suffix is present as a word, // but there is no subtree below // the last matching node. if (isWord && isLast) { cout << query << endl; return -1; } // If there are nodes below // last matching character. if (!isLast) { string suffix = query; printStrings(pCrawl, suffix); return 1; }} // Driver Codeint main(){ struct TrieNode* root = getNode(); vector<string> S = { \"geeks\", \"geeksforgeeks\", \"geek\", \"newgeeks\", \"friendsongeeks\", \"toppergeek\" }; for (string str : S) { insert(root, reverseStr(str)); } string P = \"eek\"; printStringsWithGivenSuffix( root, reverseStr(P)); return 0;}", "e": 5325, "s": 960, "text": null }, { "code": "# Python3 code for the above programclass TrieNode(): def __init__(self): # Initialize one node for trie self.children = {} self.last = False def reverse(s): str = \"\" for i in s: str = i + str return str class Trie(): def __init__(self): # Initialize the trie structure self.root = TrieNode() self.word_list = [] def formTrie(self, keys): # Forms a trie structure # with the given set of # strings if it does not # exists already else it # merges the key into it # by extending the # structure as required for key in keys: # inserting one key # to the trie. self.insert(key) def insert(self, key): # Inserts a key into # trie if it does not # exist already. And if # the key is a suffix # of the trie node, just # marks it as leaf node. node = self.root for a in list(key): if not node.children.get(a): node.children[a] = TrieNode() node = node.children[a] node.last = True def search(self, key): # Searches the given key # in trie for a full match # and returns True on # success else returns False node = self.root found = True for a in list(key): if not node.children.get(a): found = False break node = node.children[a] return node and node.last and found def printStrings(self, node, word): # Method to recursively # traverse the trie # and return a whole word if node.last: self.word_list.append(word) for a, n in node.children.items(): self.printStrings(n, word + a) def printStringsWithGivenSuffix(self, key): # Returns all the words in # the trie whose common # suffix is the given key # thus listing out all # the strings node = self.root not_found = False temp_word = '' for a in list(key): if not node.children.get(a): not_found = True break temp_word += a node = node.children[a] if not_found: return 0 elif node.last and not node.children: return -1 self.printStrings(node, temp_word) for s in self.word_list: print(reverse(s)) return 1 # Driver Code # keys to form the trie structurekeys = [reverse(\"geeks\"),reverse(\"geeksforgeeks\"),reverse(\"geek\"),reverse(\"newgeeks\"),reverse(\"friendsongeeks\"),reverse(\"toppergeek\")] # keykey = \"eek\"status = [\"Not found\", \"Found\"] # creating trie objectt = Trie() # creating the trie structure# with the given set of stringst.formTrie(keys) # print string having suffix 'P'# our trie structurecomp = t.printStringsWithGivenSuffix(reverse(key)) ", "e": 8341, "s": 5325, "text": null }, { "code": null, "e": 8357, "s": 8341, "text": "geek\ntoppergeek" }, { "code": null, "e": 8359, "s": 8357, "text": "s" }, { "code": null, "e": 8372, "s": 8359, "text": "simmytarika5" }, { "code": null, "e": 8379, "s": 8372, "text": "Suffix" }, { "code": null, "e": 8384, "s": 8379, "text": "Trie" }, { "code": null, "e": 8408, "s": 8384, "text": "Advanced Data Structure" }, { "code": null, "e": 8426, "s": 8408, "text": "Pattern Searching" }, { "code": null, "e": 8434, "s": 8426, "text": "Strings" }, { "code": null, "e": 8442, "s": 8434, "text": "Strings" }, { "code": null, "e": 8460, "s": 8442, "text": "Pattern Searching" }, { "code": null, "e": 8465, "s": 8460, "text": "Trie" } ]
How to enable Session in C# ASP.NET Core?
Session is a feature in ASP.NET Core that enables us to save/store the user data. Session stores the data in the dictionary on the Server and SessionId is used as a key. The SessionId is stored on the client at cookie. The SessionId cookie is sent with every request. The SessionId cookie is per browser and it cannot be shared between the browsers. There is no timeout specified for SessionId cookie and they are deleted when the Browser session ends. At the Server end, session is retained for a limited time. The default session timeout at the Server is 20 minutes but it is configurable. Microsoft.AspNetCore.Session package provides middleware to manage the sessions in ASP.NET Core. To use session in our Application, we need to add this package as a dependency in project.json file. The next step is to configure session in Startup class. We need to call "AddSession" method in ConfigureServices method of startup class. The "AddSession" method has one overload method, which accepts various session options such as Idle Timeout, Cookie Name and Cookie Domain etc. If we do not pass the session options, the system will take the default options public class Startup { public void Configure(IApplicationBuilder app){ app.UseSession(); app.UseMvc(); app.Run(context => { return context.Response.WriteAsync("Hello World!"); }); } public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); } } How to access the session public class HomeController : Controller{ [Route("home/index")] public IActionResult Index(){ HttpContext.Session.SetString("product","laptop"); return View(); } [Route("home/GetSessionData")] public IActionResult GetSessionData(){ ViewBag.data = HttpContext.Session.GetString("product");; return View(); } }
[ { "code": null, "e": 1269, "s": 1187, "text": "Session is a feature in ASP.NET Core that enables us to save/store the user data." }, { "code": null, "e": 1455, "s": 1269, "text": "Session stores the data in the dictionary on the Server and SessionId is used as a key.\nThe SessionId is stored on the client at cookie. The SessionId cookie is sent with\nevery request." }, { "code": null, "e": 1537, "s": 1455, "text": "The SessionId cookie is per browser and it cannot be shared between the browsers." }, { "code": null, "e": 1640, "s": 1537, "text": "There is no timeout specified for SessionId cookie and they are deleted when the\nBrowser session ends." }, { "code": null, "e": 1779, "s": 1640, "text": "At the Server end, session is retained for a limited time. The default session timeout at\nthe Server is 20 minutes but it is configurable." }, { "code": null, "e": 1977, "s": 1779, "text": "Microsoft.AspNetCore.Session package provides middleware to manage the sessions in ASP.NET Core. To use session in our Application, we need to add this package as a dependency in project.json file." }, { "code": null, "e": 2033, "s": 1977, "text": "The next step is to configure session in Startup class." }, { "code": null, "e": 2115, "s": 2033, "text": "We need to call \"AddSession\" method in ConfigureServices method of startup class." }, { "code": null, "e": 2259, "s": 2115, "text": "The \"AddSession\" method has one overload method, which accepts various session\noptions such as Idle Timeout, Cookie Name and Cookie Domain etc." }, { "code": null, "e": 2339, "s": 2259, "text": "If we do not pass the session options, the system will take the default options" }, { "code": null, "e": 2761, "s": 2339, "text": "public class Startup {\n public void Configure(IApplicationBuilder app){\n app.UseSession();\n app.UseMvc();\n app.Run(context => {\n return context.Response.WriteAsync(\"Hello World!\");\n });\n }\n public void ConfigureServices(IServiceCollection services){\n services.AddMvc();\n services.AddSession(options => {\n options.IdleTimeout = TimeSpan.FromMinutes(60);\n });\n }\n}" }, { "code": null, "e": 2787, "s": 2761, "text": "How to access the session" }, { "code": null, "e": 3138, "s": 2787, "text": "public class HomeController : Controller{\n [Route(\"home/index\")]\n public IActionResult Index(){\n HttpContext.Session.SetString(\"product\",\"laptop\");\n return View();\n }\n [Route(\"home/GetSessionData\")]\n public IActionResult GetSessionData(){\n ViewBag.data = HttpContext.Session.GetString(\"product\");;\n return View();\n }\n}" } ]
Feature Matching using Brute Force in OpenCV
10 Aug, 2021 In this article, we will do feature matching using Brute Force in Python by using OpenCV library. Prerequisites: OpenCV OpenCV is a python library which is used to solve the computer vision problems. OpenCV is an open source Computer Vision library. So computer vision is a way of teaching intelligence to machine and making them see things just like humans. In other words, OpenCV is what that allows the computer to see and process visual data just like humans. Installation: For installing the openCV library, write the following command in your command prompt. pip install opencv-python Import the OpenCV library. Load the images using imread() function and pass the path or name of the image as a parameter. Create the ORB detector for detecting the features of the images. Using the ORB detector find the keypoints and descriptors for both of the images. Now after detecting the features of the images. Now write the Brute Force Matcher for matching the features of the images and stored it in the variable named as “brute_force“. For matching we are using the brute_force.match() and pass the descriptors of first image and descriptors of the second image as a parameter. After finding the matches we have to sort that matches according to the humming distance between the matches, less will be the humming distance better will be the accuracy of the matches. Now after sorting according to humming distance we have to draw the feature matches for that we use drawMatches() function in which pass first image and keypoints of first image, second image and keypoints of second image and the best_matches as a parameter and stored it in the variable named as “output_image“. Now after drawing the feature matches we have to see the matches for that we use imshow() function which comes in cv2 library and pass the window name and output_image. Now write the waitkey() function and write the destroyAllWindows() for destroying all the windows. ORB detector stands for Oriented Fast and Rotated Brief, this is free of cost algorithm, the benefit of this algorithm is that it does not require GPU it can compute on normal CPU. ORB is basically the combination of two algorithms involved FAST and BRIEF where FAST stands for Features from Accelerated Segments Test whereas BRIEF stands for Binary Robust Independent Elementary Features. ORB detector first uses FAST algorithm, this FAST algorithm finds the key points then applies Harries corner measure to find top N numbers of key points among them, this algorithm quickly selects the key points by comparing the distinctive regions like the intensity variations. This algorithm works on Key point matching, Key point is distinctive regions in an image like the intensity variations. Now the role of BRIEF algorithm comes, this algorithm takes the key points and turn into the binary descriptor/binary feature vector that contains the combination of 0s and1s only. The key points founded by FAST algorithm and Descriptors created by BRIEF algorithm both together represent the object. BRIEF is the faster method for feature descriptor calculation and it also provides a high recognition rate until and unless there is large in-plane rotation. Brute Force Matcher is used for matching the features of the first image with another image. It takes one descriptor of first image and matches to all the descriptors of the second image and then it goes to the second descriptor of first image and matches to all the descriptor of the second image and so on. Example 1: Reading/Importing the images from their path using OpenCV library. Python # importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): # reading the images from their using imread() function read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/UsersPython(ds)/1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there path by calling the function img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images by calling the function gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) cv2.imshow('Gray scaled image 1',gray_pic1) cv2.imshow('Gray scaled image 2',gray_pic2) cv2.waitKey() cv2.destroyAllWindows() Output: Example 2: Creating ORB detector for finding the features in the images. Python # importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)//1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # showing the images with their key points finded by the detector cv2.imshow("Key points of Image 1",cv2.drawKeypoints(gray_pic1,key_pt1,None)) cv2.imshow("Key points of Image 2",cv2.drawKeypoints(gray_pic2,key_pt2,None)) # printing descriptors of both of the images print(f'Descriptors of Image 1 {descrip1}') print(f'Descriptors of Image 2 {descrip2}') print('------------------------------') # printing the Shape of the descriptors print(f'Shape of descriptor of first image {descrip1.shape}') print(f'Shape of descriptor of second image {descrip2.shape}') cv2.waitKey() cv2.destroyAllWindows() Output: The first output image shows the drawn key points of both of the images. KeyPoints are the point of interest, in simple words means that when the human will see the image at that time the features he notices in that image, in the similar way when the machine read the image it see some points of interest known as Key points. The second output image shows the descriptors and the shape of the descriptors. These Descriptors are basically array or bin of numbers. These are used to describe the features, using these descriptors we can match the two different images. In the second output image, we can see first image descriptor shape and second image descriptor shape is (467, 32) and (500,32) respectively. So, Oriented Fast and Rotated Brief (ORB) detector try to find 500 features in the image by default, and for each descriptor, it will describe 32 values. So, now how will we use these descriptors now? We can use a Brute Force Matcher (as discussed above in the article) to match these descriptors together and find how many similarities we are getting. Example 3: Feature Matching using Brute Force Matcher. Python # importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points# and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images using # detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using brute force# matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing the feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2,kpt2,best_match,None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) tot_feature_matches = len(number_of_matches) # printing total number of feature matches found print(f'Total Number of Features matches found are {tot_feature_matches}') # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows() Output: We are getting total of 178 feature matches. Total 178 matches are drawn, but they are sorted according to their humming distance in ascending order means that the distance of 178th feature is greater than the first feature, so first feature match is more accurate than the 178th feature match. It looks messy because all the 178 feature matches are drawn, let’s draw the top fifteen features (for the sake of visibility). Example 4: First/Top fifteen Feature Matching using Brute Force Matcher. Python # importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points# and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images # using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using# brute force matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing first fifteen best feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2, kpt2,best_match[:15],None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows() Output: The output image shows the first/top fifteen best feature matching using Brute Force Matcher. From the above output, we can see that these matches are more accurate than all the remaining feature matches. Let’s take another example for feature matching. Example 5: Feature matching using Brute Force. Python # importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points and# descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images # using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using brute# force matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing the feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2,kpt2, best_match[:30],None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/Titan_1.jpg' second_image_path = 'C:/Users/Python(ds)/Titan_nor.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) tot_feature_matches = len(number_of_matches) print(f'Total Number of Features matches found are {tot_feature_matches}') # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows() Output: In the above example we are getting total 147 best feature matches among them we are drawing only top 30 matches so that we can see the matches properly. Example 6: Feature Matching using Brute Force Matcher by taking rotated train image. Python # importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points# and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images # using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using brute# force matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing the feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2, kpt2,best_match[:30],None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/Titan_1.jpg' second_image_path = 'C:/Users/Python(ds)/Titan_rotated.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) tot_feature_matches = len(number_of_matches) print(f'Total Number of Features matches found are {tot_feature_matches}') # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows() Output: In this example when we have taken the rotated train image then we have found that there is little difference in the total number of best feature matches i.e, 148. In the first output image, we have only drawn the top thirty best feature matches. simranarora5sos OpenCV Technical Scripter 2020 Machine Learning Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering 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": 52, "s": 24, "text": "\n10 Aug, 2021" }, { "code": null, "e": 150, "s": 52, "text": "In this article, we will do feature matching using Brute Force in Python by using OpenCV library." }, { "code": null, "e": 172, "s": 150, "text": "Prerequisites: OpenCV" }, { "code": null, "e": 254, "s": 172, "text": "OpenCV is a python library which is used to solve the computer vision problems. " }, { "code": null, "e": 413, "s": 254, "text": "OpenCV is an open source Computer Vision library. So computer vision is a way of teaching intelligence to machine and making them see things just like humans." }, { "code": null, "e": 518, "s": 413, "text": "In other words, OpenCV is what that allows the computer to see and process visual data just like humans." }, { "code": null, "e": 532, "s": 518, "text": "Installation:" }, { "code": null, "e": 619, "s": 532, "text": "For installing the openCV library, write the following command in your command prompt." }, { "code": null, "e": 645, "s": 619, "text": "pip install opencv-python" }, { "code": null, "e": 672, "s": 645, "text": "Import the OpenCV library." }, { "code": null, "e": 767, "s": 672, "text": "Load the images using imread() function and pass the path or name of the image as a parameter." }, { "code": null, "e": 833, "s": 767, "text": "Create the ORB detector for detecting the features of the images." }, { "code": null, "e": 915, "s": 833, "text": "Using the ORB detector find the keypoints and descriptors for both of the images." }, { "code": null, "e": 1091, "s": 915, "text": "Now after detecting the features of the images. Now write the Brute Force Matcher for matching the features of the images and stored it in the variable named as “brute_force“." }, { "code": null, "e": 1233, "s": 1091, "text": "For matching we are using the brute_force.match() and pass the descriptors of first image and descriptors of the second image as a parameter." }, { "code": null, "e": 1421, "s": 1233, "text": "After finding the matches we have to sort that matches according to the humming distance between the matches, less will be the humming distance better will be the accuracy of the matches." }, { "code": null, "e": 1734, "s": 1421, "text": "Now after sorting according to humming distance we have to draw the feature matches for that we use drawMatches() function in which pass first image and keypoints of first image, second image and keypoints of second image and the best_matches as a parameter and stored it in the variable named as “output_image“." }, { "code": null, "e": 1903, "s": 1734, "text": "Now after drawing the feature matches we have to see the matches for that we use imshow() function which comes in cv2 library and pass the window name and output_image." }, { "code": null, "e": 2002, "s": 1903, "text": "Now write the waitkey() function and write the destroyAllWindows() for destroying all the windows." }, { "code": null, "e": 2183, "s": 2002, "text": "ORB detector stands for Oriented Fast and Rotated Brief, this is free of cost algorithm, the benefit of this algorithm is that it does not require GPU it can compute on normal CPU." }, { "code": null, "e": 2392, "s": 2183, "text": "ORB is basically the combination of two algorithms involved FAST and BRIEF where FAST stands for Features from Accelerated Segments Test whereas BRIEF stands for Binary Robust Independent Elementary Features." }, { "code": null, "e": 2671, "s": 2392, "text": "ORB detector first uses FAST algorithm, this FAST algorithm finds the key points then applies Harries corner measure to find top N numbers of key points among them, this algorithm quickly selects the key points by comparing the distinctive regions like the intensity variations." }, { "code": null, "e": 2791, "s": 2671, "text": "This algorithm works on Key point matching, Key point is distinctive regions in an image like the intensity variations." }, { "code": null, "e": 2973, "s": 2791, "text": "Now the role of BRIEF algorithm comes, this algorithm takes the key points and turn into the binary descriptor/binary feature vector that contains the combination of 0s and1s only. " }, { "code": null, "e": 3251, "s": 2973, "text": "The key points founded by FAST algorithm and Descriptors created by BRIEF algorithm both together represent the object. BRIEF is the faster method for feature descriptor calculation and it also provides a high recognition rate until and unless there is large in-plane rotation." }, { "code": null, "e": 3344, "s": 3251, "text": "Brute Force Matcher is used for matching the features of the first image with another image." }, { "code": null, "e": 3560, "s": 3344, "text": "It takes one descriptor of first image and matches to all the descriptors of the second image and then it goes to the second descriptor of first image and matches to all the descriptor of the second image and so on." }, { "code": null, "e": 3638, "s": 3560, "text": "Example 1: Reading/Importing the images from their path using OpenCV library." }, { "code": null, "e": 3645, "s": 3638, "text": "Python" }, { "code": "# importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): # reading the images from their using imread() function read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/UsersPython(ds)/1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there path by calling the function img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images by calling the function gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) cv2.imshow('Gray scaled image 1',gray_pic1) cv2.imshow('Gray scaled image 2',gray_pic2) cv2.waitKey() cv2.destroyAllWindows()", "e": 4757, "s": 3645, "text": null }, { "code": null, "e": 4765, "s": 4757, "text": "Output:" }, { "code": null, "e": 4838, "s": 4765, "text": "Example 2: Creating ORB detector for finding the features in the images." }, { "code": null, "e": 4845, "s": 4838, "text": "Python" }, { "code": "# importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)//1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # showing the images with their key points finded by the detector cv2.imshow(\"Key points of Image 1\",cv2.drawKeypoints(gray_pic1,key_pt1,None)) cv2.imshow(\"Key points of Image 2\",cv2.drawKeypoints(gray_pic2,key_pt2,None)) # printing descriptors of both of the images print(f'Descriptors of Image 1 {descrip1}') print(f'Descriptors of Image 2 {descrip2}') print('------------------------------') # printing the Shape of the descriptors print(f'Shape of descriptor of first image {descrip1.shape}') print(f'Shape of descriptor of second image {descrip2.shape}') cv2.waitKey() cv2.destroyAllWindows()", "e": 6935, "s": 4845, "text": null }, { "code": null, "e": 6943, "s": 6935, "text": "Output:" }, { "code": null, "e": 7017, "s": 6943, "text": "The first output image shows the drawn key points of both of the images. " }, { "code": null, "e": 7270, "s": 7017, "text": "KeyPoints are the point of interest, in simple words means that when the human will see the image at that time the features he notices in that image, in the similar way when the machine read the image it see some points of interest known as Key points." }, { "code": null, "e": 7350, "s": 7270, "text": "The second output image shows the descriptors and the shape of the descriptors." }, { "code": null, "e": 7511, "s": 7350, "text": "These Descriptors are basically array or bin of numbers. These are used to describe the features, using these descriptors we can match the two different images." }, { "code": null, "e": 7807, "s": 7511, "text": "In the second output image, we can see first image descriptor shape and second image descriptor shape is (467, 32) and (500,32) respectively. So, Oriented Fast and Rotated Brief (ORB) detector try to find 500 features in the image by default, and for each descriptor, it will describe 32 values." }, { "code": null, "e": 8006, "s": 7807, "text": "So, now how will we use these descriptors now? We can use a Brute Force Matcher (as discussed above in the article) to match these descriptors together and find how many similarities we are getting." }, { "code": null, "e": 8061, "s": 8006, "text": "Example 3: Feature Matching using Brute Force Matcher." }, { "code": null, "e": 8068, "s": 8061, "text": "Python" }, { "code": "# importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points# and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images using # detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using brute force# matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing the feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2,kpt2,best_match,None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) tot_feature_matches = len(number_of_matches) # printing total number of feature matches found print(f'Total Number of Features matches found are {tot_feature_matches}') # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows()", "e": 10750, "s": 8068, "text": null }, { "code": null, "e": 10758, "s": 10750, "text": "Output:" }, { "code": null, "e": 11053, "s": 10758, "text": "We are getting total of 178 feature matches. Total 178 matches are drawn, but they are sorted according to their humming distance in ascending order means that the distance of 178th feature is greater than the first feature, so first feature match is more accurate than the 178th feature match." }, { "code": null, "e": 11181, "s": 11053, "text": "It looks messy because all the 178 feature matches are drawn, let’s draw the top fifteen features (for the sake of visibility)." }, { "code": null, "e": 11254, "s": 11181, "text": "Example 4: First/Top fifteen Feature Matching using Brute Force Matcher." }, { "code": null, "e": 11261, "s": 11254, "text": "Python" }, { "code": "# importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points# and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images # using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using# brute force matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing first fifteen best feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2, kpt2,best_match[:15],None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/1611755129039.jpg' second_image_path = 'C:/Users/Python(ds)/1611755720390.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows()", "e": 13819, "s": 11261, "text": null }, { "code": null, "e": 13827, "s": 13819, "text": "Output:" }, { "code": null, "e": 13921, "s": 13827, "text": "The output image shows the first/top fifteen best feature matching using Brute Force Matcher." }, { "code": null, "e": 14032, "s": 13921, "text": "From the above output, we can see that these matches are more accurate than all the remaining feature matches." }, { "code": null, "e": 14081, "s": 14032, "text": "Let’s take another example for feature matching." }, { "code": null, "e": 14128, "s": 14081, "text": "Example 5: Feature matching using Brute Force." }, { "code": null, "e": 14135, "s": 14128, "text": "Python" }, { "code": "# importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points and# descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images # using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using brute# force matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing the feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2,kpt2, best_match[:30],None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/Titan_1.jpg' second_image_path = 'C:/Users/Python(ds)/Titan_nor.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) tot_feature_matches = len(number_of_matches) print(f'Total Number of Features matches found are {tot_feature_matches}') # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows()", "e": 16793, "s": 14135, "text": null }, { "code": null, "e": 16801, "s": 16793, "text": "Output:" }, { "code": null, "e": 16955, "s": 16801, "text": "In the above example we are getting total 147 best feature matches among them we are drawing only top 30 matches so that we can see the matches properly." }, { "code": null, "e": 17040, "s": 16955, "text": "Example 6: Feature Matching using Brute Force Matcher by taking rotated train image." }, { "code": null, "e": 17047, "s": 17040, "text": "Python" }, { "code": "# importing openCV libraryimport cv2 # function to read the images by taking there pathdef read_image(path1,path2): read_img1 = cv2.imread(path1) read_img2 = cv2.imread(path2) return (read_img1,read_img2) # function to convert images from RGB to gray scaledef convert_to_grayscale(pic1,pic2): gray_img1 = cv2.cvtColor(pic1,cv2.COLOR_BGR2GRAY) gray_img2 = cv2.cvtColor(pic2,cv2.COLOR_BGR2GRAY) return (gray_img1,gray_img2) # function to detect the features by finding key points# and descriptors from the imagedef detector(image1,image2): # creating ORB detector detect = cv2.ORB_create() # finding key points and descriptors of both images # using detectAndCompute() function key_point1,descrip1 = detect.detectAndCompute(image1,None) key_point2,descrip2 = detect.detectAndCompute(image2,None) return (key_point1,descrip1,key_point2,descrip2) # function to find best detected features using brute# force matcher and match them according to there humming distancedef BF_FeatureMatcher(des1,des2): brute_force = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) no_of_matches = brute_force.match(des1,des2) # finding the humming distance of the matches and sorting them no_of_matches = sorted(no_of_matches,key=lambda x:x.distance) return no_of_matches # function displaying the output image with the feature matchingdef display_output(pic1,kpt1,pic2,kpt2,best_match): # drawing the feature matches using drawMatches() function output_image = cv2.drawMatches(pic1,kpt1,pic2, kpt2,best_match[:30],None,flags=2) cv2.imshow('Output image',output_image) # main functionif __name__ == '__main__': # giving the path of both of the images first_image_path = 'C:/Users/Python(ds)/Titan_1.jpg' second_image_path = 'C:/Users/Python(ds)/Titan_rotated.jpg' # reading the image from there paths img1, img2 = read_image(first_image_path,second_image_path) # converting the readed images into the gray scale images gray_pic1, gray_pic2 = convert_to_grayscale(img1,img2) # storing the finded key points and descriptors of both of the images key_pt1,descrip1,key_pt2,descrip2 = detector(gray_pic1,gray_pic2) # sorting the number of best matches obtained from brute force matcher number_of_matches = BF_FeatureMatcher(descrip1,descrip2) tot_feature_matches = len(number_of_matches) print(f'Total Number of Features matches found are {tot_feature_matches}') # after drawing the feature matches displaying the output image display_output(gray_pic1,key_pt1,gray_pic2,key_pt2,number_of_matches) cv2.waitKey() cv2.destroyAllWindows()", "e": 19709, "s": 17047, "text": null }, { "code": null, "e": 19717, "s": 19709, "text": "Output:" }, { "code": null, "e": 19881, "s": 19717, "text": "In this example when we have taken the rotated train image then we have found that there is little difference in the total number of best feature matches i.e, 148." }, { "code": null, "e": 19964, "s": 19881, "text": "In the first output image, we have only drawn the top thirty best feature matches." }, { "code": null, "e": 19980, "s": 19964, "text": "simranarora5sos" }, { "code": null, "e": 19987, "s": 19980, "text": "OpenCV" }, { "code": null, "e": 20011, "s": 19987, "text": "Technical Scripter 2020" }, { "code": null, "e": 20028, "s": 20011, "text": "Machine Learning" }, { "code": null, "e": 20035, "s": 20028, "text": "Python" }, { "code": null, "e": 20054, "s": 20035, "text": "Technical Scripter" }, { "code": null, "e": 20071, "s": 20054, "text": "Machine Learning" }, { "code": null, "e": 20169, "s": 20071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20210, "s": 20169, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 20243, "s": 20210, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 20279, "s": 20243, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 20303, "s": 20279, "text": "Markov Decision Process" }, { "code": null, "e": 20354, "s": 20303, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 20382, "s": 20354, "text": "Read JSON file using Python" }, { "code": null, "e": 20432, "s": 20382, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 20454, "s": 20432, "text": "Python map() function" } ]
How to delete columns in PySpark dataframe ?
17 Jun, 2021 In this article, we are going to delete columns in Pyspark dataframe. To do this we will be using the drop() function. This function can be used to remove values from the dataframe. Syntax: dataframe.drop(‘column name’) Python code to create student dataframe with three columns: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data data =[["1","sravan","vignan"], ["2","ojaswi","vvit"], ["3","rohith","vvit"], ["4","sridevi","vignan"], ["1","sravan","vignan"], ["5","gnanesh","iit"]] # specify column namescolumns=['student ID','student NAME','college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print("Actual data in dataframe") # show dataframedataframe.show() Output: Actual data in dataframe +----------+------------+-------+ |student ID|student NAME|college| +----------+------------+-------+ | 1| sravan| vignan| | 2| ojaswi| vvit| | 3| rohith| vvit| | 4| sridevi| vignan| | 1| sravan| vignan| | 5| gnanesh| iit| +----------+------------+-------+ Example 1: Python program to delete a single column. Here we are going to delete ‘student ID’ from the dataframe, for this we will use drop(). Python3 # delete single columndataframe=dataframe.drop('student ID')dataframe.show() Output: +------------+-------+ |student NAME|college| +------------+-------+ | sravan| vignan| | ojaswi| vvit| | rohith| vvit| | sridevi| vignan| | sravan| vignan| | gnanesh| iit| +------------+-------+ Example 2: Delete multiple columns Here we will delete multiple columns in a dataframe just passing multiple columns inside the drop() function. Python3 # delete two columnsdataframe=dataframe.drop(*('student NAME', 'student ID'))dataframe.show() Output: +-------+ |college| +-------+ | vignan| | vvit| | vvit| | vignan| | vignan| | iit| +-------+ Example 3: Delete all columns Here we will delete all the columns in dataframe. Python3 # delete two columnsdataframe=dataframe.drop(*('student NAME', 'student ID', 'college'))dataframe.show() Output: ++ || ++ || || || || || || ++ Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 210, "s": 28, "text": "In this article, we are going to delete columns in Pyspark dataframe. To do this we will be using the drop() function. This function can be used to remove values from the dataframe." }, { "code": null, "e": 248, "s": 210, "text": "Syntax: dataframe.drop(‘column name’)" }, { "code": null, "e": 308, "s": 248, "text": "Python code to create student dataframe with three columns:" }, { "code": null, "e": 316, "s": 308, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data data =[[\"1\",\"sravan\",\"vignan\"], [\"2\",\"ojaswi\",\"vvit\"], [\"3\",\"rohith\",\"vvit\"], [\"4\",\"sridevi\",\"vignan\"], [\"1\",\"sravan\",\"vignan\"], [\"5\",\"gnanesh\",\"iit\"]] # specify column namescolumns=['student ID','student NAME','college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print(\"Actual data in dataframe\") # show dataframedataframe.show()", "e": 988, "s": 316, "text": null }, { "code": null, "e": 996, "s": 988, "text": "Output:" }, { "code": null, "e": 1361, "s": 996, "text": "Actual data in dataframe\n+----------+------------+-------+\n|student ID|student NAME|college|\n+----------+------------+-------+\n| 1| sravan| vignan|\n| 2| ojaswi| vvit|\n| 3| rohith| vvit|\n| 4| sridevi| vignan|\n| 1| sravan| vignan|\n| 5| gnanesh| iit|\n+----------+------------+-------+" }, { "code": null, "e": 1414, "s": 1361, "text": "Example 1: Python program to delete a single column." }, { "code": null, "e": 1504, "s": 1414, "text": "Here we are going to delete ‘student ID’ from the dataframe, for this we will use drop()." }, { "code": null, "e": 1512, "s": 1504, "text": "Python3" }, { "code": "# delete single columndataframe=dataframe.drop('student ID')dataframe.show()", "e": 1589, "s": 1512, "text": null }, { "code": null, "e": 1597, "s": 1589, "text": "Output:" }, { "code": null, "e": 1827, "s": 1597, "text": "+------------+-------+\n|student NAME|college|\n+------------+-------+\n| sravan| vignan|\n| ojaswi| vvit|\n| rohith| vvit|\n| sridevi| vignan|\n| sravan| vignan|\n| gnanesh| iit|\n+------------+-------+" }, { "code": null, "e": 1862, "s": 1827, "text": "Example 2: Delete multiple columns" }, { "code": null, "e": 1972, "s": 1862, "text": "Here we will delete multiple columns in a dataframe just passing multiple columns inside the drop() function." }, { "code": null, "e": 1980, "s": 1972, "text": "Python3" }, { "code": "# delete two columnsdataframe=dataframe.drop(*('student NAME', 'student ID'))dataframe.show()", "e": 2100, "s": 1980, "text": null }, { "code": null, "e": 2108, "s": 2100, "text": "Output:" }, { "code": null, "e": 2208, "s": 2108, "text": "+-------+\n|college|\n+-------+\n| vignan|\n| vvit|\n| vvit|\n| vignan|\n| vignan|\n| iit|\n+-------+" }, { "code": null, "e": 2238, "s": 2208, "text": "Example 3: Delete all columns" }, { "code": null, "e": 2288, "s": 2238, "text": "Here we will delete all the columns in dataframe." }, { "code": null, "e": 2296, "s": 2288, "text": "Python3" }, { "code": "# delete two columnsdataframe=dataframe.drop(*('student NAME', 'student ID', 'college'))dataframe.show()", "e": 2453, "s": 2296, "text": null }, { "code": null, "e": 2461, "s": 2453, "text": "Output:" }, { "code": null, "e": 2491, "s": 2461, "text": "++\n||\n++\n||\n||\n||\n||\n||\n||\n++" }, { "code": null, "e": 2498, "s": 2491, "text": "Picked" }, { "code": null, "e": 2513, "s": 2498, "text": "Python-Pyspark" }, { "code": null, "e": 2520, "s": 2513, "text": "Python" }, { "code": null, "e": 2618, "s": 2520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2663, "s": 2618, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2713, "s": 2663, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2729, "s": 2713, "text": "Deque in Python" }, { "code": null, "e": 2745, "s": 2729, "text": "Queue in Python" }, { "code": null, "e": 2767, "s": 2745, "text": "Defaultdict in Python" }, { "code": null, "e": 2809, "s": 2767, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2836, "s": 2809, "text": "Python Classes and Objects" }, { "code": null, "e": 2859, "s": 2836, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 2878, "s": 2859, "text": "reduce() in Python" } ]
Node.js __dirname Variable
08 Apr, 2021 The __dirname string gives the directory path of the current module, this is also similar to that of path.dirname() of the filename. Return Value : It returns the directory path of the current module. Example 1: Let’s create a file main.js main.js import path from 'path';const __dirname = path.resolve();console.log(__dirname) Output: Now run node main.js. Example 2: Replicating __dirname with path.dirname(). Javascript import path from 'path';const __dirname = path.resolve();const __filename = path.resolve();console.log(path.dirname(__filename)); Output: Now run node main.js. Reference:https://nodejs.org/docs/latest/api/globals.html#globals_dirname Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Windows JWT Authentication with Node.js Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2021" }, { "code": null, "e": 161, "s": 28, "text": "The __dirname string gives the directory path of the current module, this is also similar to that of path.dirname() of the filename." }, { "code": null, "e": 229, "s": 161, "text": "Return Value : It returns the directory path of the current module." }, { "code": null, "e": 268, "s": 229, "text": "Example 1: Let’s create a file main.js" }, { "code": null, "e": 276, "s": 268, "text": "main.js" }, { "code": "import path from 'path';const __dirname = path.resolve();console.log(__dirname)", "e": 356, "s": 276, "text": null }, { "code": null, "e": 386, "s": 356, "text": "Output: Now run node main.js." }, { "code": null, "e": 440, "s": 386, "text": "Example 2: Replicating __dirname with path.dirname()." }, { "code": null, "e": 451, "s": 440, "text": "Javascript" }, { "code": "import path from 'path';const __dirname = path.resolve();const __filename = path.resolve();console.log(path.dirname(__filename));", "e": 581, "s": 451, "text": null }, { "code": null, "e": 611, "s": 581, "text": "Output: Now run node main.js." }, { "code": null, "e": 685, "s": 611, "text": "Reference:https://nodejs.org/docs/latest/api/globals.html#globals_dirname" }, { "code": null, "e": 700, "s": 685, "text": "Node.js-Basics" }, { "code": null, "e": 707, "s": 700, "text": "Picked" }, { "code": null, "e": 715, "s": 707, "text": "Node.js" }, { "code": null, "e": 732, "s": 715, "text": "Web Technologies" }, { "code": null, "e": 830, "s": 732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 865, "s": 830, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 897, "s": 865, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 967, "s": 897, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 994, "s": 967, "text": "Mongoose Populate() Method" }, { "code": null, "e": 1019, "s": 994, "text": "Mongoose find() Function" }, { "code": null, "e": 1081, "s": 1019, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1142, "s": 1081, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1192, "s": 1142, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1235, "s": 1192, "text": "How to fetch data from an API in ReactJS ?" } ]
Hover Text and Formatting in Python-Plotly
06 Jul, 2022 Prerequisites: Python Plotly In this article, we will explore how to Hover Text and Formatting in Python. It is a useful approach to Hover Text and Formatting as it allows to reveal a large amount of data about complex information. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. The default setting is layout.hovermode=’closest’, wherein a single hover label appears for the point directly underneath the cursor. Python3 import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country")fig.update_traces(mode="markers+lines") fig.show() Output: If layout.hovermode=’x’ , a single hover label appears per trace, for points at the same x value as the cursor. Python3 import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country")fig.update_traces(mode="markers+lines", hovertemplate=None)fig.update_layout(hovermode="x unified") fig.show() Output: If layout.hovermode=’y’ , a single hover label appears per trace, for points at the same y value as the cursor. Python3 import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country")fig.update_traces(mode="markers+lines", hovertemplate=None)fig.update_layout(hovermode="y unified") fig.show() Output: GDP: %{x} <br>Life Expectancy: %{y} Here, GDP and Expectancy is used as naming convention about the data whereas %{ <variable>} which allows to revel a large amount of data about complex information. Python3 import plotly.express as px df_2007 = px.data.gapminder().query("year==2007") fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", log_x=True, color='continent') fig.update_traces(hovertemplate='GDP: %{x} <br>Life Expectancy: %{y}') fig.show() Output: %{label}: <br>Popularity: %{percent} </br> %{text} Here, Label, Percent, and Text is used as naming convention about the data whereas %{ <variable>} which allows to revel a large amount of data about complex information. Python3 import plotly.graph_objects as go fig = go.Figure(go.Pie( name = "", values = [2, 5, 3, 2.5], labels = ["R", "Python", "Java Script", "Matlab"], text = ["R", "Python", "JS", "Matlab"], hovertemplate = "%{label}: <br>Popularity: %{percent} </br> %{text}")) fig.show() Output: vinayedula Picked Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2022" }, { "code": null, "e": 57, "s": 28, "text": "Prerequisites: Python Plotly" }, { "code": null, "e": 134, "s": 57, "text": "In this article, we will explore how to Hover Text and Formatting in Python." }, { "code": null, "e": 476, "s": 134, "text": "It is a useful approach to Hover Text and Formatting as it allows to reveal a large amount of data about complex information. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears." }, { "code": null, "e": 611, "s": 476, "text": " The default setting is layout.hovermode=’closest’, wherein a single hover label appears for the point directly underneath the cursor." }, { "code": null, "e": 619, "s": 611, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.gapminder().query(\"continent=='Oceania'\") fig = px.line(df, x=\"year\", y=\"lifeExp\", color=\"country\")fig.update_traces(mode=\"markers+lines\") fig.show()", "e": 810, "s": 619, "text": null }, { "code": null, "e": 818, "s": 810, "text": "Output:" }, { "code": null, "e": 930, "s": 818, "text": "If layout.hovermode=’x’ , a single hover label appears per trace, for points at the same x value as the cursor." }, { "code": null, "e": 938, "s": 930, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.gapminder().query(\"continent=='Oceania'\") fig = px.line(df, x=\"year\", y=\"lifeExp\", color=\"country\")fig.update_traces(mode=\"markers+lines\", hovertemplate=None)fig.update_layout(hovermode=\"x unified\") fig.show()", "e": 1189, "s": 938, "text": null }, { "code": null, "e": 1197, "s": 1189, "text": "Output:" }, { "code": null, "e": 1309, "s": 1197, "text": "If layout.hovermode=’y’ , a single hover label appears per trace, for points at the same y value as the cursor." }, { "code": null, "e": 1317, "s": 1309, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.gapminder().query(\"continent=='Oceania'\") fig = px.line(df, x=\"year\", y=\"lifeExp\", color=\"country\")fig.update_traces(mode=\"markers+lines\", hovertemplate=None)fig.update_layout(hovermode=\"y unified\") fig.show()", "e": 1568, "s": 1317, "text": null }, { "code": null, "e": 1576, "s": 1568, "text": "Output:" }, { "code": null, "e": 1612, "s": 1576, "text": "GDP: %{x} <br>Life Expectancy: %{y}" }, { "code": null, "e": 1776, "s": 1612, "text": "Here, GDP and Expectancy is used as naming convention about the data whereas %{ <variable>} which allows to revel a large amount of data about complex information." }, { "code": null, "e": 1784, "s": 1776, "text": "Python3" }, { "code": "import plotly.express as px df_2007 = px.data.gapminder().query(\"year==2007\") fig = px.scatter(df_2007, x=\"gdpPercap\", y=\"lifeExp\", log_x=True, color='continent') fig.update_traces(hovertemplate='GDP: %{x} <br>Life Expectancy: %{y}') fig.show()", "e": 2045, "s": 1784, "text": null }, { "code": null, "e": 2053, "s": 2045, "text": "Output:" }, { "code": null, "e": 2104, "s": 2053, "text": "%{label}: <br>Popularity: %{percent} </br> %{text}" }, { "code": null, "e": 2274, "s": 2104, "text": "Here, Label, Percent, and Text is used as naming convention about the data whereas %{ <variable>} which allows to revel a large amount of data about complex information." }, { "code": null, "e": 2282, "s": 2274, "text": "Python3" }, { "code": "import plotly.graph_objects as go fig = go.Figure(go.Pie( name = \"\", values = [2, 5, 3, 2.5], labels = [\"R\", \"Python\", \"Java Script\", \"Matlab\"], text = [\"R\", \"Python\", \"JS\", \"Matlab\"], hovertemplate = \"%{label}: <br>Popularity: %{percent} </br> %{text}\")) fig.show()", "e": 2564, "s": 2282, "text": null }, { "code": null, "e": 2572, "s": 2564, "text": "Output:" }, { "code": null, "e": 2583, "s": 2572, "text": "vinayedula" }, { "code": null, "e": 2590, "s": 2583, "text": "Picked" }, { "code": null, "e": 2604, "s": 2590, "text": "Python-Plotly" }, { "code": null, "e": 2611, "s": 2604, "text": "Python" } ]
MATLAB - Algebra
So far, we have seen that all the examples work in MATLAB as well as its GNU, alternatively called Octave. But for solving basic algebraic equations, both MATLAB and Octave are little different, so we will try to cover MATLAB and Octave in separate sections. We will also discuss factorizing and simplification of algebraic expressions. The solve function is used for solving algebraic equations. In its simplest form, the solve function takes the equation enclosed in quotes as an argument. For example, let us solve for x in the equation x-5 = 0 solve('x-5=0') MATLAB will execute the above statement and return the following result − ans = 5 You can also call the solve function as − y = solve('x-5 = 0') MATLAB will execute the above statement and return the following result − y = 5 You may even not include the right hand side of the equation − solve('x-5') MATLAB will execute the above statement and return the following result − ans = 5 If the equation involves multiple symbols, then MATLAB by default assumes that you are solving for x, however, the solve function has another form − solve(equation, variable) where, you can also mention the variable. For example, let us solve the equation v – u – 3t2 = 0, for v. In this case, we should write − solve('v-u-3*t^2=0', 'v') MATLAB will execute the above statement and return the following result − ans = 3*t^2 + u The roots function is used for solving algebraic equations in Octave and you can write above examples as follows − For example, let us solve for x in the equation x-5 = 0 roots([1, -5]) Octave will execute the above statement and return the following result − ans = 5 You can also call the solve function as − y = roots([1, -5]) Octave will execute the above statement and return the following result − y = 5 The solve function can also solve higher order equations. It is often used to solve quadratic equations. The function returns the roots of the equation in an array. The following example solves the quadratic equation x2 -7x +12 = 0. Create a script file and type the following code − eq = 'x^2 -7*x + 12 = 0'; s = solve(eq); disp('The first root is: '), disp(s(1)); disp('The second root is: '), disp(s(2)); When you run the file, it displays the following result − The first root is: 3 The second root is: 4 The following example solves the quadratic equation x2 -7x +12 = 0 in Octave. Create a script file and type the following code − s = roots([1, -7, 12]); disp('The first root is: '), disp(s(1)); disp('The second root is: '), disp(s(2)); When you run the file, it displays the following result − The first root is: 4 The second root is: 3 The solve function can also solve higher order equations. For example, let us solve a cubic equation as (x-3)2(x-7) = 0 solve('(x-3)^2*(x-7)=0') MATLAB will execute the above statement and return the following result − ans = 3 3 7 In case of higher order equations, roots are long containing many terms. You can get the numerical value of such roots by converting them to double. The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0. Create a script file and type the following code − eq = 'x^4 - 7*x^3 + 3*x^2 - 5*x + 9 = 0'; s = solve(eq); disp('The first root is: '), disp(s(1)); disp('The second root is: '), disp(s(2)); disp('The third root is: '), disp(s(3)); disp('The fourth root is: '), disp(s(4)); % converting the roots to double type disp('Numeric value of first root'), disp(double(s(1))); disp('Numeric value of second root'), disp(double(s(2))); disp('Numeric value of third root'), disp(double(s(3))); disp('Numeric value of fourth root'), disp(double(s(4))); When you run the file, it returns the following result − The first root is: 6.630396332390718431485053218985 The second root is: 1.0597804633025896291682772499885 The third root is: - 0.34508839784665403032666523448675 - 1.0778362954630176596831109269793*i The fourth root is: - 0.34508839784665403032666523448675 + 1.0778362954630176596831109269793*i Numeric value of first root 6.6304 Numeric value of second root 1.0598 Numeric value of third root -0.3451 - 1.0778i Numeric value of fourth root -0.3451 + 1.0778i Please note that the last two roots are complex numbers. The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0. Create a script file and type the following code − v = [1, -7, 3, -5, 9]; s = roots(v); % converting the roots to double type disp('Numeric value of first root'), disp(double(s(1))); disp('Numeric value of second root'), disp(double(s(2))); disp('Numeric value of third root'), disp(double(s(3))); disp('Numeric value of fourth root'), disp(double(s(4))); When you run the file, it returns the following result − Numeric value of first root 6.6304 Numeric value of second root -0.34509 + 1.07784i Numeric value of third root -0.34509 - 1.07784i Numeric value of fourth root 1.0598 The solve function can also be used to generate solutions of systems of equations involving more than one variables. Let us take up a simple example to demonstrate this use. Let us solve the equations − 5x + 9y = 5 3x – 6y = 4 Create a script file and type the following code − s = solve('5*x + 9*y = 5','3*x - 6*y = 4'); s.x s.y When you run the file, it displays the following result − ans = 22/19 ans = -5/57 In same way, you can solve larger linear systems. Consider the following set of equations − x + 3y -2z = 5 3x + 5y + 6z = 7 2x + 4y + 3z = 8 We have a little different approach to solve a system of 'n' linear equations in 'n' unknowns. Let us take up a simple example to demonstrate this use. Let us solve the equations − 5x + 9y = 5 3x – 6y = 4 Such a system of linear equations can be written as the single matrix equation Ax = b, where A is the coefficient matrix, b is the column vector containing the right-hand side of the linear equations and x is the column vector representing the solution as shown in the below program − Create a script file and type the following code − A = [5, 9; 3, -6]; b = [5;4]; A \ b When you run the file, it displays the following result − ans = 1.157895 -0.087719 In same way, you can solve larger linear systems as given below − x + 3y -2z = 5 3x + 5y + 6z = 7 2x + 4y + 3z = 8 The expand and the collect function expands and collects an equation respectively. The following example demonstrates the concepts − When you work with many symbolic functions, you should declare that your variables are symbolic. Create a script file and type the following code − syms x %symbolic variable x syms y %symbolic variable x % expanding equations expand((x-5)*(x+9)) expand((x+2)*(x-3)*(x-5)*(x+7)) expand(sin(2*x)) expand(cos(x+y)) % collecting equations collect(x^3 *(x-7)) collect(x^4*(x-3)*(x-5)) When you run the file, it displays the following result − ans = x^2 + 4*x - 45 ans = x^4 + x^3 - 43*x^2 + 23*x + 210 ans = 2*cos(x)*sin(x) ans = cos(x)*cos(y) - sin(x)*sin(y) ans = x^4 - 7*x^3 ans = x^6 - 8*x^5 + 15*x^4 You need to have symbolic package, which provides expand and the collect function to expand and collect an equation, respectively. The following example demonstrates the concepts − When you work with many symbolic functions, you should declare that your variables are symbolic but Octave has different approach to define symbolic variables. Notice the use of Sin and Cos, which are also defined in symbolic package. Create a script file and type the following code − % first of all load the package, make sure its installed. pkg load symbolic % make symbols module available symbols % define symbolic variables x = sym ('x'); y = sym ('y'); z = sym ('z'); % expanding equations expand((x-5)*(x+9)) expand((x+2)*(x-3)*(x-5)*(x+7)) expand(Sin(2*x)) expand(Cos(x+y)) % collecting equations collect(x^3 *(x-7), z) collect(x^4*(x-3)*(x-5), z) When you run the file, it displays the following result − ans = -45.0+x^2+(4.0)*x ans = 210.0+x^4-(43.0)*x^2+x^3+(23.0)*x ans = sin((2.0)*x) ans = cos(y+x) ans = x^(3.0)*(-7.0+x) ans = (-3.0+x)*x^(4.0)*(-5.0+x) The factor function factorizes an expression and the simplify function simplifies an expression. The following example demonstrates the concept − Create a script file and type the following code − syms x syms y factor(x^3 - y^3) factor([x^2-y^2,x^3+y^3]) simplify((x^4-16)/(x^2-4)) When you run the file, it displays the following result − ans = (x - y)*(x^2 + x*y + y^2) ans = [ (x - y)*(x + y), (x + y)*(x^2 - x*y + y^2)] ans = x^2 + 4
[ { "code": null, "e": 2536, "s": 2275, "text": "So far, we have seen that all the examples work in MATLAB as well as its GNU, alternatively called Octave. But for solving basic algebraic equations, both MATLAB and Octave are little different, so we will try to cover MATLAB and Octave in separate sections." }, { "code": null, "e": 2614, "s": 2536, "text": "We will also discuss factorizing and simplification of algebraic expressions." }, { "code": null, "e": 2769, "s": 2614, "text": "The solve function is used for solving algebraic equations. In its simplest form, the solve function takes the equation enclosed in quotes as an argument." }, { "code": null, "e": 2825, "s": 2769, "text": "For example, let us solve for x in the equation x-5 = 0" }, { "code": null, "e": 2841, "s": 2825, "text": "solve('x-5=0')\n" }, { "code": null, "e": 2915, "s": 2841, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 2927, "s": 2915, "text": "ans =\n 5\n" }, { "code": null, "e": 2969, "s": 2927, "text": "You can also call the solve function as −" }, { "code": null, "e": 2990, "s": 2969, "text": "y = solve('x-5 = 0')" }, { "code": null, "e": 3064, "s": 2990, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3074, "s": 3064, "text": "y =\n 5\n" }, { "code": null, "e": 3137, "s": 3074, "text": "You may even not include the right hand side of the equation −" }, { "code": null, "e": 3150, "s": 3137, "text": "solve('x-5')" }, { "code": null, "e": 3224, "s": 3150, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3236, "s": 3224, "text": "ans =\n 5\n" }, { "code": null, "e": 3385, "s": 3236, "text": "If the equation involves multiple symbols, then MATLAB by default assumes that you are solving for x, however, the solve function has another form −" }, { "code": null, "e": 3411, "s": 3385, "text": "solve(equation, variable)" }, { "code": null, "e": 3453, "s": 3411, "text": "where, you can also mention the variable." }, { "code": null, "e": 3548, "s": 3453, "text": "For example, let us solve the equation v – u – 3t2 = 0, for v. In this case, we should write −" }, { "code": null, "e": 3574, "s": 3548, "text": "solve('v-u-3*t^2=0', 'v')" }, { "code": null, "e": 3648, "s": 3574, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3668, "s": 3648, "text": "ans =\n 3*t^2 + u\n" }, { "code": null, "e": 3783, "s": 3668, "text": "The roots function is used for solving algebraic equations in Octave and you can write above examples as follows −" }, { "code": null, "e": 3839, "s": 3783, "text": "For example, let us solve for x in the equation x-5 = 0" }, { "code": null, "e": 3854, "s": 3839, "text": "roots([1, -5])" }, { "code": null, "e": 3928, "s": 3854, "text": "Octave will execute the above statement and return the following result −" }, { "code": null, "e": 3937, "s": 3928, "text": "ans = 5\n" }, { "code": null, "e": 3979, "s": 3937, "text": "You can also call the solve function as −" }, { "code": null, "e": 3998, "s": 3979, "text": "y = roots([1, -5])" }, { "code": null, "e": 4072, "s": 3998, "text": "Octave will execute the above statement and return the following result −" }, { "code": null, "e": 4079, "s": 4072, "text": "y = 5\n" }, { "code": null, "e": 4244, "s": 4079, "text": "The solve function can also solve higher order equations. It is often used to solve quadratic equations. The function returns the roots of the equation in an array." }, { "code": null, "e": 4363, "s": 4244, "text": "The following example solves the quadratic equation x2 -7x +12 = 0. Create a script file and type the following code −" }, { "code": null, "e": 4487, "s": 4363, "text": "eq = 'x^2 -7*x + 12 = 0';\ns = solve(eq);\ndisp('The first root is: '), disp(s(1));\ndisp('The second root is: '), disp(s(2));" }, { "code": null, "e": 4545, "s": 4487, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 4597, "s": 4545, "text": "The first root is: \n 3\nThe second root is: \n 4\n" }, { "code": null, "e": 4726, "s": 4597, "text": "The following example solves the quadratic equation x2 -7x +12 = 0 in Octave. Create a script file and type the following code −" }, { "code": null, "e": 4834, "s": 4726, "text": "s = roots([1, -7, 12]);\n\ndisp('The first root is: '), disp(s(1));\ndisp('The second root is: '), disp(s(2));" }, { "code": null, "e": 4892, "s": 4834, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 4944, "s": 4892, "text": "The first root is: \n 4\nThe second root is: \n 3\n" }, { "code": null, "e": 5064, "s": 4944, "text": "The solve function can also solve higher order equations. For example, let us solve a cubic equation as (x-3)2(x-7) = 0" }, { "code": null, "e": 5089, "s": 5064, "text": "solve('(x-3)^2*(x-7)=0')" }, { "code": null, "e": 5163, "s": 5089, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 5185, "s": 5163, "text": "ans =\n 3\n 3\n 7\n" }, { "code": null, "e": 5418, "s": 5185, "text": "In case of higher order equations, roots are long containing many terms. You can get the numerical value of such roots by converting them to double. The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0." }, { "code": null, "e": 5469, "s": 5418, "text": "Create a script file and type the following code −" }, { "code": null, "e": 5961, "s": 5469, "text": "eq = 'x^4 - 7*x^3 + 3*x^2 - 5*x + 9 = 0';\ns = solve(eq);\ndisp('The first root is: '), disp(s(1));\ndisp('The second root is: '), disp(s(2));\ndisp('The third root is: '), disp(s(3));\ndisp('The fourth root is: '), disp(s(4));\n\n% converting the roots to double type\ndisp('Numeric value of first root'), disp(double(s(1)));\ndisp('Numeric value of second root'), disp(double(s(2)));\ndisp('Numeric value of third root'), disp(double(s(3)));\ndisp('Numeric value of fourth root'), disp(double(s(4)));" }, { "code": null, "e": 6018, "s": 5961, "text": "When you run the file, it returns the following result −" }, { "code": null, "e": 6497, "s": 6018, "text": "The first root is: \n6.630396332390718431485053218985\n The second root is: \n1.0597804633025896291682772499885\n The third root is: \n- 0.34508839784665403032666523448675 - 1.0778362954630176596831109269793*i\n The fourth root is: \n- 0.34508839784665403032666523448675 + 1.0778362954630176596831109269793*i\nNumeric value of first root\n 6.6304\nNumeric value of second root\n 1.0598\nNumeric value of third root\n -0.3451 - 1.0778i\nNumeric value of fourth root\n -0.3451 + 1.0778i\n" }, { "code": null, "e": 6554, "s": 6497, "text": "Please note that the last two roots are complex numbers." }, { "code": null, "e": 6638, "s": 6554, "text": "The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0." }, { "code": null, "e": 6689, "s": 6638, "text": "Create a script file and type the following code −" }, { "code": null, "e": 6996, "s": 6689, "text": "v = [1, -7, 3, -5, 9];\ns = roots(v);\n\n% converting the roots to double type\ndisp('Numeric value of first root'), disp(double(s(1)));\ndisp('Numeric value of second root'), disp(double(s(2)));\ndisp('Numeric value of third root'), disp(double(s(3)));\ndisp('Numeric value of fourth root'), disp(double(s(4)));" }, { "code": null, "e": 7053, "s": 6996, "text": "When you run the file, it returns the following result −" }, { "code": null, "e": 7224, "s": 7053, "text": "Numeric value of first root\n 6.6304\nNumeric value of second root\n-0.34509 + 1.07784i\nNumeric value of third root\n-0.34509 - 1.07784i\nNumeric value of fourth root\n 1.0598\n" }, { "code": null, "e": 7398, "s": 7224, "text": "The solve function can also be used to generate solutions of systems of equations involving more than one variables. Let us take up a simple example to demonstrate this use." }, { "code": null, "e": 7427, "s": 7398, "text": "Let us solve the equations −" }, { "code": null, "e": 7439, "s": 7427, "text": "5x + 9y = 5" }, { "code": null, "e": 7451, "s": 7439, "text": "3x – 6y = 4" }, { "code": null, "e": 7502, "s": 7451, "text": "Create a script file and type the following code −" }, { "code": null, "e": 7554, "s": 7502, "text": "s = solve('5*x + 9*y = 5','3*x - 6*y = 4');\ns.x\ns.y" }, { "code": null, "e": 7612, "s": 7554, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 7643, "s": 7612, "text": "ans =\n 22/19\nans =\n -5/57\n" }, { "code": null, "e": 7735, "s": 7643, "text": "In same way, you can solve larger linear systems. Consider the following set of equations −" }, { "code": null, "e": 7750, "s": 7735, "text": "x + 3y -2z = 5" }, { "code": null, "e": 7767, "s": 7750, "text": "3x + 5y + 6z = 7" }, { "code": null, "e": 7784, "s": 7767, "text": "2x + 4y + 3z = 8" }, { "code": null, "e": 7936, "s": 7784, "text": "We have a little different approach to solve a system of 'n' linear equations in 'n' unknowns. Let us take up a simple example to demonstrate this use." }, { "code": null, "e": 7965, "s": 7936, "text": "Let us solve the equations −" }, { "code": null, "e": 7977, "s": 7965, "text": "5x + 9y = 5" }, { "code": null, "e": 7989, "s": 7977, "text": "3x – 6y = 4" }, { "code": null, "e": 8274, "s": 7989, "text": "Such a system of linear equations can be written as the single matrix equation Ax = b, where A is the coefficient matrix, b is the column vector containing the right-hand side of the linear equations and x is the column vector representing the solution as shown in the below program −" }, { "code": null, "e": 8325, "s": 8274, "text": "Create a script file and type the following code −" }, { "code": null, "e": 8361, "s": 8325, "text": "A = [5, 9; 3, -6];\nb = [5;4];\nA \\ b" }, { "code": null, "e": 8419, "s": 8361, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 8451, "s": 8419, "text": "ans =\n\n 1.157895\n -0.087719\n" }, { "code": null, "e": 8517, "s": 8451, "text": "In same way, you can solve larger linear systems as given below −" }, { "code": null, "e": 8532, "s": 8517, "text": "x + 3y -2z = 5" }, { "code": null, "e": 8549, "s": 8532, "text": "3x + 5y + 6z = 7" }, { "code": null, "e": 8566, "s": 8549, "text": "2x + 4y + 3z = 8" }, { "code": null, "e": 8699, "s": 8566, "text": "The expand and the collect function expands and collects an equation respectively. The following example demonstrates the concepts −" }, { "code": null, "e": 8796, "s": 8699, "text": "When you work with many symbolic functions, you should declare that your variables are symbolic." }, { "code": null, "e": 8847, "s": 8796, "text": "Create a script file and type the following code −" }, { "code": null, "e": 9085, "s": 8847, "text": "syms x %symbolic variable x\nsyms y %symbolic variable x\n% expanding equations\nexpand((x-5)*(x+9))\nexpand((x+2)*(x-3)*(x-5)*(x+7))\nexpand(sin(2*x))\nexpand(cos(x+y))\n \n% collecting equations\ncollect(x^3 *(x-7))\ncollect(x^4*(x-3)*(x-5))" }, { "code": null, "e": 9143, "s": 9085, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 9324, "s": 9143, "text": "ans =\n x^2 + 4*x - 45\nans =\n x^4 + x^3 - 43*x^2 + 23*x + 210\nans =\n 2*cos(x)*sin(x)\nans =\n cos(x)*cos(y) - sin(x)*sin(y)\nans =\n x^4 - 7*x^3\nans =\n x^6 - 8*x^5 + 15*x^4\n" }, { "code": null, "e": 9506, "s": 9324, "text": "You need to have symbolic package, which provides expand and the collect function to expand and collect an equation, respectively. The following example demonstrates the concepts −" }, { "code": null, "e": 9741, "s": 9506, "text": "When you work with many symbolic functions, you should declare that your variables are symbolic but Octave has different approach to define symbolic variables. Notice the use of Sin and Cos, which are also defined in symbolic package." }, { "code": null, "e": 9792, "s": 9741, "text": "Create a script file and type the following code −" }, { "code": null, "e": 10168, "s": 9792, "text": "% first of all load the package, make sure its installed.\npkg load symbolic\n\n% make symbols module available\nsymbols\n\n% define symbolic variables\nx = sym ('x');\ny = sym ('y');\nz = sym ('z');\n\n% expanding equations\nexpand((x-5)*(x+9))\nexpand((x+2)*(x-3)*(x-5)*(x+7))\nexpand(Sin(2*x))\nexpand(Cos(x+y))\n \n% collecting equations\ncollect(x^3 *(x-7), z)\ncollect(x^4*(x-3)*(x-5), z)" }, { "code": null, "e": 10226, "s": 10168, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 10386, "s": 10226, "text": "ans =\n\n-45.0+x^2+(4.0)*x\nans =\n\n210.0+x^4-(43.0)*x^2+x^3+(23.0)*x\nans =\n\nsin((2.0)*x)\nans =\n\ncos(y+x)\nans =\n\nx^(3.0)*(-7.0+x)\nans =\n\n(-3.0+x)*x^(4.0)*(-5.0+x)\n" }, { "code": null, "e": 10532, "s": 10386, "text": "The factor function factorizes an expression and the simplify function simplifies an expression. The following example demonstrates the concept −" }, { "code": null, "e": 10583, "s": 10532, "text": "Create a script file and type the following code −" }, { "code": null, "e": 10668, "s": 10583, "text": "syms x\nsyms y\nfactor(x^3 - y^3)\nfactor([x^2-y^2,x^3+y^3])\nsimplify((x^4-16)/(x^2-4))" }, { "code": null, "e": 10726, "s": 10668, "text": "When you run the file, it displays the following result −" } ]
javap tool in Java with Examples
10 May, 2019 javap tool The javap tool is used to get the information of any class or interface. The javap command (also known as the Java Disassembler) disassembles one or more class files. Its output depends on the options used (“-c” or “-verbose” for byte code and byte code along with innards info, respectively). If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it.Syntax: javap [option] [classname] When no options are used:Syntax: javap class_name Output:When Options are used: The description and implementation of options are given below:Note: Some options prints very long output which can’t be shown completely. Please try in your System to view the complete output of options used. -help or –help or -? :This option prints a help message for the javap command.Syntax:javap -help Output: javap -help Output: -version :This option prints Version information of java.Syntax:javap -version Output: javap -version Output: -v or -verbose :This option Prints additional information like stack size, number of locals and arguments for methods.Syntax:javap -v class_name Output: javap -v class_name Output: -l :This option prints line number and local variable tables.Syntax:javap -l class_name Output: javap -l class_name Output: -public :This option prints only public classes and members.Syntax:javap -public class_name Output: javap -public class_name Output: -protected :This option prints protected/public classes and members.Syntax:javap -protected class_name Output: javap -protected class_name Output: -package :This option prints package/protected/public classes and members (default).Syntax:javap -package class_name Output: javap -package class_name Output: -c :This option prints Disassembled code.Syntax:javap -c class_name Output: javap -c class_name Output: -s :This option prints internal type signatures.Syntax:javap -s class_name Output: javap -s class_name Output: -sysinfo :This option prints system info (path, size, date, MD5 hash) of class being processed.Syntax:javap -sysinfo class_name Output: javap -sysinfo class_name Output: -constants :This option prints final constants of class.Syntax:javap -constants class_name Output: javap -constants class_name Output: References: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javap.html java-advanced 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 Multidimensional Arrays in Java Stream In Java Set in Java Singleton Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2019" }, { "code": null, "e": 63, "s": 52, "text": "javap tool" }, { "code": null, "e": 488, "s": 63, "text": "The javap tool is used to get the information of any class or interface. The javap command (also known as the Java Disassembler) disassembles one or more class files. Its output depends on the options used (“-c” or “-verbose” for byte code and byte code along with innards info, respectively). If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it.Syntax:" }, { "code": null, "e": 516, "s": 488, "text": "javap [option] [classname]\n" }, { "code": null, "e": 549, "s": 516, "text": "When no options are used:Syntax:" }, { "code": null, "e": 567, "s": 549, "text": "javap class_name\n" }, { "code": null, "e": 597, "s": 567, "text": "Output:When Options are used:" }, { "code": null, "e": 806, "s": 597, "text": "The description and implementation of options are given below:Note: Some options prints very long output which can’t be shown completely. Please try in your System to view the complete output of options used." }, { "code": null, "e": 911, "s": 806, "text": "-help or –help or -? :This option prints a help message for the javap command.Syntax:javap -help\nOutput:" }, { "code": null, "e": 924, "s": 911, "text": "javap -help\n" }, { "code": null, "e": 932, "s": 924, "text": "Output:" }, { "code": null, "e": 1019, "s": 932, "text": "-version :This option prints Version information of java.Syntax:javap -version\nOutput:" }, { "code": null, "e": 1035, "s": 1019, "text": "javap -version\n" }, { "code": null, "e": 1043, "s": 1035, "text": "Output:" }, { "code": null, "e": 1196, "s": 1043, "text": "-v or -verbose :This option Prints additional information like stack size, number of locals and arguments for methods.Syntax:javap -v class_name\nOutput:" }, { "code": null, "e": 1217, "s": 1196, "text": "javap -v class_name\n" }, { "code": null, "e": 1225, "s": 1217, "text": "Output:" }, { "code": null, "e": 1321, "s": 1225, "text": "-l :This option prints line number and local variable tables.Syntax:javap -l class_name\nOutput:" }, { "code": null, "e": 1342, "s": 1321, "text": "javap -l class_name\n" }, { "code": null, "e": 1350, "s": 1342, "text": "Output:" }, { "code": null, "e": 1450, "s": 1350, "text": "-public :This option prints only public classes and members.Syntax:javap -public class_name\nOutput:" }, { "code": null, "e": 1476, "s": 1450, "text": "javap -public class_name\n" }, { "code": null, "e": 1484, "s": 1476, "text": "Output:" }, { "code": null, "e": 1595, "s": 1484, "text": "-protected :This option prints protected/public classes and members.Syntax:javap -protected class_name\nOutput:" }, { "code": null, "e": 1624, "s": 1595, "text": "javap -protected class_name\n" }, { "code": null, "e": 1632, "s": 1624, "text": "Output:" }, { "code": null, "e": 1757, "s": 1632, "text": "-package :This option prints package/protected/public classes and members (default).Syntax:javap -package class_name\nOutput:" }, { "code": null, "e": 1784, "s": 1757, "text": "javap -package class_name\n" }, { "code": null, "e": 1792, "s": 1784, "text": "Output:" }, { "code": null, "e": 1868, "s": 1792, "text": "-c :This option prints Disassembled code.Syntax:javap -c class_name\nOutput:" }, { "code": null, "e": 1889, "s": 1868, "text": "javap -c class_name\n" }, { "code": null, "e": 1897, "s": 1889, "text": "Output:" }, { "code": null, "e": 1980, "s": 1897, "text": "-s :This option prints internal type signatures.Syntax:javap -s class_name\nOutput:" }, { "code": null, "e": 2001, "s": 1980, "text": "javap -s class_name\n" }, { "code": null, "e": 2009, "s": 2001, "text": "Output:" }, { "code": null, "e": 2145, "s": 2009, "text": "-sysinfo :This option prints system info (path, size, date, MD5 hash) of class being processed.Syntax:javap -sysinfo class_name\nOutput:" }, { "code": null, "e": 2172, "s": 2145, "text": "javap -sysinfo class_name\n" }, { "code": null, "e": 2180, "s": 2172, "text": "Output:" }, { "code": null, "e": 2279, "s": 2180, "text": "-constants :This option prints final constants of class.Syntax:javap -constants class_name\nOutput:" }, { "code": null, "e": 2308, "s": 2279, "text": "javap -constants class_name\n" }, { "code": null, "e": 2316, "s": 2308, "text": "Output:" }, { "code": null, "e": 2401, "s": 2316, "text": "References: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javap.html" }, { "code": null, "e": 2415, "s": 2401, "text": "java-advanced" }, { "code": null, "e": 2420, "s": 2415, "text": "Java" }, { "code": null, "e": 2425, "s": 2420, "text": "Java" }, { "code": null, "e": 2523, "s": 2425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2574, "s": 2523, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2605, "s": 2574, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2624, "s": 2605, "text": "Interfaces in Java" }, { "code": null, "e": 2654, "s": 2624, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2672, "s": 2654, "text": "ArrayList in Java" }, { "code": null, "e": 2692, "s": 2672, "text": "Collections in Java" }, { "code": null, "e": 2724, "s": 2692, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2739, "s": 2724, "text": "Stream In Java" }, { "code": null, "e": 2751, "s": 2739, "text": "Set in Java" } ]
Minimum number of operations on an array to make all elements 0
11 May, 2021 Given an array arr[] of N integers and an integer cost, the task is to calculate the cost of making all the elements of the array 0 with the given operation. In a single operation, an index 0 ≤ i < N and an integer X > 0 can be chosen such that 0 ≤ i + X < N then elements can be updated as arr[i] = arr[i] – 1 and arr[i + X] = arr[i + X] + 1. If i + X ≥ N then only arr[i] will be updated but with twice the regular cost. Print the minimum cost required.Examples: Input: arr[] = {1, 2, 4, 5}, cost = 1 Output: 31 Move 1: i = 0, X = 3, arr[] = {0, 2, 4, 6} (cost = 1) Moves 2 and 3: i = 1, X = 2, arr[] = {0, 0, 4, 8} (cost = 2) Moves 4, 5, 6 and 7: i = 2, X = 1, arr[] = {0, 0, 0, 12} (cost = 4) Move 8: i = 3, X > 0, arr[] = {0, 0, 0, 0} (cost = 24) Total cost = 1 + 2 + 4 + 24 = 31Input: arr[] = {1, 1, 0, 5}, cost = 2 Output: 32 Approach: To minimize the cost, for every index i always choose X such that i + X = N – 1 i.e. the last element then minimum cost can be calculated as: Store the sum of the elements from arr[0] to arr[n – 2] in sum then update totalCost = cost * sum and arr[n – 1] = arr[n – 1] + sum. Now the cost of making all the elements 0 except the last one has been calculated. And the cost of making the last element 0 can be calculated as totalCost = totalCost + (2 * cost * arr[n – 1]). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum costint minCost(int n, int arr[], int cost){ int sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (int i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost;} // Driver codeint main(){ int arr[] = { 1, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int cost = 1; cout << minCost(n, arr, cost);} // Java implementation of the approachpublic class GfG{ // Function to return the minimum cost static int minCost(int n, int arr[], int cost) { int sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (int i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost; } // Driver code public static void main(String []args) { int arr[] = { 1, 2, 4, 5 }; int n = arr.length; int cost = 1; System.out.println(minCost(n, arr, cost)); }} // This code is contributed by Rituraj Jain # Python3 implementation of the approach # Function to return the minimum costdef minCost(n, arr, cost): Sum, totalCost = 0, 0 # Sum of all the array elements # except the last element for i in range(0, n - 1): Sum += arr[i] # Cost of making all the array elements 0 # except the last element totalCost += cost * Sum # Update the last element arr[n - 1] += Sum # Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]) return totalCost # Driver codeif __name__ == "__main__": arr = [1, 2, 4, 5] n = len(arr) cost = 1 print(minCost(n, arr, cost)) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System ; class GfG{ // Function to return the minimum cost static int minCost(int n, int []arr, int cost) { int sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (int i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost; } // Driver code public static void Main() { int []arr = { 1, 2, 4, 5 }; int n = arr.Length; int cost = 1; Console.WriteLine(minCost(n, arr, cost)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to return the minimum costfunction minCost($n, $arr, $cost){ $sum = 0; $totalCost = 0; // Sum of all the array elements // except the last element for ($i = 0; $i < ($n - 1); $i++) $sum += $arr[$i]; // Cost of making all the array // elements 0 except the last element $totalCost += $cost * $sum; // Update the last element $arr[$n - 1] += $sum; // Cost of making the last element 0 $totalCost += (2 * $cost * $arr[$n - 1]); return $totalCost;} // Driver code$arr = array( 1, 2, 4, 5 );$n = sizeof($arr);$cost = 1;echo minCost($n, $arr, $cost); // This code is contributed by ajit?> <script> // Javascript implementation of the approach // Function to return the minimum cost function minCost(n, arr, cost) { let sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (let i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost; } let arr = [ 1, 2, 4, 5 ]; let n = arr.length; let cost = 1; document.write(minCost(n, arr, cost)); </script> 31 Time Complexity: O(n) rituraj_jain ankthon jit_t suresh07 array-traversal-question Algorithms Arrays Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2021" }, { "code": null, "e": 495, "s": 28, "text": "Given an array arr[] of N integers and an integer cost, the task is to calculate the cost of making all the elements of the array 0 with the given operation. In a single operation, an index 0 ≤ i < N and an integer X > 0 can be chosen such that 0 ≤ i + X < N then elements can be updated as arr[i] = arr[i] – 1 and arr[i + X] = arr[i + X] + 1. If i + X ≥ N then only arr[i] will be updated but with twice the regular cost. Print the minimum cost required.Examples: " }, { "code": null, "e": 865, "s": 495, "text": "Input: arr[] = {1, 2, 4, 5}, cost = 1 Output: 31 Move 1: i = 0, X = 3, arr[] = {0, 2, 4, 6} (cost = 1) Moves 2 and 3: i = 1, X = 2, arr[] = {0, 0, 4, 8} (cost = 2) Moves 4, 5, 6 and 7: i = 2, X = 1, arr[] = {0, 0, 0, 12} (cost = 4) Move 8: i = 3, X > 0, arr[] = {0, 0, 0, 0} (cost = 24) Total cost = 1 + 2 + 4 + 24 = 31Input: arr[] = {1, 1, 0, 5}, cost = 2 Output: 32 " }, { "code": null, "e": 1021, "s": 867, "text": "Approach: To minimize the cost, for every index i always choose X such that i + X = N – 1 i.e. the last element then minimum cost can be calculated as: " }, { "code": null, "e": 1154, "s": 1021, "text": "Store the sum of the elements from arr[0] to arr[n – 2] in sum then update totalCost = cost * sum and arr[n – 1] = arr[n – 1] + sum." }, { "code": null, "e": 1349, "s": 1154, "text": "Now the cost of making all the elements 0 except the last one has been calculated. And the cost of making the last element 0 can be calculated as totalCost = totalCost + (2 * cost * arr[n – 1])." }, { "code": null, "e": 1401, "s": 1349, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1405, "s": 1401, "text": "C++" }, { "code": null, "e": 1410, "s": 1405, "text": "Java" }, { "code": null, "e": 1418, "s": 1410, "text": "Python3" }, { "code": null, "e": 1421, "s": 1418, "text": "C#" }, { "code": null, "e": 1425, "s": 1421, "text": "PHP" }, { "code": null, "e": 1436, "s": 1425, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum costint minCost(int n, int arr[], int cost){ int sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (int i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost;} // Driver codeint main(){ int arr[] = { 1, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int cost = 1; cout << minCost(n, arr, cost);}", "e": 2165, "s": 1436, "text": null }, { "code": "// Java implementation of the approachpublic class GfG{ // Function to return the minimum cost static int minCost(int n, int arr[], int cost) { int sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (int i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost; } // Driver code public static void main(String []args) { int arr[] = { 1, 2, 4, 5 }; int n = arr.length; int cost = 1; System.out.println(minCost(n, arr, cost)); }} // This code is contributed by Rituraj Jain", "e": 3071, "s": 2165, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimum costdef minCost(n, arr, cost): Sum, totalCost = 0, 0 # Sum of all the array elements # except the last element for i in range(0, n - 1): Sum += arr[i] # Cost of making all the array elements 0 # except the last element totalCost += cost * Sum # Update the last element arr[n - 1] += Sum # Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]) return totalCost # Driver codeif __name__ == \"__main__\": arr = [1, 2, 4, 5] n = len(arr) cost = 1 print(minCost(n, arr, cost)) # This code is contributed by Rituraj Jain", "e": 3737, "s": 3071, "text": null }, { "code": "// C# implementation of the approachusing System ; class GfG{ // Function to return the minimum cost static int minCost(int n, int []arr, int cost) { int sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (int i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost; } // Driver code public static void Main() { int []arr = { 1, 2, 4, 5 }; int n = arr.Length; int cost = 1; Console.WriteLine(minCost(n, arr, cost)); }} // This code is contributed by Ryuga", "e": 4628, "s": 3737, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the minimum costfunction minCost($n, $arr, $cost){ $sum = 0; $totalCost = 0; // Sum of all the array elements // except the last element for ($i = 0; $i < ($n - 1); $i++) $sum += $arr[$i]; // Cost of making all the array // elements 0 except the last element $totalCost += $cost * $sum; // Update the last element $arr[$n - 1] += $sum; // Cost of making the last element 0 $totalCost += (2 * $cost * $arr[$n - 1]); return $totalCost;} // Driver code$arr = array( 1, 2, 4, 5 );$n = sizeof($arr);$cost = 1;echo minCost($n, $arr, $cost); // This code is contributed by ajit?>", "e": 5317, "s": 4628, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the minimum cost function minCost(n, arr, cost) { let sum = 0, totalCost = 0; // Sum of all the array elements // except the last element for (let i = 0; i < n - 1; i++) sum += arr[i]; // Cost of making all the array elements 0 // except the last element totalCost += cost * sum; // Update the last element arr[n - 1] += sum; // Cost of making the last element 0 totalCost += (2 * cost * arr[n - 1]); return totalCost; } let arr = [ 1, 2, 4, 5 ]; let n = arr.length; let cost = 1; document.write(minCost(n, arr, cost)); </script>", "e": 6094, "s": 5317, "text": null }, { "code": null, "e": 6097, "s": 6094, "text": "31" }, { "code": null, "e": 6122, "s": 6099, "text": "Time Complexity: O(n) " }, { "code": null, "e": 6135, "s": 6122, "text": "rituraj_jain" }, { "code": null, "e": 6143, "s": 6135, "text": "ankthon" }, { "code": null, "e": 6149, "s": 6143, "text": "jit_t" }, { "code": null, "e": 6158, "s": 6149, "text": "suresh07" }, { "code": null, "e": 6183, "s": 6158, "text": "array-traversal-question" }, { "code": null, "e": 6194, "s": 6183, "text": "Algorithms" }, { "code": null, "e": 6201, "s": 6194, "text": "Arrays" }, { "code": null, "e": 6208, "s": 6201, "text": "Arrays" }, { "code": null, "e": 6219, "s": 6208, "text": "Algorithms" }, { "code": null, "e": 6317, "s": 6219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6342, "s": 6317, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6391, "s": 6342, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6429, "s": 6391, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6480, "s": 6429, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 6516, "s": 6480, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 6531, "s": 6516, "text": "Arrays in Java" }, { "code": null, "e": 6577, "s": 6531, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6645, "s": 6577, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6677, "s": 6645, "text": "Largest Sum Contiguous Subarray" } ]
How to use ngfor to make a dropdown in Angular from an array ?
12 Mar, 2021 In this post, we will see how we can display the array elements in the drop-down menu using AngularJS. Sometimes we need to display dynamically fetched data and this is where features ngFor come into the scene. We can iterate over the array, apply conditions and display the data easily. Using ngFor: NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item. Syntax: <tag-name *ngFor="let item of array">{{iter}}</tag-name> <tag-name *ngFor="let key of object">{{key}}</tag-name> Prerequisites: NPM must be preinstalled. Install angular : npm install -g @angular/cli Create a new Angular project: ng new <project-name> cd <project-name> Check the installation by running the project. You should see the angular landing page on http://localhost:4200/ ng serve -o 1. Create a new component: ng g c dropdown 2. It will create a new directory with 4 new files. Open dropdown.component.ts and paste the following code: dropdown.component.ts: Javascript import { Component } from '@angular/core'; @Component({ selector: 'app-dropdown', templateUrl: './dropdown.component.html', styleUrls: ['./dropdown.component.css']})export class DropdownComponent { players = [ "Sachin Tendulkar", "Ricky Ponting", "Virat Kohli", "Kumar Sangakkara", "Jacques Kallis", "Hashim Amla ", "Mahela Jayawardene ", "Brian Lara", "Rahul Dravid", "AB de Villiers" ] selected = "----" update(e){ this.selected = e.target.value }} In above code, we have defined players array that contains the data that we will display in the drop down menu. Additionally we have a selected variable that we will use to display the selected element. The method update() takes an event and sets selected to its value. 3. Now add the following code into dropdown.component.html: dropdown.component.html: HTML <h3>Choose Your Favorite Cricket Player</h3><select #cricket (change)="update($event)"> <option value="default">----</option> <option *ngFor="let player of players" [value]="player"> {{player}} </option></select> <p>You selected {{selected}}</p> We have created a drop-down menu that will use the players array. The options are populated using ngFor. The selected variable is used to display the selected option. 4. Finally add this component into app.component.html: app.component.html: HTML <app-dropdown></app-dropdown> 5. Now run the project and open http://localhost:4200/ to see the results: ng serve -o AngularJS-Questions HTML-Questions Picked AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Mar, 2021" }, { "code": null, "e": 342, "s": 54, "text": "In this post, we will see how we can display the array elements in the drop-down menu using AngularJS. Sometimes we need to display dynamically fetched data and this is where features ngFor come into the scene. We can iterate over the array, apply conditions and display the data easily." }, { "code": null, "e": 504, "s": 342, "text": "Using ngFor: NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item. " }, { "code": null, "e": 512, "s": 504, "text": "Syntax:" }, { "code": null, "e": 627, "s": 512, "text": "<tag-name *ngFor=\"let item of array\">{{iter}}</tag-name>\n<tag-name *ngFor=\"let key of object\">{{key}}</tag-name>" }, { "code": null, "e": 668, "s": 627, "text": "Prerequisites: NPM must be preinstalled." }, { "code": null, "e": 686, "s": 668, "text": "Install angular :" }, { "code": null, "e": 714, "s": 686, "text": "npm install -g @angular/cli" }, { "code": null, "e": 744, "s": 714, "text": "Create a new Angular project:" }, { "code": null, "e": 785, "s": 744, "text": "ng new <project-name>\ncd <project-name> " }, { "code": null, "e": 898, "s": 785, "text": "Check the installation by running the project. You should see the angular landing page on http://localhost:4200/" }, { "code": null, "e": 910, "s": 898, "text": "ng serve -o" }, { "code": null, "e": 937, "s": 910, "text": "1. Create a new component:" }, { "code": null, "e": 953, "s": 937, "text": "ng g c dropdown" }, { "code": null, "e": 1062, "s": 953, "text": "2. It will create a new directory with 4 new files. Open dropdown.component.ts and paste the following code:" }, { "code": null, "e": 1085, "s": 1062, "text": "dropdown.component.ts:" }, { "code": null, "e": 1096, "s": 1085, "text": "Javascript" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-dropdown', templateUrl: './dropdown.component.html', styleUrls: ['./dropdown.component.css']})export class DropdownComponent { players = [ \"Sachin Tendulkar\", \"Ricky Ponting\", \"Virat Kohli\", \"Kumar Sangakkara\", \"Jacques Kallis\", \"Hashim Amla \", \"Mahela Jayawardene \", \"Brian Lara\", \"Rahul Dravid\", \"AB de Villiers\" ] selected = \"----\" update(e){ this.selected = e.target.value }}", "e": 1597, "s": 1096, "text": null }, { "code": null, "e": 1867, "s": 1597, "text": "In above code, we have defined players array that contains the data that we will display in the drop down menu. Additionally we have a selected variable that we will use to display the selected element. The method update() takes an event and sets selected to its value." }, { "code": null, "e": 1927, "s": 1867, "text": "3. Now add the following code into dropdown.component.html:" }, { "code": null, "e": 1952, "s": 1927, "text": "dropdown.component.html:" }, { "code": null, "e": 1957, "s": 1952, "text": "HTML" }, { "code": "<h3>Choose Your Favorite Cricket Player</h3><select #cricket (change)=\"update($event)\"> <option value=\"default\">----</option> <option *ngFor=\"let player of players\" [value]=\"player\"> {{player}} </option></select> <p>You selected {{selected}}</p>", "e": 2220, "s": 1957, "text": null }, { "code": null, "e": 2387, "s": 2220, "text": "We have created a drop-down menu that will use the players array. The options are populated using ngFor. The selected variable is used to display the selected option." }, { "code": null, "e": 2442, "s": 2387, "text": "4. Finally add this component into app.component.html:" }, { "code": null, "e": 2462, "s": 2442, "text": "app.component.html:" }, { "code": null, "e": 2467, "s": 2462, "text": "HTML" }, { "code": "<app-dropdown></app-dropdown>", "e": 2497, "s": 2467, "text": null }, { "code": null, "e": 2572, "s": 2497, "text": "5. Now run the project and open http://localhost:4200/ to see the results:" }, { "code": null, "e": 2584, "s": 2572, "text": "ng serve -o" }, { "code": null, "e": 2604, "s": 2584, "text": "AngularJS-Questions" }, { "code": null, "e": 2619, "s": 2604, "text": "HTML-Questions" }, { "code": null, "e": 2626, "s": 2619, "text": "Picked" }, { "code": null, "e": 2636, "s": 2626, "text": "AngularJS" }, { "code": null, "e": 2641, "s": 2636, "text": "HTML" }, { "code": null, "e": 2658, "s": 2641, "text": "Web Technologies" }, { "code": null, "e": 2663, "s": 2658, "text": "HTML" } ]
Set a Minimum Field Width in Java
The minimum field width specifier is what you include between % and the format conversion code. To include a 0 before the field width specifier, pad with 0's. An integer between the % sign and the format conversion code acts as a minimum field width specifier. Let us see an example − Live Demo import java.util.Formatter; public class Demo { public static void main(String args[]) { Formatter f = new Formatter(); System.out.println(f.format("%08d", 697)); f = new Formatter(); System.out.println(f.format("%10d", 9878)); f = new Formatter(); System.out.println(f.format("%06d", 697)); } } 00000697 9878 000697
[ { "code": null, "e": 1158, "s": 1062, "text": "The minimum field width specifier is what you include between % and the format conversion code." }, { "code": null, "e": 1323, "s": 1158, "text": "To include a 0 before the field width specifier, pad with 0's. An integer between the % sign and the format conversion code acts as a minimum field width specifier." }, { "code": null, "e": 1347, "s": 1323, "text": "Let us see an example −" }, { "code": null, "e": 1358, "s": 1347, "text": " Live Demo" }, { "code": null, "e": 1696, "s": 1358, "text": "import java.util.Formatter;\npublic class Demo {\n public static void main(String args[]) {\n Formatter f = new Formatter();\n System.out.println(f.format(\"%08d\", 697));\n f = new Formatter();\n System.out.println(f.format(\"%10d\", 9878));\n f = new Formatter();\n System.out.println(f.format(\"%06d\", 697));\n }\n}" }, { "code": null, "e": 1722, "s": 1696, "text": "00000697\n 9878\n000697" } ]
Erlang - Databases
Erlang has the ability to connect to the traditional databases such as SQL Server and Oracle. Erlang has an inbuilt odbc library that can be used to work with databases. In our example, we are going to make use of the Microsoft SQL Server. Before connecting to a Microsoft SQL Server database, make sure that the following pointers are checked. You have created a database TESTDB. You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB. User ID "testuser" and password "test123" are set to access TESTDB. Ensure that you have created an ODBC DSN called usersqlserver which creates an ODBC connection to the database Ensure that you have created an ODBC DSN called usersqlserver which creates an ODBC connection to the database To establish a connection to the database, the following code example can be used. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver;UID = testuser;PWD = test123", []), io:fwrite("~p",[Ref]). The output of the above program is as follows − Output <0.33.0> The following things need to be noted about the above program. The start method of the odbc library is used to indicate the beginning of the database operation. The start method of the odbc library is used to indicate the beginning of the database operation. The connect method requires a DSN, user name and password to connect. The connect method requires a DSN, user name and password to connect. The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Erlang. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = testuser;PWD = test123, []), odbc:sql_query(Ref, "CREATE TABLE EMPLOYEE (FIRSTNAME char varying(20), LASTNAME char varying(20), AGE integer, SEX char(1), INCOME integer)") If you now check the database, you will see that a table called EMPLOYEE will be created. It is required when you want to create your records into a database table. The following example will insert a record in the employee table. If the table is successfully updated, the record and the statement will return the value of the updated record and the number of records that were updated. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = testuser;PWD = test123", []), io:fwrite("~p",[odbc:sql_query(Ref, "INSERT INTO EMPLOYEE VALUES('Mac', 'Mohan', 20, 'M', 2000)")]). The output of the above program will be − Output {updated,1} Erlang also has the capability to fetch records from the database. This is done via the sql_query method. An example is shown in the following program − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = testuser;PWD = test123", []), io:fwrite("~p",[odbc:sql_query(Ref, "SELECT * FROM EMPLOYEE") ]). The output of the above program will be as follows − Output {selected,["FIRSTNAME","LASTNAME","AGE","SEX","INCOME"], [{"Mac","Mohan",20,"M",2000}]} So you can see that the insert command in the last section worked and the select command returned the right data. Erlang also has the capability to fetch records from the database based on certain filter criteria. An example is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN=usersqlserver; UID=testuser;PWD=test123", []), io:fwrite("~p",[ odbc:param_query(Ref, "SELECT * FROM EMPLOYEE WHERE SEX=?", [{{sql_char, 1}, ["M"]}])]). The output of the above program will be − Output {selected,["FIRSTNAME","LASTNAME","AGE","SEX","INCOME"], [{"Mac","Mohan",20,"M",2000}]} Erlang also has the capability to update records from the database. An example for the same is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = testuser;PWD = test123", []), io:fwrite("~p",[ odbc:sql_query(Ref, " UPDATE EMPLOYEE SET AGE = 5 WHERE INCOME= 2000")]). The output of the above program will be − Output {updated,1} Erlang also has the capability to delete records from the database. An example for the same is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = testuser;PWD = test123", []), io:fwrite("~p",[ odbc:sql_query(Ref, "DELETE EMPLOYEE WHERE INCOME= 2000")]). The output of the above program will be as follows − Output {updated,1} Erlang also has the capability to describe a table structure. An example is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = testuser;PWD = test123", []), io:fwrite("~p",[odbc:describe_table(Ref, "EMPLOYEE")]). The output of the above program will be as follows − Output {ok,[{"FIRSTNAME",{sql_varchar,20}}, {"LASTNAME",{sql_varchar,20}}, {"AGE",sql_integer}, {"SEX",{sql_char,1}}, {"INCOME",sql_integer}]} Erlang also has the capability to fetch the total count of the records in a table. An example for the same is shown in the following program. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect("DSN = usersqlserver; UID = sa;PWD = demo123", []), io:fwrite("~p",[odbc:select_count(Ref, "SELECT * FROM EMPLOYEE")]). The output of the above program will be − {ok,1} Print Add Notes Bookmark this page
[ { "code": null, "e": 2471, "s": 2301, "text": "Erlang has the ability to connect to the traditional databases such as SQL Server and Oracle. Erlang has an inbuilt odbc library that can be used to work with databases." }, { "code": null, "e": 2646, "s": 2471, "text": "In our example, we are going to make use of the Microsoft SQL Server. Before connecting to a Microsoft SQL Server database, make sure that the following pointers are checked." }, { "code": null, "e": 2682, "s": 2646, "text": "You have created a database TESTDB." }, { "code": null, "e": 2718, "s": 2682, "text": "You have created a database TESTDB." }, { "code": null, "e": 2763, "s": 2718, "text": "You have created a table EMPLOYEE in TESTDB." }, { "code": null, "e": 2808, "s": 2763, "text": "You have created a table EMPLOYEE in TESTDB." }, { "code": null, "e": 2874, "s": 2808, "text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME." }, { "code": null, "e": 2940, "s": 2874, "text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME." }, { "code": null, "e": 3008, "s": 2940, "text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB." }, { "code": null, "e": 3076, "s": 3008, "text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB." }, { "code": null, "e": 3187, "s": 3076, "text": "Ensure that you have created an ODBC DSN called usersqlserver which creates an ODBC connection to the database" }, { "code": null, "e": 3298, "s": 3187, "text": "Ensure that you have created an ODBC DSN called usersqlserver which creates an ODBC connection to the database" }, { "code": null, "e": 3381, "s": 3298, "text": "To establish a connection to the database, the following code example can be used." }, { "code": null, "e": 3389, "s": 3381, "text": "Example" }, { "code": null, "e": 3574, "s": 3389, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() ->\n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver;UID = testuser;PWD = test123\", []), \n io:fwrite(\"~p\",[Ref])." }, { "code": null, "e": 3622, "s": 3574, "text": "The output of the above program is as follows −" }, { "code": null, "e": 3629, "s": 3622, "text": "Output" }, { "code": null, "e": 3639, "s": 3629, "text": "<0.33.0>\n" }, { "code": null, "e": 3702, "s": 3639, "text": "The following things need to be noted about the above program." }, { "code": null, "e": 3800, "s": 3702, "text": "The start method of the odbc library is used to indicate the beginning of the database operation." }, { "code": null, "e": 3898, "s": 3800, "text": "The start method of the odbc library is used to indicate the beginning of the database operation." }, { "code": null, "e": 3968, "s": 3898, "text": "The connect method requires a DSN, user name and password to connect." }, { "code": null, "e": 4038, "s": 3968, "text": "The connect method requires a DSN, user name and password to connect." }, { "code": null, "e": 4206, "s": 4038, "text": "The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Erlang." }, { "code": null, "e": 4214, "s": 4206, "text": "Example" }, { "code": null, "e": 4524, "s": 4214, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = testuser;PWD = test123, []), \n odbc:sql_query(Ref, \"CREATE TABLE EMPLOYEE (FIRSTNAME char varying(20), \n LASTNAME char varying(20), AGE integer, SEX char(1), INCOME integer)\")" }, { "code": null, "e": 4614, "s": 4524, "text": "If you now check the database, you will see that a table called EMPLOYEE will be created." }, { "code": null, "e": 4689, "s": 4614, "text": "It is required when you want to create your records into a database table." }, { "code": null, "e": 4911, "s": 4689, "text": "The following example will insert a record in the employee table. If the table is successfully updated, the record and the statement will return the value of the updated record and the number of records that were updated." }, { "code": null, "e": 4919, "s": 4911, "text": "Example" }, { "code": null, "e": 5188, "s": 4919, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = testuser;PWD = test123\", []), \n io:fwrite(\"~p\",[odbc:sql_query(Ref, \n \"INSERT INTO EMPLOYEE VALUES('Mac', 'Mohan', 20, 'M', 2000)\")])." }, { "code": null, "e": 5230, "s": 5188, "text": "The output of the above program will be −" }, { "code": null, "e": 5237, "s": 5230, "text": "Output" }, { "code": null, "e": 5250, "s": 5237, "text": "{updated,1}\n" }, { "code": null, "e": 5356, "s": 5250, "text": "Erlang also has the capability to fetch records from the database. This is done via the sql_query method." }, { "code": null, "e": 5403, "s": 5356, "text": "An example is shown in the following program −" }, { "code": null, "e": 5411, "s": 5403, "text": "Example" }, { "code": null, "e": 5640, "s": 5411, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() ->\n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = testuser;PWD = test123\", []), \n io:fwrite(\"~p\",[odbc:sql_query(Ref, \"SELECT * FROM EMPLOYEE\") ])." }, { "code": null, "e": 5693, "s": 5640, "text": "The output of the above program will be as follows −" }, { "code": null, "e": 5700, "s": 5693, "text": "Output" }, { "code": null, "e": 5789, "s": 5700, "text": "{selected,[\"FIRSTNAME\",\"LASTNAME\",\"AGE\",\"SEX\",\"INCOME\"],\n[{\"Mac\",\"Mohan\",20,\"M\",2000}]}\n" }, { "code": null, "e": 5903, "s": 5789, "text": "So you can see that the insert command in the last section worked and the select command returned the right data." }, { "code": null, "e": 6003, "s": 5903, "text": "Erlang also has the capability to fetch records from the database based on certain filter criteria." }, { "code": null, "e": 6030, "s": 6003, "text": "An example is as follows −" }, { "code": null, "e": 6038, "s": 6030, "text": "Example" }, { "code": null, "e": 6306, "s": 6038, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN=usersqlserver; UID=testuser;PWD=test123\", []), \n io:fwrite(\"~p\",[ odbc:param_query(Ref, \"SELECT * FROM EMPLOYEE WHERE SEX=?\", \n [{{sql_char, 1}, [\"M\"]}])])." }, { "code": null, "e": 6348, "s": 6306, "text": "The output of the above program will be −" }, { "code": null, "e": 6355, "s": 6348, "text": "Output" }, { "code": null, "e": 6453, "s": 6355, "text": "{selected,[\"FIRSTNAME\",\"LASTNAME\",\"AGE\",\"SEX\",\"INCOME\"],\n [{\"Mac\",\"Mohan\",20,\"M\",2000}]}\n" }, { "code": null, "e": 6521, "s": 6453, "text": "Erlang also has the capability to update records from the database." }, { "code": null, "e": 6561, "s": 6521, "text": "An example for the same is as follows −" }, { "code": null, "e": 6569, "s": 6561, "text": "Example" }, { "code": null, "e": 6834, "s": 6569, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = testuser;PWD = test123\", []), \n \n io:fwrite(\"~p\",[ odbc:sql_query(Ref, \"\n UPDATE EMPLOYEE SET AGE = 5 WHERE INCOME= 2000\")])." }, { "code": null, "e": 6876, "s": 6834, "text": "The output of the above program will be −" }, { "code": null, "e": 6883, "s": 6876, "text": "Output" }, { "code": null, "e": 6896, "s": 6883, "text": "{updated,1}\n" }, { "code": null, "e": 6964, "s": 6896, "text": "Erlang also has the capability to delete records from the database." }, { "code": null, "e": 7004, "s": 6964, "text": "An example for the same is as follows −" }, { "code": null, "e": 7012, "s": 7004, "text": "Example" }, { "code": null, "e": 7254, "s": 7012, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = testuser;PWD = test123\", []), \n io:fwrite(\"~p\",[ odbc:sql_query(Ref, \"DELETE EMPLOYEE WHERE INCOME= 2000\")])." }, { "code": null, "e": 7307, "s": 7254, "text": "The output of the above program will be as follows −" }, { "code": null, "e": 7314, "s": 7307, "text": "Output" }, { "code": null, "e": 7327, "s": 7314, "text": "{updated,1}\n" }, { "code": null, "e": 7389, "s": 7327, "text": "Erlang also has the capability to describe a table structure." }, { "code": null, "e": 7416, "s": 7389, "text": "An example is as follows −" }, { "code": null, "e": 7424, "s": 7416, "text": "Example" }, { "code": null, "e": 7644, "s": 7424, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = testuser;PWD = test123\", []), \n io:fwrite(\"~p\",[odbc:describe_table(Ref, \"EMPLOYEE\")])." }, { "code": null, "e": 7697, "s": 7644, "text": "The output of the above program will be as follows −" }, { "code": null, "e": 7704, "s": 7697, "text": "Output" }, { "code": null, "e": 7853, "s": 7704, "text": "{ok,[{\"FIRSTNAME\",{sql_varchar,20}},\n {\"LASTNAME\",{sql_varchar,20}},\n {\"AGE\",sql_integer},\n {\"SEX\",{sql_char,1}},\n {\"INCOME\",sql_integer}]}\n" }, { "code": null, "e": 7936, "s": 7853, "text": "Erlang also has the capability to fetch the total count of the records in a table." }, { "code": null, "e": 7995, "s": 7936, "text": "An example for the same is shown in the following program." }, { "code": null, "e": 8003, "s": 7995, "text": "Example" }, { "code": null, "e": 8228, "s": 8003, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() ->\n odbc:start(), \n {ok, Ref} = odbc:connect(\"DSN = usersqlserver; UID = sa;PWD = demo123\", []), \n io:fwrite(\"~p\",[odbc:select_count(Ref, \"SELECT * FROM EMPLOYEE\")])." }, { "code": null, "e": 8270, "s": 8228, "text": "The output of the above program will be −" }, { "code": null, "e": 8278, "s": 8270, "text": "{ok,1}\n" }, { "code": null, "e": 8285, "s": 8278, "text": " Print" }, { "code": null, "e": 8296, "s": 8285, "text": " Add Notes" } ]
Classification Algorithms - Naà ̄ve Bayes
Naïve Bayes algorithms is a classification technique based on applying Bayes’ theorem with a strong assumption that all the predictors are independent to each other. In simple words, the assumption is that the presence of a feature in a class is independent to the presence of any other feature in the same class. For example, a phone may be considered as smart if it is having touch screen, internet facility, good camera etc. Though all these features are dependent on each other, they contribute independently to the probability of that the phone is a smart phone. In Bayesian classification, the main interest is to find the posterior probabilities i.e. the probability of a label given some observed features, P(L | features). With the help of Bayes theorem, we can express this in quantitative form as follows − Here, P(L | features) is the posterior probability of class. P(L) is the prior probability of class. P(features | L) is the likelihood which is the probability of predictor given class. P(features) is the prior probability of predictor. Python library, Scikit learn is the most useful library that helps us to build a Naïve Bayes model in Python. We have the following three types of Naïve Bayes model under Scikit learn Python library − It is the simplest Naïve Bayes classifier having the assumption that the data from each label is drawn from a simple Gaussian distribution. Another useful Naïve Bayes classifier is Multinomial Naïve Bayes in which the features are assumed to be drawn from a simple Multinomial distribution. Such kind of Naïve Bayes are most appropriate for the features that represents discrete counts. Another important model is Bernoulli Naïve Bayes in which features are assumed to be binary (0s and 1s). Text classification with ‘bag of words’ model can be an application of Bernoulli Naïve Bayes. Depending on our data set, we can choose any of the Naïve Bayes model explained above. Here, we are implementing Gaussian Naïve Bayes model in Python − We will start with required imports as follows − import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set() Now, by using make_blobs() function of Scikit learn, we can generate blobs of points with Gaussian distribution as follows − from sklearn.datasets import make_blobs X, y = make_blobs(300, 2, centers=2, random_state=2, cluster_std=1.5) plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer'); Next, for using GaussianNB model, we need to import and make its object as follows − from sklearn.naive_bayes import GaussianNB model_GBN = GaussianNB() model_GNB.fit(X, y); Now, we have to do prediction. It can be done after generating some new data as follows − rng = np.random.RandomState(0) Xnew = [-6, -14] + [14, 18] * rng.rand(2000, 2) ynew = model_GNB.predict(Xnew) Next, we are plotting new data to find its boundaries − plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer') lim = plt.axis() plt.scatter(Xnew[:, 0], Xnew[:, 1], c=ynew, s=20, cmap='summer', alpha=0.1) plt.axis(lim); Now, with the help of following line of codes, we can find the posterior probabilities of first and second label − yprob = model_GNB.predict_proba(Xnew) yprob[-10:].round(3) array([[0.998, 0.002], [1. , 0. ], [0.987, 0.013], [1. , 0. ], [1. , 0. ], [1. , 0. ], [1. , 0. ], [1. , 0. ], [0. , 1. ], [0.986, 0.014]] ) The followings are some pros of using Naïve Bayes classifiers − Naïve Bayes classification is easy to implement and fast. Naïve Bayes classification is easy to implement and fast. It will converge faster than discriminative models like logistic regression. It will converge faster than discriminative models like logistic regression. It requires less training data. It requires less training data. It is highly scalable in nature, or they scale linearly with the number of predictors and data points. It is highly scalable in nature, or they scale linearly with the number of predictors and data points. It can make probabilistic predictions and can handle continuous as well as discrete data. It can make probabilistic predictions and can handle continuous as well as discrete data. Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both. Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both. The followings are some cons of using Naïve Bayes classifiers − One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other. One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other. Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction. Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction. The following are some common applications of Naïve Bayes classification − Real-time prediction − Due to its ease of implementation and fast computation, it can be used to do prediction in real-time. Multi-class prediction − Naïve Bayes classification algorithm can be used to predict posterior probability of multiple classes of target variable. Text classification − Due to the feature of multi-class prediction, Naïve Bayes classification algorithms are well suited for text classification. That is why it is also used to solve problems like spam-filtering and sentiment analysis. Recommendation system − Along with the algorithms like collaborative filtering, Naïve Bayes makes a Recommendation system which can be used to filter unseen information and to predict weather a user would like the given resource or not. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2873, "s": 2304, "text": "Naïve Bayes algorithms is a classification technique based on applying Bayes’ theorem with a strong assumption that all the predictors are independent to each other. In simple words, the assumption is that the presence of a feature in a class is independent to the presence of any other feature in the same class. For example, a phone may be considered as smart if it is having touch screen, internet facility, good camera etc. Though all these features are dependent on each other, they contribute independently to the probability of that the phone is a smart phone." }, { "code": null, "e": 3123, "s": 2873, "text": "In Bayesian classification, the main interest is to find the posterior probabilities i.e. the probability of a label given some observed features, P(L | features). With the help of Bayes theorem, we can express this in quantitative form as follows −" }, { "code": null, "e": 3184, "s": 3123, "text": "Here, P(L | features) is the posterior probability of class." }, { "code": null, "e": 3224, "s": 3184, "text": "P(L) is the prior probability of class." }, { "code": null, "e": 3309, "s": 3224, "text": "P(features | L) is the likelihood which is the probability of predictor given class." }, { "code": null, "e": 3360, "s": 3309, "text": "P(features) is the prior probability of predictor." }, { "code": null, "e": 3563, "s": 3360, "text": "Python library, Scikit learn is the most useful library that helps us to build a Naïve Bayes model in Python. We have the following three types of Naïve Bayes model under Scikit learn Python library −" }, { "code": null, "e": 3704, "s": 3563, "text": "It is the simplest Naïve Bayes classifier having the assumption that the data from each label is drawn from a simple Gaussian distribution." }, { "code": null, "e": 3954, "s": 3704, "text": "Another useful Naïve Bayes classifier is Multinomial Naïve Bayes in which the features are assumed to be drawn from a simple Multinomial distribution. Such kind of Naïve Bayes are most appropriate for the features that represents discrete counts." }, { "code": null, "e": 4155, "s": 3954, "text": "Another important model is Bernoulli Naïve Bayes in which features are assumed to be binary (0s and 1s). Text classification with ‘bag of words’ model can be an application of Bernoulli Naïve Bayes." }, { "code": null, "e": 4309, "s": 4155, "text": "Depending on our data set, we can choose any of the Naïve Bayes model explained above. Here, we are implementing Gaussian Naïve Bayes model in Python −" }, { "code": null, "e": 4358, "s": 4309, "text": "We will start with required imports as follows −" }, { "code": null, "e": 4443, "s": 4358, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\n" }, { "code": null, "e": 4568, "s": 4443, "text": "Now, by using make_blobs() function of Scikit learn, we can generate blobs of points with Gaussian distribution as follows −" }, { "code": null, "e": 4736, "s": 4568, "text": "from sklearn.datasets import make_blobs\nX, y = make_blobs(300, 2, centers=2, random_state=2, cluster_std=1.5)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer');\n" }, { "code": null, "e": 4821, "s": 4736, "text": "Next, for using GaussianNB model, we need to import and make its object as follows −" }, { "code": null, "e": 4911, "s": 4821, "text": "from sklearn.naive_bayes import GaussianNB\nmodel_GBN = GaussianNB()\nmodel_GNB.fit(X, y);\n" }, { "code": null, "e": 5001, "s": 4911, "text": "Now, we have to do prediction. It can be done after generating some new data as follows −" }, { "code": null, "e": 5112, "s": 5001, "text": "rng = np.random.RandomState(0)\nXnew = [-6, -14] + [14, 18] * rng.rand(2000, 2)\nynew = model_GNB.predict(Xnew)\n" }, { "code": null, "e": 5168, "s": 5112, "text": "Next, we are plotting new data to find its boundaries −" }, { "code": null, "e": 5333, "s": 5168, "text": "plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')\nlim = plt.axis()\nplt.scatter(Xnew[:, 0], Xnew[:, 1], c=ynew, s=20, cmap='summer', alpha=0.1)\nplt.axis(lim);\n" }, { "code": null, "e": 5448, "s": 5333, "text": "Now, with the help of following line of codes, we can find the posterior probabilities of first and second label −" }, { "code": null, "e": 5508, "s": 5448, "text": "yprob = model_GNB.predict_proba(Xnew)\nyprob[-10:].round(3)\n" }, { "code": null, "e": 5705, "s": 5508, "text": "array([[0.998, 0.002],\n [1. , 0. ],\n [0.987, 0.013],\n [1. , 0. ],\n [1. , 0. ],\n [1. , 0. ],\n [1. , 0. ],\n [1. , 0. ],\n [0. , 1. ],\n [0.986, 0.014]]\n)\n" }, { "code": null, "e": 5770, "s": 5705, "text": "The followings are some pros of using Naïve Bayes classifiers −" }, { "code": null, "e": 5829, "s": 5770, "text": "Naïve Bayes classification is easy to implement and fast." }, { "code": null, "e": 5888, "s": 5829, "text": "Naïve Bayes classification is easy to implement and fast." }, { "code": null, "e": 5965, "s": 5888, "text": "It will converge faster than discriminative models like logistic regression." }, { "code": null, "e": 6042, "s": 5965, "text": "It will converge faster than discriminative models like logistic regression." }, { "code": null, "e": 6074, "s": 6042, "text": "It requires less training data." }, { "code": null, "e": 6106, "s": 6074, "text": "It requires less training data." }, { "code": null, "e": 6209, "s": 6106, "text": "It is highly scalable in nature, or they scale linearly with the number of predictors and data points." }, { "code": null, "e": 6312, "s": 6209, "text": "It is highly scalable in nature, or they scale linearly with the number of predictors and data points." }, { "code": null, "e": 6402, "s": 6312, "text": "It can make probabilistic predictions and can handle continuous as well as discrete data." }, { "code": null, "e": 6492, "s": 6402, "text": "It can make probabilistic predictions and can handle continuous as well as discrete data." }, { "code": null, "e": 6606, "s": 6492, "text": "Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both." }, { "code": null, "e": 6720, "s": 6606, "text": "Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both." }, { "code": null, "e": 6785, "s": 6720, "text": "The followings are some cons of using Naïve Bayes classifiers −" }, { "code": null, "e": 7001, "s": 6785, "text": "One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other." }, { "code": null, "e": 7217, "s": 7001, "text": "One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other." }, { "code": null, "e": 7495, "s": 7217, "text": "Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction." }, { "code": null, "e": 7773, "s": 7495, "text": "Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction." }, { "code": null, "e": 7849, "s": 7773, "text": "The following are some common applications of Naïve Bayes classification −" }, { "code": null, "e": 7974, "s": 7849, "text": "Real-time prediction − Due to its ease of implementation and fast computation, it can be used to do prediction in real-time." }, { "code": null, "e": 8122, "s": 7974, "text": "Multi-class prediction − Naïve Bayes classification algorithm can be used to predict posterior probability of multiple classes of target variable." }, { "code": null, "e": 8360, "s": 8122, "text": "Text classification − Due to the feature of multi-class prediction, Naïve Bayes classification algorithms are well suited for text classification. That is why it is also used to solve problems like spam-filtering and sentiment analysis." }, { "code": null, "e": 8598, "s": 8360, "text": "Recommendation system − Along with the algorithms like collaborative filtering, Naïve Bayes makes a Recommendation system which can be used to filter unseen information and to predict weather a user would like the given resource or not." }, { "code": null, "e": 8635, "s": 8598, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 8658, "s": 8635, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 8694, "s": 8658, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 8722, "s": 8694, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8756, "s": 8722, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 8773, "s": 8756, "text": " Abhilash Nelson" }, { "code": null, "e": 8806, "s": 8773, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 8828, "s": 8806, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8861, "s": 8828, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 8883, "s": 8861, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8916, "s": 8883, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 8938, "s": 8916, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8945, "s": 8938, "text": " Print" }, { "code": null, "e": 8956, "s": 8945, "text": " Add Notes" } ]
Machine Learning with Datetime Feature Engineering: Predicting Healthcare Appointment No-Shows | by Andrew Long | Towards Data Science
Dates and times are rich sources of information that can be used with machine learning models. However, these datetime variables do require some feature engineering to turn them into numerical data. In this post, I will demonstrate how to create datetime features with built in pandas functions for your machine learning models. When I was teaching a machine learning course at Northeastern University, a few of my students used a really interesting dataset (medical appointment no-shows) which I am going to explore in this blog post. Medical appointment no-shows is a large problem in healthcare as approximately 1 in 5 patients will miss their appointment (source). This is an issue for everyone involved: 1) the scheduled patient presumably needs to be seen otherwise they wouldn’t have had an appointment, 2) other patients would have liked to have that spot but couldn’t, 3) healthcare providers must spend extra time to contact and re-schedule the patient as well as wasted any time they used to prepare for the visit. Given the dates and times of scheduling day and appointment day, predict if a patient will miss their medical appointment. Here we will use the medical appointment no-show hosted on Kaggle (https://www.kaggle.com/joniarroba/noshowappointments). This dataset consists of over 110,000 medical appointments. The main three columns we will use for this project are the ScheduledDay (date and time when the appointment was scheduled), AppointmentDay(date of the appointment, no time included), No-Show (binary flag indicating if they no-showed). For the purposes of this post we will ignore the rest of the numerical features (although to be honest they added no value to the AUC). Let’s begin by loading our dataset, creating an output column (1 = no-show, 0= showed up), and converting our datetimes (currently strings) into python datetimes. import pandas as pdimport numpy as npimport matplotlib.pyplot as plt Here I assume that you downloaded the data from Kaggle and placed it in a ‘data’ folder: df = pd.read_csv(‘data/KaggleV2-May-2016.csv’) We can investigate the No-Show column with value_counts Let’s define a binary column OUTPUT_LABEL to indicate Yes = 1, No = 0. df[‘OUTPUT_LABEL’] = (df[‘No-show’] == ‘Yes’).astype(‘int’) We can check the prevalence of our OUTPUT_LABEL: def calc_prevalence(y): return (sum(y)/len(y)) which means that 1 in 5 patients will miss their scheduled appointment. Now let’s work with the datetime columns by looking at the first 5 rows of ScheduledDay and AppointmentDay As you can see, the dtype for both columns is object which means pandas currently views these values as strings. Another thing to point out is that ScheduledDay has times where as Appointment Day has all the times as 00:00:00. We should probably deal with this, but I find it kind of odd that they didn’t included the time of the appointment in the dataset. Presumably, the time of the appointment would be predictive too. To convert these strings into internal datetimes, we can use the pandas function to_datetime . I like to use the format parameter to specifically indicate the format. If you use the format parameter, you have to specify what to do with errors. Here I will make any errors turn into not a datetime (NaT). In general (although not the case here), using the format parameter will speed up the execution of this line. df[‘ScheduledDay’] = pd.to_datetime(df[‘ScheduledDay’], format = ‘%Y-%m-%dT%H:%M:%SZ’, errors = ‘coerce’)df[‘AppointmentDay’] = pd.to_datetime(df[‘AppointmentDay’], format = ‘%Y-%m-%dT%H:%M:%SZ’, errors = ‘coerce’) I haven’t seen T and Z in standard formats before so I just put them in the format string. If someone knows how to handle these better, let me know. Whenever I use the format parameter and if I assume all rows should have dates, I like to put an assertion statement to verify I didn’t get the format incorrect. assert df.ScheduledDay.isnull().sum() == 0, ‘missing ScheduledDay dates’assert df.AppointmentDay.isnull().sum() == 0, ‘missing AppointmentDay dates’ If you check the dtype now, you will see it is datetime64, which is what we want because it exposes us to all the datetime properties in pandas. One thing I noticed was that currently there are ~40k appointments that were scheduled after the appointment datetime. I think this is due to the fact that all the appointment times were set at the earliest time (00:00:00) whereas the times are included in ScheduledDay. To adjust for this, lets just shift all the appointment times to the end of the day. If I was doing this project for work, I would actually go and get the appointment times. df[‘AppointmentDay’] = df[‘AppointmentDay’] +pd.Timedelta(‘1d’) — pd.Timedelta(‘1s’) With this change there are only 5 rows where scheduledDay time is after appointmentDay. Let’s just drop those rows. By converting the strings into datetimes, this exposes all the pandas dt properties. Basically you can break apart the date and get the year, month, week of year, day of month, hour, minute, second, etc. You can also get the day of the week (Monday = 0, Sunday = 6). Note be careful with week of year because the first few days of the year may be 53 if that week begins in the prior year. Let’s apply some of these properties to both of our datetime columns. df[‘ScheduledDay_year’] = df[‘ScheduledDay’].dt.yeardf[‘ScheduledDay_month’] = df[‘ScheduledDay’].dt.monthdf[‘ScheduledDay_week’] = df[‘ScheduledDay’].dt.weekdf[‘ScheduledDay_day’] = df[‘ScheduledDay’].dt.daydf[‘ScheduledDay_hour’] = df[‘ScheduledDay’].dt.hourdf[‘ScheduledDay_minute’] = df[‘ScheduledDay’].dt.minutedf[‘ScheduledDay_dayofweek’] = df[‘ScheduledDay’].dt.dayofweekdf[‘AppointmentDay_year’] = df[‘AppointmentDay’].dt.yeardf[‘AppointmentDay_month’] = df[‘AppointmentDay’].dt.monthdf[‘AppointmentDay_week’] = df[‘AppointmentDay’].dt.weekdf[‘AppointmentDay_day’] = df[‘AppointmentDay’].dt.daydf[‘AppointmentDay_hour’] = df[‘AppointmentDay’].dt.hourdf[‘AppointmentDay_minute’] = df[‘AppointmentDay’].dt.minutedf[‘AppointmentDay_dayofweek’] = df[‘AppointmentDay’].dt.dayofweek You can verify this works: At this point it would be good to explore our dates a bit. As you can see here, the appointments are in April, May and June of 2016 and range from Monday through Saturday with no appointments on Sunday. I would never use Year as a feature (but showed it anyways) because presumably we want to use this predictive model in the future and those future years wouldn’t be included in the dataset. However, I am kind of disappointed that the months are just for a few months of the year. This means month (and consequently week of year) probably shouldn’t be used as a feature either. If I was doing this for work, I would go back to the database and get a whole year’s (or many years) worth of data. I would imagine that certain times of the year (ie around holidays) would impact the rate of no show. Let’s quickly check if dayofweek is predictive of no-show: Looks like more people skip their appointments on Friday and Saturday, although the effect is modest. Another nice thing with pandas datetime representation is that you can calculate the ‘time’ between datetimes. Let’s create a new feature that is the number of days between the scheduled date and the appointment date. df[‘delta_days’] = (df[‘AppointmentDay’]-df[‘ScheduledDay’]).dt.total_seconds()/(60*60*24) Note that here I use total_seconds . There is a function dt.days but I got in the habit of using total_seconds because 1) dt.days rounds to the nearest day, 2) dt.days used to take much longer than total_seconds. The second point seems to have been fixed in later versions of pandas. We can plot the histogram of our two classes on this variable: plt.hist(df.loc[df.OUTPUT_LABEL == 1,’delta_days’], label = ‘Missed’,bins = range(0,60,1), normed = True)plt.hist(df.loc[df.OUTPUT_LABEL == 0,’delta_days’], label = ‘Not Missed’,bins = range(0,60,1), normed = True,alpha =0.5)plt.legend()plt.xlabel(‘days until appointment’)plt.ylabel(‘normed distribution’)plt.xlim(0,40)plt.show() This distribution is a bit odd to me since most of the patients who did not miss their appointment scheduled the appointment on the same day. I kind of wonder if walk-in appointments are included in this data set. My guess is that this model will just draw a line at 1 day and say not-missed if you scheduled it the same day. We are now ready to split our samples and train a model! For simplicity, I’ll just split into two datasets: train (70%) and validation (30%). It is important to shuffle your samples because you may have been given the data in order of dates. # shuffle the samplesdf = df.sample(n = len(df), random_state = 42)df = df.reset_index(drop = True)df_valid = df.sample(frac = 0.3, random_state = 42)df_train = df.drop(df_valid.index) We can check the prevalence is about 20% in each: print(‘Valid prevalence(n = %d):%.3f’%(len(df_valid),calc_prevalence(df_valid.OUTPUT_LABEL.values)))print(‘Train prevalence(n = %d):%.3f’%(len(df_train), calc_prevalence(df_train.OUTPUT_LABEL.values))) Given this data comes from just Apr-Jun 2016 and their are no appointment times, we will just use these columns: col2use = [‘ScheduledDay_day’, ‘ScheduledDay_hour’, ‘ScheduledDay_minute’, ‘ScheduledDay_dayofweek’, ‘AppointmentDay_day’, ‘AppointmentDay_dayofweek’, ‘delta_days’] The ‘day’ features may even be suspect, but let’s leave in for now. This could be expanded if we had: appointments from the entire calendar year appointment times We can now build our X (inputs) and Y(output) for training and validation: X_train = df_train[col2use].valuesX_valid = df_valid[col2use].valuesy_train = df_train[‘OUTPUT_LABEL’].valuesy_valid = df_valid[‘OUTPUT_LABEL’].valuesprint(‘Training shapes:’,X_train.shape, y_train.shape)print(‘Validation shapes:’,X_valid.shape, y_valid.shape) Since the focus of this post is about the datetime features, we will just train a random forest model here. Note if you want to use other types of models, you may need to scale or normalize your data. Another thing you may want to do is convert the dayofweek into a categorical variable via one-hot encoding. We don’t need to do these things for a tree-based method though. from sklearn.ensemble import RandomForestClassifierrf=RandomForestClassifier(max_depth = 5, n_estimators=100, random_state = 42)rf.fit(X_train, y_train) We can then get our predictions with: y_train_preds = rf.predict_proba(X_train)[:,1]y_valid_preds = rf.predict_proba(X_valid)[:,1] Here we will evaluate performance of the model. If you are new to classification metrics, I recommend checking out my posts about these metrics (technical post or non-technical post) . from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_scoredef calc_specificity(y_actual, y_pred, thresh): # calculates specificity return sum((y_pred < thresh) & (y_actual == 0)) /sum(y_actual ==0)def print_report(y_actual, y_pred, thresh): auc = roc_auc_score(y_actual, y_pred) accuracy = accuracy_score(y_actual, (y_pred > thresh)) recall = recall_score(y_actual, (y_pred > thresh)) precision = precision_score(y_actual, (y_pred > thresh)) specificity = calc_specificity(y_actual, y_pred, thresh) print(‘AUC:%.3f’%auc) print(‘accuracy:%.3f’%accuracy) print(‘recall:%.3f’%recall) print(‘precision:%.3f’%precision) print(‘specificity:%.3f’%specificity) print(‘prevalence:%.3f’%calc_prevalence(y_actual)) print(‘ ‘) return auc, accuracy, recall, precision, specificity Using this print_report function we can evaluate the performance for training and validation. Here I set the threshold at the prevalence of 0.201 We can plot the ROC with from sklearn.metrics import roc_curvefpr_train, tpr_train, thresholds_train = roc_curve(y_train, y_train_preds)auc_train = roc_auc_score(y_train, y_train_preds)fpr_valid, tpr_valid, thresholds_valid = roc_curve(y_valid, y_valid_preds)auc_valid = roc_auc_score(y_valid, y_valid_preds)plt.plot(fpr_train, tpr_train, ‘r-’,label =’Train AUC:%.3f’%auc_train)plt.plot(fpr_valid, tpr_valid, ‘b-’,label =’Valid AUC:%.3f’%auc_valid)plt.plot([0,1],[0,1],’k — ‘)plt.xlabel(‘False Positive Rate’)plt.ylabel(‘True Positive Rate’)plt.legend()plt.show() This indicates that we can get an AUC of 0.71 with just using datetime features. This ROC curve is kind of odd since it has that elbow. We can investigate this a bit by looking at the top features feature_importances = pd.DataFrame(rf.feature_importances_, index = col2use, columns=[‘importance’]).sort_values(‘importance’, ascending=False)num = min([50,len(col2use)])ylocs = np.arange(num)# get the feature importance for top num and sort in reverse ordervalues_to_plot = feature_importances.iloc[:num].values.ravel()[::-1]feature_labels = list(feature_importances.iloc[:num].index)[::-1]plt.figure(num=None, figsize=(6, 6), dpi=80, facecolor=’w’, edgecolor=’k’);plt.barh(ylocs, values_to_plot, align = ‘center’)plt.ylabel(‘Features’)plt.xlabel(‘Importance Score’)plt.title(‘Feature Importance Score — Random Forest’)plt.yticks(ylocs, feature_labels)plt.show() Which shows that delta_days is basically the only features used in the model. This confirms our suspicion above that the model will likely struggle due to those same day appointments. Since our training and validation scores are very similar, this means that we are in the case of high bias. In order to improve this model, we will need additional features, so I will end this project here. In this project, we created many new features by unpacking the datetime variables to predict if a patient will no-show. In my experience, datetime features can have a big impact on healthcare machine learning models. I highly recommend trying this in your next project. Please reach out if you have any questions or concerns about this post.
[ { "code": null, "e": 500, "s": 171, "text": "Dates and times are rich sources of information that can be used with machine learning models. However, these datetime variables do require some feature engineering to turn them into numerical data. In this post, I will demonstrate how to create datetime features with built in pandas functions for your machine learning models." }, { "code": null, "e": 1197, "s": 500, "text": "When I was teaching a machine learning course at Northeastern University, a few of my students used a really interesting dataset (medical appointment no-shows) which I am going to explore in this blog post. Medical appointment no-shows is a large problem in healthcare as approximately 1 in 5 patients will miss their appointment (source). This is an issue for everyone involved: 1) the scheduled patient presumably needs to be seen otherwise they wouldn’t have had an appointment, 2) other patients would have liked to have that spot but couldn’t, 3) healthcare providers must spend extra time to contact and re-schedule the patient as well as wasted any time they used to prepare for the visit." }, { "code": null, "e": 1320, "s": 1197, "text": "Given the dates and times of scheduling day and appointment day, predict if a patient will miss their medical appointment." }, { "code": null, "e": 1874, "s": 1320, "text": "Here we will use the medical appointment no-show hosted on Kaggle (https://www.kaggle.com/joniarroba/noshowappointments). This dataset consists of over 110,000 medical appointments. The main three columns we will use for this project are the ScheduledDay (date and time when the appointment was scheduled), AppointmentDay(date of the appointment, no time included), No-Show (binary flag indicating if they no-showed). For the purposes of this post we will ignore the rest of the numerical features (although to be honest they added no value to the AUC)." }, { "code": null, "e": 2037, "s": 1874, "text": "Let’s begin by loading our dataset, creating an output column (1 = no-show, 0= showed up), and converting our datetimes (currently strings) into python datetimes." }, { "code": null, "e": 2106, "s": 2037, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt" }, { "code": null, "e": 2195, "s": 2106, "text": "Here I assume that you downloaded the data from Kaggle and placed it in a ‘data’ folder:" }, { "code": null, "e": 2242, "s": 2195, "text": "df = pd.read_csv(‘data/KaggleV2-May-2016.csv’)" }, { "code": null, "e": 2298, "s": 2242, "text": "We can investigate the No-Show column with value_counts" }, { "code": null, "e": 2369, "s": 2298, "text": "Let’s define a binary column OUTPUT_LABEL to indicate Yes = 1, No = 0." }, { "code": null, "e": 2429, "s": 2369, "text": "df[‘OUTPUT_LABEL’] = (df[‘No-show’] == ‘Yes’).astype(‘int’)" }, { "code": null, "e": 2478, "s": 2429, "text": "We can check the prevalence of our OUTPUT_LABEL:" }, { "code": null, "e": 2525, "s": 2478, "text": "def calc_prevalence(y): return (sum(y)/len(y))" }, { "code": null, "e": 2597, "s": 2525, "text": "which means that 1 in 5 patients will miss their scheduled appointment." }, { "code": null, "e": 2704, "s": 2597, "text": "Now let’s work with the datetime columns by looking at the first 5 rows of ScheduledDay and AppointmentDay" }, { "code": null, "e": 3127, "s": 2704, "text": "As you can see, the dtype for both columns is object which means pandas currently views these values as strings. Another thing to point out is that ScheduledDay has times where as Appointment Day has all the times as 00:00:00. We should probably deal with this, but I find it kind of odd that they didn’t included the time of the appointment in the dataset. Presumably, the time of the appointment would be predictive too." }, { "code": null, "e": 3541, "s": 3127, "text": "To convert these strings into internal datetimes, we can use the pandas function to_datetime . I like to use the format parameter to specifically indicate the format. If you use the format parameter, you have to specify what to do with errors. Here I will make any errors turn into not a datetime (NaT). In general (although not the case here), using the format parameter will speed up the execution of this line." }, { "code": null, "e": 3760, "s": 3541, "text": "df[‘ScheduledDay’] = pd.to_datetime(df[‘ScheduledDay’], format = ‘%Y-%m-%dT%H:%M:%SZ’, errors = ‘coerce’)df[‘AppointmentDay’] = pd.to_datetime(df[‘AppointmentDay’], format = ‘%Y-%m-%dT%H:%M:%SZ’, errors = ‘coerce’)" }, { "code": null, "e": 3909, "s": 3760, "text": "I haven’t seen T and Z in standard formats before so I just put them in the format string. If someone knows how to handle these better, let me know." }, { "code": null, "e": 4071, "s": 3909, "text": "Whenever I use the format parameter and if I assume all rows should have dates, I like to put an assertion statement to verify I didn’t get the format incorrect." }, { "code": null, "e": 4220, "s": 4071, "text": "assert df.ScheduledDay.isnull().sum() == 0, ‘missing ScheduledDay dates’assert df.AppointmentDay.isnull().sum() == 0, ‘missing AppointmentDay dates’" }, { "code": null, "e": 4365, "s": 4220, "text": "If you check the dtype now, you will see it is datetime64, which is what we want because it exposes us to all the datetime properties in pandas." }, { "code": null, "e": 4484, "s": 4365, "text": "One thing I noticed was that currently there are ~40k appointments that were scheduled after the appointment datetime." }, { "code": null, "e": 4810, "s": 4484, "text": "I think this is due to the fact that all the appointment times were set at the earliest time (00:00:00) whereas the times are included in ScheduledDay. To adjust for this, lets just shift all the appointment times to the end of the day. If I was doing this project for work, I would actually go and get the appointment times." }, { "code": null, "e": 4895, "s": 4810, "text": "df[‘AppointmentDay’] = df[‘AppointmentDay’] +pd.Timedelta(‘1d’) — pd.Timedelta(‘1s’)" }, { "code": null, "e": 5011, "s": 4895, "text": "With this change there are only 5 rows where scheduledDay time is after appointmentDay. Let’s just drop those rows." }, { "code": null, "e": 5096, "s": 5011, "text": "By converting the strings into datetimes, this exposes all the pandas dt properties." }, { "code": null, "e": 5470, "s": 5096, "text": "Basically you can break apart the date and get the year, month, week of year, day of month, hour, minute, second, etc. You can also get the day of the week (Monday = 0, Sunday = 6). Note be careful with week of year because the first few days of the year may be 53 if that week begins in the prior year. Let’s apply some of these properties to both of our datetime columns." }, { "code": null, "e": 6255, "s": 5470, "text": "df[‘ScheduledDay_year’] = df[‘ScheduledDay’].dt.yeardf[‘ScheduledDay_month’] = df[‘ScheduledDay’].dt.monthdf[‘ScheduledDay_week’] = df[‘ScheduledDay’].dt.weekdf[‘ScheduledDay_day’] = df[‘ScheduledDay’].dt.daydf[‘ScheduledDay_hour’] = df[‘ScheduledDay’].dt.hourdf[‘ScheduledDay_minute’] = df[‘ScheduledDay’].dt.minutedf[‘ScheduledDay_dayofweek’] = df[‘ScheduledDay’].dt.dayofweekdf[‘AppointmentDay_year’] = df[‘AppointmentDay’].dt.yeardf[‘AppointmentDay_month’] = df[‘AppointmentDay’].dt.monthdf[‘AppointmentDay_week’] = df[‘AppointmentDay’].dt.weekdf[‘AppointmentDay_day’] = df[‘AppointmentDay’].dt.daydf[‘AppointmentDay_hour’] = df[‘AppointmentDay’].dt.hourdf[‘AppointmentDay_minute’] = df[‘AppointmentDay’].dt.minutedf[‘AppointmentDay_dayofweek’] = df[‘AppointmentDay’].dt.dayofweek" }, { "code": null, "e": 6282, "s": 6255, "text": "You can verify this works:" }, { "code": null, "e": 6341, "s": 6282, "text": "At this point it would be good to explore our dates a bit." }, { "code": null, "e": 7080, "s": 6341, "text": "As you can see here, the appointments are in April, May and June of 2016 and range from Monday through Saturday with no appointments on Sunday. I would never use Year as a feature (but showed it anyways) because presumably we want to use this predictive model in the future and those future years wouldn’t be included in the dataset. However, I am kind of disappointed that the months are just for a few months of the year. This means month (and consequently week of year) probably shouldn’t be used as a feature either. If I was doing this for work, I would go back to the database and get a whole year’s (or many years) worth of data. I would imagine that certain times of the year (ie around holidays) would impact the rate of no show." }, { "code": null, "e": 7139, "s": 7080, "text": "Let’s quickly check if dayofweek is predictive of no-show:" }, { "code": null, "e": 7241, "s": 7139, "text": "Looks like more people skip their appointments on Friday and Saturday, although the effect is modest." }, { "code": null, "e": 7459, "s": 7241, "text": "Another nice thing with pandas datetime representation is that you can calculate the ‘time’ between datetimes. Let’s create a new feature that is the number of days between the scheduled date and the appointment date." }, { "code": null, "e": 7550, "s": 7459, "text": "df[‘delta_days’] = (df[‘AppointmentDay’]-df[‘ScheduledDay’]).dt.total_seconds()/(60*60*24)" }, { "code": null, "e": 7834, "s": 7550, "text": "Note that here I use total_seconds . There is a function dt.days but I got in the habit of using total_seconds because 1) dt.days rounds to the nearest day, 2) dt.days used to take much longer than total_seconds. The second point seems to have been fixed in later versions of pandas." }, { "code": null, "e": 7897, "s": 7834, "text": "We can plot the histogram of our two classes on this variable:" }, { "code": null, "e": 8230, "s": 7897, "text": "plt.hist(df.loc[df.OUTPUT_LABEL == 1,’delta_days’], label = ‘Missed’,bins = range(0,60,1), normed = True)plt.hist(df.loc[df.OUTPUT_LABEL == 0,’delta_days’], label = ‘Not Missed’,bins = range(0,60,1), normed = True,alpha =0.5)plt.legend()plt.xlabel(‘days until appointment’)plt.ylabel(‘normed distribution’)plt.xlim(0,40)plt.show()" }, { "code": null, "e": 8556, "s": 8230, "text": "This distribution is a bit odd to me since most of the patients who did not miss their appointment scheduled the appointment on the same day. I kind of wonder if walk-in appointments are included in this data set. My guess is that this model will just draw a line at 1 day and say not-missed if you scheduled it the same day." }, { "code": null, "e": 8613, "s": 8556, "text": "We are now ready to split our samples and train a model!" }, { "code": null, "e": 8798, "s": 8613, "text": "For simplicity, I’ll just split into two datasets: train (70%) and validation (30%). It is important to shuffle your samples because you may have been given the data in order of dates." }, { "code": null, "e": 8983, "s": 8798, "text": "# shuffle the samplesdf = df.sample(n = len(df), random_state = 42)df = df.reset_index(drop = True)df_valid = df.sample(frac = 0.3, random_state = 42)df_train = df.drop(df_valid.index)" }, { "code": null, "e": 9033, "s": 8983, "text": "We can check the prevalence is about 20% in each:" }, { "code": null, "e": 9235, "s": 9033, "text": "print(‘Valid prevalence(n = %d):%.3f’%(len(df_valid),calc_prevalence(df_valid.OUTPUT_LABEL.values)))print(‘Train prevalence(n = %d):%.3f’%(len(df_train), calc_prevalence(df_train.OUTPUT_LABEL.values)))" }, { "code": null, "e": 9348, "s": 9235, "text": "Given this data comes from just Apr-Jun 2016 and their are no appointment times, we will just use these columns:" }, { "code": null, "e": 9514, "s": 9348, "text": "col2use = [‘ScheduledDay_day’, ‘ScheduledDay_hour’, ‘ScheduledDay_minute’, ‘ScheduledDay_dayofweek’, ‘AppointmentDay_day’, ‘AppointmentDay_dayofweek’, ‘delta_days’]" }, { "code": null, "e": 9582, "s": 9514, "text": "The ‘day’ features may even be suspect, but let’s leave in for now." }, { "code": null, "e": 9616, "s": 9582, "text": "This could be expanded if we had:" }, { "code": null, "e": 9659, "s": 9616, "text": "appointments from the entire calendar year" }, { "code": null, "e": 9677, "s": 9659, "text": "appointment times" }, { "code": null, "e": 9752, "s": 9677, "text": "We can now build our X (inputs) and Y(output) for training and validation:" }, { "code": null, "e": 10013, "s": 9752, "text": "X_train = df_train[col2use].valuesX_valid = df_valid[col2use].valuesy_train = df_train[‘OUTPUT_LABEL’].valuesy_valid = df_valid[‘OUTPUT_LABEL’].valuesprint(‘Training shapes:’,X_train.shape, y_train.shape)print(‘Validation shapes:’,X_valid.shape, y_valid.shape)" }, { "code": null, "e": 10387, "s": 10013, "text": "Since the focus of this post is about the datetime features, we will just train a random forest model here. Note if you want to use other types of models, you may need to scale or normalize your data. Another thing you may want to do is convert the dayofweek into a categorical variable via one-hot encoding. We don’t need to do these things for a tree-based method though." }, { "code": null, "e": 10540, "s": 10387, "text": "from sklearn.ensemble import RandomForestClassifierrf=RandomForestClassifier(max_depth = 5, n_estimators=100, random_state = 42)rf.fit(X_train, y_train)" }, { "code": null, "e": 10578, "s": 10540, "text": "We can then get our predictions with:" }, { "code": null, "e": 10671, "s": 10578, "text": "y_train_preds = rf.predict_proba(X_train)[:,1]y_valid_preds = rf.predict_proba(X_valid)[:,1]" }, { "code": null, "e": 10856, "s": 10671, "text": "Here we will evaluate performance of the model. If you are new to classification metrics, I recommend checking out my posts about these metrics (technical post or non-technical post) ." }, { "code": null, "e": 11655, "s": 10856, "text": "from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_scoredef calc_specificity(y_actual, y_pred, thresh): # calculates specificity return sum((y_pred < thresh) & (y_actual == 0)) /sum(y_actual ==0)def print_report(y_actual, y_pred, thresh): auc = roc_auc_score(y_actual, y_pred) accuracy = accuracy_score(y_actual, (y_pred > thresh)) recall = recall_score(y_actual, (y_pred > thresh)) precision = precision_score(y_actual, (y_pred > thresh)) specificity = calc_specificity(y_actual, y_pred, thresh) print(‘AUC:%.3f’%auc) print(‘accuracy:%.3f’%accuracy) print(‘recall:%.3f’%recall) print(‘precision:%.3f’%precision) print(‘specificity:%.3f’%specificity) print(‘prevalence:%.3f’%calc_prevalence(y_actual)) print(‘ ‘) return auc, accuracy, recall, precision, specificity" }, { "code": null, "e": 11801, "s": 11655, "text": "Using this print_report function we can evaluate the performance for training and validation. Here I set the threshold at the prevalence of 0.201" }, { "code": null, "e": 11826, "s": 11801, "text": "We can plot the ROC with" }, { "code": null, "e": 12365, "s": 11826, "text": "from sklearn.metrics import roc_curvefpr_train, tpr_train, thresholds_train = roc_curve(y_train, y_train_preds)auc_train = roc_auc_score(y_train, y_train_preds)fpr_valid, tpr_valid, thresholds_valid = roc_curve(y_valid, y_valid_preds)auc_valid = roc_auc_score(y_valid, y_valid_preds)plt.plot(fpr_train, tpr_train, ‘r-’,label =’Train AUC:%.3f’%auc_train)plt.plot(fpr_valid, tpr_valid, ‘b-’,label =’Valid AUC:%.3f’%auc_valid)plt.plot([0,1],[0,1],’k — ‘)plt.xlabel(‘False Positive Rate’)plt.ylabel(‘True Positive Rate’)plt.legend()plt.show()" }, { "code": null, "e": 12501, "s": 12365, "text": "This indicates that we can get an AUC of 0.71 with just using datetime features. This ROC curve is kind of odd since it has that elbow." }, { "code": null, "e": 12562, "s": 12501, "text": "We can investigate this a bit by looking at the top features" }, { "code": null, "e": 13227, "s": 12562, "text": "feature_importances = pd.DataFrame(rf.feature_importances_, index = col2use, columns=[‘importance’]).sort_values(‘importance’, ascending=False)num = min([50,len(col2use)])ylocs = np.arange(num)# get the feature importance for top num and sort in reverse ordervalues_to_plot = feature_importances.iloc[:num].values.ravel()[::-1]feature_labels = list(feature_importances.iloc[:num].index)[::-1]plt.figure(num=None, figsize=(6, 6), dpi=80, facecolor=’w’, edgecolor=’k’);plt.barh(ylocs, values_to_plot, align = ‘center’)plt.ylabel(‘Features’)plt.xlabel(‘Importance Score’)plt.title(‘Feature Importance Score — Random Forest’)plt.yticks(ylocs, feature_labels)plt.show()" }, { "code": null, "e": 13411, "s": 13227, "text": "Which shows that delta_days is basically the only features used in the model. This confirms our suspicion above that the model will likely struggle due to those same day appointments." }, { "code": null, "e": 13618, "s": 13411, "text": "Since our training and validation scores are very similar, this means that we are in the case of high bias. In order to improve this model, we will need additional features, so I will end this project here." } ]
Extract keywords from documents, an unsupervised solution | by Andrew Zhu | Towards Data Science
Imagine you have millions(maybe billions) of text documents in hand. No matter it is customer support tickets, social media data, or community forum posts. There were no tags when the data was generated. You are scratching your head hard to giving tags to those random documents. Manually tagging is unpractical; Giving an existing tagging list will be outdated soon. Hiring a vendor company to do the tagging work is too much expensive. You may say, why not using Machine Learning? like, Neral Network deep learning. But, NN needs some training data first. The training data that right fit your dataset. So, is there a solution that we can give documents tagging meet: Need no pre-request training data.Minimum manual interference and can automatically run.Capture new words and phrases automatically. Need no pre-request training data. Minimum manual interference and can automatically run. Capture new words and phrases automatically. This article is logging how I extracted keywords, how it works, walkarounds, in Python. Note that the code in this article was run and test in Jupyter Notebook. If you run a code block but welcomed with a missing import package error, this package must have been imported already somewhere ahead. TF-IDF is a widely used algorithm that evaluates how relevant a word is to a document in a collection of documents. In my previous article: Measure Text Weight using TF-IDF in Python and scikit-learn, I used a simple sample to show how to calculate the TF-IDF value for all words in a document. In both pure Python code and using scikit-learn package. Based on TF-IDF, those unique and important words should have high TF-IDF values in a certain document. So, in theory, we should be able to leverage the text weight # to extract the most important words of a document. For example, a document talks about scikit-learn should include much high density of keywords scikit-learn, while another document talks about “pandas” should have a high TF-IDF value for pandas. Since I can’t use my daily work database here and also ensure you can perform the keywords extraction sample code in your local machine with minimum efforts. I found the Reuters document corpus from NLTK is a good target for keyword extraction. In case you are not familiar with NLTK corpus, this article may be helpful to get NLTK started in less than one hour: Book Writing Pattern Analysis — Get start with NLTK and Python text analysis with a use case. To download the Reuters corpus. run Python code: import nltknltk.download("reuters") List all documents ids from the corpus we just downloaded. from nltk.corpus import reutersreuters.fileids() Check out one document's content, and its category. fileid = reuters.fileids()[202]print(fileid,"\n" ,reuters.raw(fileid),"\n" ,reuters.categories(fileid),"\n") Reuters corpus is organized by overlapping categories. We can also get documents by category name. For the complete NLTK corpus operations, check out this wonderful article: Accessing Text Corpora and Lexical Resources To save time and computation resources, we’d better exclude stop words like, “am”, “I”, “should”. NLTK provides a good English stop words list. from nltk.corpus import stopwordsignored_words = list(stopwords.words('english')) And you can also extend the list with your own stop words that are not included in NLTK stop words list. ignored_words.extend('''get see seeing seems back join excludes has have other that are likely like due since next 100 take based high day set ago still however long early much help sees would will say says said applying apply remark explain explaining'''.split()) Before using TF-IDF to extract the keywords, I will build my own vocabulary list include both single-word(e.g. “Python”) and two words (e.g. “white house”). Here I will use CountVectorizer from scikit-learn to perform the single word extraction job. from sklearn.feature_extraction.text import CountVectorizerimport pandas as pdcount_vec = CountVectorizer( ngram_range = (1,1) #1 ,stop_words = ignored_words)text_set = [reuters.raw(fileid).lower() for fileid in reuters.fileids()] #2tf_result = count_vec.fit_transform(text_set)tf_result_df = pd.DataFrame(tf_result.toarray() ,columns=count_vec.get_feature_names()) #3the_sum_s = tf_result_df.sum(axis=0) #4the_sum_df = pd.DataFrame({ #5 'keyword':the_sum_s.index ,'tf_sum':the_sum_s.values})the_sum_df = the_sum_df[ the_sum_df['tf_sum']>2 #6].sort_values(by=['tf_sum'],ascending=False) Code #1, specified that CountVectorizer will only count single word. aka, 1gram word. You may ask, why not use ngram_range = (1,2) then get both single and bigram words at the same time? That is because capture bigram here will get phrases like "they are", "I will", and "will be". Those are conjunction phrases and usually not keywords or key phrases to a document. Another reason is for saving memory resources, capture bigram phrases in this stage will use a lot of memory due to too many combinations. Code #2, using Python comprehension to take all Reuters article in one line code. Code #3, transform the count vector result to a readable Pandas Dataframe. Code #4, produce a Series list include keywords and its total appearance # in the corpus. Code #5, turn Series to Dataframe for easier to read and data manipulation. Code #6, take words that only appear more than 2 times. If you peek at the top 10 results set by the_sum_df[:10], you will see those most frequently used words: The most frequent but meaningless, we can easily proportionally exclude those by Python slicing: start_index = int(len(the_sum_df)*0.01) # exclude the top 1%my_word_df = the_sum_df.iloc[start_index:]my_word_df = my_word_df[my_word_df['keyword'].str.len()>2] And also remove words with less than 2 characters like “vs”, “lt” etc. Note that I am using .iloc instead of .loc. Because the original dataset is reordered by TF(term frequency) value. iloc will slice on the index of the index(or the sequence of index label). but loc will slice on the index label. To build a bigram phrase list, we not only need to consider the frequency of appearance together but also its relationship with neighbor words. For example phrase they are, appears together many times, but they are can only follow with limited words like they are brothers, they are nice people, those words have high internal stickiness but low external connection flexibility. The external connection flexibility usually can be measured with information entropy. The higher the entropy value indicates the higher possibility to use together with other words. And phrases that with high internal stickiness(count frequency) and high external entropy to our brain, we call these “Common Phrases”, and these are what we want to add into our extraction vocabulary. NLTK provides a similar solution to solve the bigram phrase extraction problem. from nltk.collocations import BigramAssocMeasuresfrom nltk.collocations import BigramCollocationFinderfrom nltk.tokenize import word_tokenizetext_set_words = [word_tokenize(reuters.raw(fileid).lower()) for fileid in reuters.fileids()] #1bigram_measures = BigramAssocMeasures()finder = BigramCollocationFinder.from_documents(text_set_words) #2finder.apply_freq_filter(3) #3finder.apply_word_filter(lambda w: len(w) < 3 or len(w) > 15 or w.lower() in ignored_words) #4phrase_result = finder.nbest(bigram_measures.pmi, 20000) #5colloc_strings = [w1+' '+w2 for w1,w2 in phrase_result] #6 Code #1, In this Python comprehension expression, I use the word_tokenize to tokenize a document to a word list. The output will be like this: [ ['word1','word2',...,'wordn'], ['word1','word2',...,'wordn'], ... ['word1','word2',...,'wordn']] Code #2, start the bigram finder object from the tokenized document list. there is another function from_words() can process tokenized words list. Code #3, remove candidates which have a frequency less than 3. Code #4, remove candidates which word length less than 3 or longer than 15. and those in ignored_words list. Code #5, use pmi function from BigramAssocMeasures to measure the likelihood of a 2 words phrase. You can find out how it works in section 5.4 of Foundations of Statical Natural Language Processing. And this link list all other measure functions and source. Code #6, transform the result to a more readable format. By replacing BigramAssocMeasures, BigramCollocationFinder with TrigramAssocMeasures and TrigramCollocationFinder, you will get the 3-words phrase extractor. In the Reuters keywords extraction sample, I will skip the 3-words phrase. I post the sample code here in case you need it. from nltk.collocations import TrigramAssocMeasuresfrom nltk.collocations import TrigramCollocationFinderfrom nltk.tokenize import word_tokenizetext_set_words = [word_tokenize(reuters.raw(fileid).lower()) for fileid in reuters.fileids()]trigram_measures = TrigramAssocMeasures()finder = TrigramCollocationFinder.from_documents(text_set_words)finder.apply_freq_filter(3)finder.apply_word_filter(lambda w: len(w) < 3 or len(w) > 15 or w.lower() in ignored_words)tri_phrase_result = finder.nbest(bigram_measures.pmi, 1000)tri_colloc_strings = [w1+' '+w2+' '+w3 for w1,w2,w3 in tri_phrase_result] tri_colloc_strings[:10] Now, let’s combine the single words and 2-words phrases together to build the Reuters customized vocabulary list. my_vocabulary = []my_vocabulary.extend(my_word_df['keyword'].tolist()) my_vocabulary.extend(colloc_strings) Let’s start the engine. Note that please find a machine with at least 16g RAM to run the code. The TF-IDF calculation will take a while and may consume a large chunk of your memory. from sklearn.feature_extraction.text import TfidfVectorizervec = TfidfVectorizer( analyzer ='word' ,ngram_range =(1, 2) ,vocabulary =my_vocabulary)text_set = [reuters.raw(fileid) for fileid in reuters.fileids()]tf_idf = vec.fit_transform(text_set)result_tfidf = pd.DataFrame(tf_idf.toarray() , columns=vec.get_feature_names()) #1 After transforming the result set to Dateframe in code #1, The result_tfidf hold all keywords' TF-IDF values: Let’s check out one of the articles and compare with its keywords extracted by the above extractor to verify the effectiveness. Output one of the original document by specifying the fileid index. file_index= 202 # change number to check different articlesfileid = reuters.fileids()[file_index]print(fileid,"\n" ,reuters.raw(fileid),"\n" ,reuters.categories(fileid),"\n") Returns fileid, raw content, and its category. (hmm, many years ago, U.S. fought a tariffs war with Japan) test/15223 WHITE HOUSE SAYS JAPANESE TARRIFFS LIKELY The White House said high U.S. Tariffs on Japanese electronic goods would likely be imposed as scheduled on April 17, despite an all-out effort by Japan to avoid them. Presidential spokesman Marlin Fitzwater made the remark one day before U.S. And Japanese officials are to meet under the emergency provisions of a July 1986 semiconductor pact to discuss trade and the punitive tariffs. Fitzwater said: "I would say Japan is applying the full-court press...They certainly are putting both feet forward in terms of explaining their position." But he added that "all indications are they (the tariffs) will take effect." ['trade'] Print out the top 10 keywords from our just brewed result_tfidf dataframe object. test_tfidf_row = result_tfidf.loc[file_index]keywords_df = pd.DataFrame({ 'keyword':test_tfidf_row.index, 'tf-idf':test_tfidf_row.values})keywords_df = keywords_df[ keywords_df['tf-idf'] >0].sort_values(by=['tf-idf'],ascending=False)keywords_df[:10] Top 10 keywords: Looks like white and house here is duplicated with white house. We need to remove those single words that already appeared in a 2-words phrase. bigram_words = [item.split() for item in keywords_df['keyword'].tolist() if len(item.split())==2]bigram_words_set = set(subitem for item in bigram_words for subitem in item) keywords_df_new = keywords_df[~keywords_df['keyword'].isin(bigram_words_set)] The above code first builds a word set that contains words from a 2-words phrase. Then, filtered out single words that already being used in 2-words phrase by ~xxxx.isin(xxxx). The larger the text corpus you have, the better TF-IDF will perform on extracting the keywords. The Reuters corpus contains 10788 articles, and the result shows it works. I believe this solution will work better for larger text databases. The above code runs less than 2 minutes in my Macbook Air M1, which means the daily refresh result set is workable. If you have data in hundreds of GB or even TB size. you may need to consider rewrite the logic in C/C++ or Go, and may also leverage the power of GPU to improve the performance. The solution described in this article is far from perfect, For example, I didn’t filter out the verb and adjective words. The backbone of the solution can be expanded to other languages. Let print out again the final result. keywords_df_new[:10] tariffs get the highest TF-IDF value and the rest keywords look good to represent this Reuters article. Goal reached!
[ { "code": null, "e": 452, "s": 172, "text": "Imagine you have millions(maybe billions) of text documents in hand. No matter it is customer support tickets, social media data, or community forum posts. There were no tags when the data was generated. You are scratching your head hard to giving tags to those random documents." }, { "code": null, "e": 610, "s": 452, "text": "Manually tagging is unpractical; Giving an existing tagging list will be outdated soon. Hiring a vendor company to do the tagging work is too much expensive." }, { "code": null, "e": 777, "s": 610, "text": "You may say, why not using Machine Learning? like, Neral Network deep learning. But, NN needs some training data first. The training data that right fit your dataset." }, { "code": null, "e": 842, "s": 777, "text": "So, is there a solution that we can give documents tagging meet:" }, { "code": null, "e": 975, "s": 842, "text": "Need no pre-request training data.Minimum manual interference and can automatically run.Capture new words and phrases automatically." }, { "code": null, "e": 1010, "s": 975, "text": "Need no pre-request training data." }, { "code": null, "e": 1065, "s": 1010, "text": "Minimum manual interference and can automatically run." }, { "code": null, "e": 1110, "s": 1065, "text": "Capture new words and phrases automatically." }, { "code": null, "e": 1198, "s": 1110, "text": "This article is logging how I extracted keywords, how it works, walkarounds, in Python." }, { "code": null, "e": 1407, "s": 1198, "text": "Note that the code in this article was run and test in Jupyter Notebook. If you run a code block but welcomed with a missing import package error, this package must have been imported already somewhere ahead." }, { "code": null, "e": 1523, "s": 1407, "text": "TF-IDF is a widely used algorithm that evaluates how relevant a word is to a document in a collection of documents." }, { "code": null, "e": 1759, "s": 1523, "text": "In my previous article: Measure Text Weight using TF-IDF in Python and scikit-learn, I used a simple sample to show how to calculate the TF-IDF value for all words in a document. In both pure Python code and using scikit-learn package." }, { "code": null, "e": 1977, "s": 1759, "text": "Based on TF-IDF, those unique and important words should have high TF-IDF values in a certain document. So, in theory, we should be able to leverage the text weight # to extract the most important words of a document." }, { "code": null, "e": 2173, "s": 1977, "text": "For example, a document talks about scikit-learn should include much high density of keywords scikit-learn, while another document talks about “pandas” should have a high TF-IDF value for pandas." }, { "code": null, "e": 2418, "s": 2173, "text": "Since I can’t use my daily work database here and also ensure you can perform the keywords extraction sample code in your local machine with minimum efforts. I found the Reuters document corpus from NLTK is a good target for keyword extraction." }, { "code": null, "e": 2630, "s": 2418, "text": "In case you are not familiar with NLTK corpus, this article may be helpful to get NLTK started in less than one hour: Book Writing Pattern Analysis — Get start with NLTK and Python text analysis with a use case." }, { "code": null, "e": 2679, "s": 2630, "text": "To download the Reuters corpus. run Python code:" }, { "code": null, "e": 2715, "s": 2679, "text": "import nltknltk.download(\"reuters\")" }, { "code": null, "e": 2774, "s": 2715, "text": "List all documents ids from the corpus we just downloaded." }, { "code": null, "e": 2823, "s": 2774, "text": "from nltk.corpus import reutersreuters.fileids()" }, { "code": null, "e": 2875, "s": 2823, "text": "Check out one document's content, and its category." }, { "code": null, "e": 2994, "s": 2875, "text": "fileid = reuters.fileids()[202]print(fileid,\"\\n\" ,reuters.raw(fileid),\"\\n\" ,reuters.categories(fileid),\"\\n\")" }, { "code": null, "e": 3213, "s": 2994, "text": "Reuters corpus is organized by overlapping categories. We can also get documents by category name. For the complete NLTK corpus operations, check out this wonderful article: Accessing Text Corpora and Lexical Resources" }, { "code": null, "e": 3357, "s": 3213, "text": "To save time and computation resources, we’d better exclude stop words like, “am”, “I”, “should”. NLTK provides a good English stop words list." }, { "code": null, "e": 3439, "s": 3357, "text": "from nltk.corpus import stopwordsignored_words = list(stopwords.words('english'))" }, { "code": null, "e": 3544, "s": 3439, "text": "And you can also extend the list with your own stop words that are not included in NLTK stop words list." }, { "code": null, "e": 3809, "s": 3544, "text": "ignored_words.extend('''get see seeing seems back join excludes has have other that are likely like due since next 100 take based high day set ago still however long early much help sees would will say says said applying apply remark explain explaining'''.split())" }, { "code": null, "e": 3966, "s": 3809, "text": "Before using TF-IDF to extract the keywords, I will build my own vocabulary list include both single-word(e.g. “Python”) and two words (e.g. “white house”)." }, { "code": null, "e": 4059, "s": 3966, "text": "Here I will use CountVectorizer from scikit-learn to perform the single word extraction job." }, { "code": null, "e": 4701, "s": 4059, "text": "from sklearn.feature_extraction.text import CountVectorizerimport pandas as pdcount_vec = CountVectorizer( ngram_range = (1,1) #1 ,stop_words = ignored_words)text_set = [reuters.raw(fileid).lower() for fileid in reuters.fileids()] #2tf_result = count_vec.fit_transform(text_set)tf_result_df = pd.DataFrame(tf_result.toarray() ,columns=count_vec.get_feature_names()) #3the_sum_s = tf_result_df.sum(axis=0) #4the_sum_df = pd.DataFrame({ #5 'keyword':the_sum_s.index ,'tf_sum':the_sum_s.values})the_sum_df = the_sum_df[ the_sum_df['tf_sum']>2 #6].sort_values(by=['tf_sum'],ascending=False)" }, { "code": null, "e": 5068, "s": 4701, "text": "Code #1, specified that CountVectorizer will only count single word. aka, 1gram word. You may ask, why not use ngram_range = (1,2) then get both single and bigram words at the same time? That is because capture bigram here will get phrases like \"they are\", \"I will\", and \"will be\". Those are conjunction phrases and usually not keywords or key phrases to a document." }, { "code": null, "e": 5207, "s": 5068, "text": "Another reason is for saving memory resources, capture bigram phrases in this stage will use a lot of memory due to too many combinations." }, { "code": null, "e": 5289, "s": 5207, "text": "Code #2, using Python comprehension to take all Reuters article in one line code." }, { "code": null, "e": 5364, "s": 5289, "text": "Code #3, transform the count vector result to a readable Pandas Dataframe." }, { "code": null, "e": 5454, "s": 5364, "text": "Code #4, produce a Series list include keywords and its total appearance # in the corpus." }, { "code": null, "e": 5530, "s": 5454, "text": "Code #5, turn Series to Dataframe for easier to read and data manipulation." }, { "code": null, "e": 5586, "s": 5530, "text": "Code #6, take words that only appear more than 2 times." }, { "code": null, "e": 5691, "s": 5586, "text": "If you peek at the top 10 results set by the_sum_df[:10], you will see those most frequently used words:" }, { "code": null, "e": 5788, "s": 5691, "text": "The most frequent but meaningless, we can easily proportionally exclude those by Python slicing:" }, { "code": null, "e": 5963, "s": 5788, "text": "start_index = int(len(the_sum_df)*0.01) # exclude the top 1%my_word_df = the_sum_df.iloc[start_index:]my_word_df = my_word_df[my_word_df['keyword'].str.len()>2]" }, { "code": null, "e": 6034, "s": 5963, "text": "And also remove words with less than 2 characters like “vs”, “lt” etc." }, { "code": null, "e": 6263, "s": 6034, "text": "Note that I am using .iloc instead of .loc. Because the original dataset is reordered by TF(term frequency) value. iloc will slice on the index of the index(or the sequence of index label). but loc will slice on the index label." }, { "code": null, "e": 6407, "s": 6263, "text": "To build a bigram phrase list, we not only need to consider the frequency of appearance together but also its relationship with neighbor words." }, { "code": null, "e": 6642, "s": 6407, "text": "For example phrase they are, appears together many times, but they are can only follow with limited words like they are brothers, they are nice people, those words have high internal stickiness but low external connection flexibility." }, { "code": null, "e": 6824, "s": 6642, "text": "The external connection flexibility usually can be measured with information entropy. The higher the entropy value indicates the higher possibility to use together with other words." }, { "code": null, "e": 7026, "s": 6824, "text": "And phrases that with high internal stickiness(count frequency) and high external entropy to our brain, we call these “Common Phrases”, and these are what we want to add into our extraction vocabulary." }, { "code": null, "e": 7106, "s": 7026, "text": "NLTK provides a similar solution to solve the bigram phrase extraction problem." }, { "code": null, "e": 7785, "s": 7106, "text": "from nltk.collocations import BigramAssocMeasuresfrom nltk.collocations import BigramCollocationFinderfrom nltk.tokenize import word_tokenizetext_set_words = [word_tokenize(reuters.raw(fileid).lower()) for fileid in reuters.fileids()] #1bigram_measures = BigramAssocMeasures()finder = BigramCollocationFinder.from_documents(text_set_words) #2finder.apply_freq_filter(3) #3finder.apply_word_filter(lambda w: len(w) < 3 or len(w) > 15 or w.lower() in ignored_words) #4phrase_result = finder.nbest(bigram_measures.pmi, 20000) #5colloc_strings = [w1+' '+w2 for w1,w2 in phrase_result] #6" }, { "code": null, "e": 7928, "s": 7785, "text": "Code #1, In this Python comprehension expression, I use the word_tokenize to tokenize a document to a word list. The output will be like this:" }, { "code": null, "e": 8040, "s": 7928, "text": "[ ['word1','word2',...,'wordn'], ['word1','word2',...,'wordn'], ... ['word1','word2',...,'wordn']]" }, { "code": null, "e": 8187, "s": 8040, "text": "Code #2, start the bigram finder object from the tokenized document list. there is another function from_words() can process tokenized words list." }, { "code": null, "e": 8250, "s": 8187, "text": "Code #3, remove candidates which have a frequency less than 3." }, { "code": null, "e": 8359, "s": 8250, "text": "Code #4, remove candidates which word length less than 3 or longer than 15. and those in ignored_words list." }, { "code": null, "e": 8617, "s": 8359, "text": "Code #5, use pmi function from BigramAssocMeasures to measure the likelihood of a 2 words phrase. You can find out how it works in section 5.4 of Foundations of Statical Natural Language Processing. And this link list all other measure functions and source." }, { "code": null, "e": 8674, "s": 8617, "text": "Code #6, transform the result to a more readable format." }, { "code": null, "e": 8955, "s": 8674, "text": "By replacing BigramAssocMeasures, BigramCollocationFinder with TrigramAssocMeasures and TrigramCollocationFinder, you will get the 3-words phrase extractor. In the Reuters keywords extraction sample, I will skip the 3-words phrase. I post the sample code here in case you need it." }, { "code": null, "e": 9666, "s": 8955, "text": "from nltk.collocations import TrigramAssocMeasuresfrom nltk.collocations import TrigramCollocationFinderfrom nltk.tokenize import word_tokenizetext_set_words = [word_tokenize(reuters.raw(fileid).lower()) for fileid in reuters.fileids()]trigram_measures = TrigramAssocMeasures()finder = TrigramCollocationFinder.from_documents(text_set_words)finder.apply_freq_filter(3)finder.apply_word_filter(lambda w: len(w) < 3 or len(w) > 15 or w.lower() in ignored_words)tri_phrase_result = finder.nbest(bigram_measures.pmi, 1000)tri_colloc_strings = [w1+' '+w2+' '+w3 for w1,w2,w3 in tri_phrase_result] tri_colloc_strings[:10]" }, { "code": null, "e": 9780, "s": 9666, "text": "Now, let’s combine the single words and 2-words phrases together to build the Reuters customized vocabulary list." }, { "code": null, "e": 9888, "s": 9780, "text": "my_vocabulary = []my_vocabulary.extend(my_word_df['keyword'].tolist()) my_vocabulary.extend(colloc_strings)" }, { "code": null, "e": 10070, "s": 9888, "text": "Let’s start the engine. Note that please find a machine with at least 16g RAM to run the code. The TF-IDF calculation will take a while and may consume a large chunk of your memory." }, { "code": null, "e": 10508, "s": 10070, "text": "from sklearn.feature_extraction.text import TfidfVectorizervec = TfidfVectorizer( analyzer ='word' ,ngram_range =(1, 2) ,vocabulary =my_vocabulary)text_set = [reuters.raw(fileid) for fileid in reuters.fileids()]tf_idf = vec.fit_transform(text_set)result_tfidf = pd.DataFrame(tf_idf.toarray() , columns=vec.get_feature_names()) #1" }, { "code": null, "e": 10618, "s": 10508, "text": "After transforming the result set to Dateframe in code #1, The result_tfidf hold all keywords' TF-IDF values:" }, { "code": null, "e": 10746, "s": 10618, "text": "Let’s check out one of the articles and compare with its keywords extracted by the above extractor to verify the effectiveness." }, { "code": null, "e": 10814, "s": 10746, "text": "Output one of the original document by specifying the fileid index." }, { "code": null, "e": 11003, "s": 10814, "text": "file_index= 202 # change number to check different articlesfileid = reuters.fileids()[file_index]print(fileid,\"\\n\" ,reuters.raw(fileid),\"\\n\" ,reuters.categories(fileid),\"\\n\")" }, { "code": null, "e": 11110, "s": 11003, "text": "Returns fileid, raw content, and its category. (hmm, many years ago, U.S. fought a tariffs war with Japan)" }, { "code": null, "e": 11813, "s": 11110, "text": "test/15223 WHITE HOUSE SAYS JAPANESE TARRIFFS LIKELY The White House said high U.S. Tariffs on Japanese electronic goods would likely be imposed as scheduled on April 17, despite an all-out effort by Japan to avoid them. Presidential spokesman Marlin Fitzwater made the remark one day before U.S. And Japanese officials are to meet under the emergency provisions of a July 1986 semiconductor pact to discuss trade and the punitive tariffs. Fitzwater said: \"I would say Japan is applying the full-court press...They certainly are putting both feet forward in terms of explaining their position.\" But he added that \"all indications are they (the tariffs) will take effect.\" ['trade']" }, { "code": null, "e": 11895, "s": 11813, "text": "Print out the top 10 keywords from our just brewed result_tfidf dataframe object." }, { "code": null, "e": 12154, "s": 11895, "text": "test_tfidf_row = result_tfidf.loc[file_index]keywords_df = pd.DataFrame({ 'keyword':test_tfidf_row.index, 'tf-idf':test_tfidf_row.values})keywords_df = keywords_df[ keywords_df['tf-idf'] >0].sort_values(by=['tf-idf'],ascending=False)keywords_df[:10]" }, { "code": null, "e": 12171, "s": 12154, "text": "Top 10 keywords:" }, { "code": null, "e": 12315, "s": 12171, "text": "Looks like white and house here is duplicated with white house. We need to remove those single words that already appeared in a 2-words phrase." }, { "code": null, "e": 12655, "s": 12315, "text": "bigram_words = [item.split() for item in keywords_df['keyword'].tolist() if len(item.split())==2]bigram_words_set = set(subitem for item in bigram_words for subitem in item) keywords_df_new = keywords_df[~keywords_df['keyword'].isin(bigram_words_set)]" }, { "code": null, "e": 12832, "s": 12655, "text": "The above code first builds a word set that contains words from a 2-words phrase. Then, filtered out single words that already being used in 2-words phrase by ~xxxx.isin(xxxx)." }, { "code": null, "e": 13071, "s": 12832, "text": "The larger the text corpus you have, the better TF-IDF will perform on extracting the keywords. The Reuters corpus contains 10788 articles, and the result shows it works. I believe this solution will work better for larger text databases." }, { "code": null, "e": 13187, "s": 13071, "text": "The above code runs less than 2 minutes in my Macbook Air M1, which means the daily refresh result set is workable." }, { "code": null, "e": 13365, "s": 13187, "text": "If you have data in hundreds of GB or even TB size. you may need to consider rewrite the logic in C/C++ or Go, and may also leverage the power of GPU to improve the performance." }, { "code": null, "e": 13553, "s": 13365, "text": "The solution described in this article is far from perfect, For example, I didn’t filter out the verb and adjective words. The backbone of the solution can be expanded to other languages." }, { "code": null, "e": 13591, "s": 13553, "text": "Let print out again the final result." }, { "code": null, "e": 13612, "s": 13591, "text": "keywords_df_new[:10]" } ]
Collapsible Pane in Tkinter Python
Tkinter is the GUI building library of python. In this article we will see how we can create a collapsible pane. They are usefult when we have some large amount of data to be displayed over a GUI canvas but we do not want to be displayed always. It is made collapsible so that it can be displayed as and when needed. The below program creates the collapsible pane where we see the result both after expanding and contracting the arrow. The code comments indicate the approach we take at each step. from tkinter import * import tkinter as tk from tkinter import ttk from tkinter.ttk import * class cpane(ttk.Frame): def __init__(self, MainWindow, expanded_text, collapsed_text): ttk.Frame.__init__(self, MainWindow) # The class variable self.MainWindow = MainWindow self._expanded_text = expanded_text self._collapsed_text = collapsed_text # Weight=1 to grow it's size as needed self.columnconfigure(1, weight=1) self._variable = tk.IntVar() # Creating Checkbutton self._button = ttk.Checkbutton(self, variable=self._variable, command=self._activate, style="TButton") self._button.grid(row=0, column=0) # Create a Horizontal line self._separator = ttk.Separator(self, orient="horizontal") self._separator.grid(row=0, column=1, sticky="we") self.frame = ttk.Frame(self) # Activate the class self._activate() def _activate(self): if not self._variable.get(): # Remove this widget when button pressed. self.frame.grid_forget() # Show collapsed text self._button.configure(text=self._collapsed_text) elif self._variable.get(): # Increase the frame area as needed self.frame.grid(row=1, column=0, columnspan=2) self._button.configure(text=self._expanded_text) def toggle(self): self._variable.set(not self._variable.get()) self._activate() # Creating root window or MainWindow root = Tk() root.geometry('300x300') # Creating Object of Collapsible Pane Container cpane_obj = cpane(root, 'Close Me', 'Open Me!') cpane_obj.grid(row=0, column=0) # Buttons to # appear in collapsible pane b = Button(cpane_obj.frame, text=" Frame Expanded").grid( row=1, column=2, pady=20) b = Checkbutton(cpane_obj.frame, text="Hi There ! How are you doing?").grid( row=3, column=4, pady=20) mainloop() Running the above code gives us the following result −
[ { "code": null, "e": 1379, "s": 1062, "text": "Tkinter is the GUI building library of python. In this article we will see how we can create a collapsible pane. They are usefult when we have some large amount of data to be displayed over a GUI canvas but we do not want to be displayed always. It is made collapsible so that it can be displayed as and when needed." }, { "code": null, "e": 1560, "s": 1379, "text": "The below program creates the collapsible pane where we see the result both after expanding and contracting the arrow. The code comments indicate the approach we take at each step." }, { "code": null, "e": 3448, "s": 1560, "text": "from tkinter import *\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.ttk import *\nclass cpane(ttk.Frame):\n def __init__(self, MainWindow, expanded_text, collapsed_text):\n ttk.Frame.__init__(self, MainWindow)\n # The class variable\n self.MainWindow = MainWindow\n self._expanded_text = expanded_text\n self._collapsed_text = collapsed_text\n # Weight=1 to grow it's size as needed\n self.columnconfigure(1, weight=1)\n self._variable = tk.IntVar()\n # Creating Checkbutton\n self._button = ttk.Checkbutton(self, variable=self._variable,\n command=self._activate, style=\"TButton\")\n self._button.grid(row=0, column=0)\n # Create a Horizontal line\n self._separator = ttk.Separator(self, orient=\"horizontal\")\n self._separator.grid(row=0, column=1, sticky=\"we\")\n self.frame = ttk.Frame(self)\n # Activate the class\n self._activate()\n def _activate(self):\n if not self._variable.get():\n # Remove this widget when button pressed.\n self.frame.grid_forget()\n # Show collapsed text\n self._button.configure(text=self._collapsed_text)\n elif self._variable.get():\n # Increase the frame area as needed\n self.frame.grid(row=1, column=0, columnspan=2)\n self._button.configure(text=self._expanded_text)\n def toggle(self):\n self._variable.set(not self._variable.get())\n self._activate()\n# Creating root window or MainWindow\nroot = Tk()\nroot.geometry('300x300')\n# Creating Object of Collapsible Pane Container\ncpane_obj = cpane(root, 'Close Me', 'Open Me!')\ncpane_obj.grid(row=0, column=0)\n# Buttons to # appear in collapsible pane\nb = Button(cpane_obj.frame, text=\" Frame Expanded\").grid(\n row=1, column=2, pady=20)\nb = Checkbutton(cpane_obj.frame, text=\"Hi There ! How are you doing?\").grid(\n row=3, column=4, pady=20)\nmainloop()" }, { "code": null, "e": 3503, "s": 3448, "text": "Running the above code gives us the following result −" } ]
Node.js Yargs Module - GeeksforGeeks
08 Oct, 2021 Yargs module is used for creating your own command-line commands in node.js and helps in generating an elegant user interface. This module makes command-line arguments flexible and easy to use. Installation of yargs module: You can visit the link Install yargs module. You can install this package by using this command.npm install yargsAfter installing yargs you can check your yargs version in command prompt using the command.npm version yargsAfter 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 Install yargs module. You can install this package by using this command.npm install yargs npm install yargs After installing yargs you can check your yargs version in command prompt using the command.npm version yargs npm version yargs 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 yargs = require('yargs') // Customize yargs versionyargs.version('1.1.0') // Create add commandyargs.command({ command: 'add', describe: 'Adds two number', builder: { firstNumber: { describe: 'First Number', demandOption: true, // Required type: 'number' }, secondNumber: { describe: 'Second Number', demandOption: true, type: 'number' } }, // Function for your command handler(argv) { console.log("Result:", (argv.firstNumber+argv.secondNumber)) }}) yargs.parse() // To set above changes Steps to run the program: The project structure will look like this:Make sure you have install express and yargs module using following commands:npm install express npm install yargsRun index.js file using below command:node index.jsAfter running this above command, now yargs command is set, you can use it as shown below:node index.js add --firstNumber=4 --secondNumber=10 The project structure will look like this: Make sure you have install express and yargs module using following commands:npm install express npm install yargs npm install express npm install yargs Run index.js file using below command:node index.jsAfter running this above command, now yargs command is set, you can use it as shown below:node index.js add --firstNumber=4 --secondNumber=10 node index.js After running this above command, now yargs command is set, you can use it as shown below: node index.js add --firstNumber=4 --secondNumber=10 So this is how you can use yargs module for making your own command-line arguments command thereby making it more interactive. Node.js-Misc Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Top 10 Front End Developer Skills That You Need in 2022 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24325, "s": 24297, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24519, "s": 24325, "text": "Yargs module is used for creating your own command-line commands in node.js and helps in generating an elegant user interface. This module makes command-line arguments flexible and easy to use." }, { "code": null, "e": 24549, "s": 24519, "text": "Installation of yargs module:" }, { "code": null, "e": 24918, "s": 24549, "text": "You can visit the link Install yargs module. You can install this package by using this command.npm install yargsAfter installing yargs you can check your yargs version in command prompt using the command.npm version yargsAfter 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": 25032, "s": 24918, "text": "You can visit the link Install yargs module. You can install this package by using this command.npm install yargs" }, { "code": null, "e": 25050, "s": 25032, "text": "npm install yargs" }, { "code": null, "e": 25160, "s": 25050, "text": "After installing yargs you can check your yargs version in command prompt using the command.npm version yargs" }, { "code": null, "e": 25178, "s": 25160, "text": "npm version yargs" }, { "code": null, "e": 25325, "s": 25178, "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": 25339, "s": 25325, "text": "node index.js" }, { "code": null, "e": 25358, "s": 25339, "text": "Filename: index.js" }, { "code": "const yargs = require('yargs') // Customize yargs versionyargs.version('1.1.0') // Create add commandyargs.command({ command: 'add', describe: 'Adds two number', builder: { firstNumber: { describe: 'First Number', demandOption: true, // Required type: 'number' }, secondNumber: { describe: 'Second Number', demandOption: true, type: 'number' } }, // Function for your command handler(argv) { console.log(\"Result:\", (argv.firstNumber+argv.secondNumber)) }}) yargs.parse() // To set above changes", "e": 26003, "s": 25358, "text": null }, { "code": null, "e": 26029, "s": 26003, "text": "Steps to run the program:" }, { "code": null, "e": 26378, "s": 26029, "text": "The project structure will look like this:Make sure you have install express and yargs module using following commands:npm install express\nnpm install yargsRun index.js file using below command:node index.jsAfter running this above command, now yargs command is set, you can use it as shown below:node index.js add --firstNumber=4 --secondNumber=10" }, { "code": null, "e": 26421, "s": 26378, "text": "The project structure will look like this:" }, { "code": null, "e": 26536, "s": 26421, "text": "Make sure you have install express and yargs module using following commands:npm install express\nnpm install yargs" }, { "code": null, "e": 26574, "s": 26536, "text": "npm install express\nnpm install yargs" }, { "code": null, "e": 26767, "s": 26574, "text": "Run index.js file using below command:node index.jsAfter running this above command, now yargs command is set, you can use it as shown below:node index.js add --firstNumber=4 --secondNumber=10" }, { "code": null, "e": 26781, "s": 26767, "text": "node index.js" }, { "code": null, "e": 26872, "s": 26781, "text": "After running this above command, now yargs command is set, you can use it as shown below:" }, { "code": null, "e": 26924, "s": 26872, "text": "node index.js add --firstNumber=4 --secondNumber=10" }, { "code": null, "e": 27051, "s": 26924, "text": "So this is how you can use yargs module for making your own command-line arguments command thereby making it more interactive." }, { "code": null, "e": 27064, "s": 27051, "text": "Node.js-Misc" }, { "code": null, "e": 27072, "s": 27064, "text": "Node.js" }, { "code": null, "e": 27089, "s": 27072, "text": "Web Technologies" }, { "code": null, "e": 27116, "s": 27089, "text": "Web technologies Questions" }, { "code": null, "e": 27132, "s": 27116, "text": "Write From Home" }, { "code": null, "e": 27230, "s": 27132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27239, "s": 27230, "text": "Comments" }, { "code": null, "e": 27252, "s": 27239, "text": "Old Comments" }, { "code": null, "e": 27281, "s": 27252, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27311, "s": 27281, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27368, "s": 27311, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27422, "s": 27368, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27459, "s": 27422, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 27515, "s": 27459, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27577, "s": 27515, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27620, "s": 27577, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27670, "s": 27620, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Defining Dependencies in Makefile
It is very common that a final binary will be dependent on various source code and source header files. Dependencies are important because they let the make Known about the source for any target. Consider the following example − hello: main.o factorial.o hello.o $(CC) main.o factorial.o hello.o -o hello Here, we tell the make that hello is dependent on main.o, factorial.o, and hello.o files. Hence, whenever there is a change in any of these object files, make will take action. At the same time, we need to tell the make how to prepare .o files. Hence we need to define those dependencies also as follows − main.o: main.cpp functions.h $(CC) -c main.cpp factorial.o: factorial.cpp functions.h $(CC) -c factorial.cpp hello.o: hello.cpp functions.h $(CC) -c hello.cpp Print Add Notes Bookmark this page
[ { "code": null, "e": 2013, "s": 1784, "text": "It is very common that a final binary will be dependent on various source code and source header files. Dependencies are important because they let the make Known about the source for any target. Consider the following example −" }, { "code": null, "e": 2092, "s": 2013, "text": "hello: main.o factorial.o hello.o\n $(CC) main.o factorial.o hello.o -o hello" }, { "code": null, "e": 2269, "s": 2092, "text": "Here, we tell the make that hello is dependent on main.o, factorial.o, and hello.o files. Hence, whenever there is a change in any of these object files, make will take action." }, { "code": null, "e": 2398, "s": 2269, "text": "At the same time, we need to tell the make how to prepare .o files. Hence we need to define those dependencies also as follows −" }, { "code": null, "e": 2568, "s": 2398, "text": "main.o: main.cpp functions.h\n $(CC) -c main.cpp\n\nfactorial.o: factorial.cpp functions.h\n $(CC) -c factorial.cpp\n\nhello.o: hello.cpp functions.h\n $(CC) -c hello.cpp" }, { "code": null, "e": 2575, "s": 2568, "text": " Print" }, { "code": null, "e": 2586, "s": 2575, "text": " Add Notes" } ]
C++ ios Library - Function Scientific
It is used to sets the floatfield format flag for the str stream to scientific. When floatfield is set to scientific, floating-point values are written using scientific notation: the value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter e followed by an optional sign and three exponential digits. The floatfield format flag is both a selective and a toggle flag: it can take one or more of the following values as shown below − The floatfield format flag is both a selective and a toggle flag: it can take any of the following values, or none as shown below − write floating-point values in hexadecimal format. The value of this is the same as (fixed|scientific) Following is the declaration for std::scientific function. ios_base& scientific (ios_base& str); str − Stream object whose format flag is affected. It returns Argument str. Basic guarantee − if an exception is thrown, str is in a valid state. It modifies str. Concurrent access to the same stream object may cause data races. In below example explains about std::scientific function. #include <iostream> int main () { double a = 3.1415926534; double b = 2006.0; double c = 1.0e-10; std::cout.precision(5); std::cout << "default:\n"; std::cout << a << '\n' << b << '\n' << c << '\n'; std::cout << '\n'; std::cout << "fixed:\n" << std::fixed; std::cout << a << '\n' << b << '\n' << c << '\n'; std::cout << '\n'; std::cout << "scientific:\n" << std::scientific; std::cout << a << '\n' << b << '\n' << c << '\n'; return 0; } Let us compile and run the above program, this will produce the following result − default: 3.1416 2006 1e-010 fixed: 3.14159 2006.00000 0.00000 scientific: 3.14159e+000 2.00600e+003 1.00000e-010 Print Add Notes Bookmark this page
[ { "code": null, "e": 3098, "s": 2603, "text": "It is used to sets the floatfield format flag for the str stream to scientific. When floatfield is set to scientific, floating-point values are written using scientific notation: the value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter e followed by an optional sign and three exponential digits." }, { "code": null, "e": 3229, "s": 3098, "text": "The floatfield format flag is both a selective and a toggle flag: it can take one or more of the following values as shown below −" }, { "code": null, "e": 3361, "s": 3229, "text": "The floatfield format flag is both a selective and a toggle flag: it can take any of the following values, or none as shown below −" }, { "code": null, "e": 3412, "s": 3361, "text": "write floating-point values in hexadecimal format." }, { "code": null, "e": 3464, "s": 3412, "text": "The value of this is the same as (fixed|scientific)" }, { "code": null, "e": 3523, "s": 3464, "text": "Following is the declaration for std::scientific function." }, { "code": null, "e": 3561, "s": 3523, "text": "ios_base& scientific (ios_base& str);" }, { "code": null, "e": 3612, "s": 3561, "text": "str − Stream object whose format flag is affected." }, { "code": null, "e": 3637, "s": 3612, "text": "It returns Argument str." }, { "code": null, "e": 3707, "s": 3637, "text": "Basic guarantee − if an exception is thrown, str is in a valid state." }, { "code": null, "e": 3790, "s": 3707, "text": "It modifies str. Concurrent access to the same stream object may cause data races." }, { "code": null, "e": 3848, "s": 3790, "text": "In below example explains about std::scientific function." }, { "code": null, "e": 4331, "s": 3848, "text": "#include <iostream>\n\nint main () {\n double a = 3.1415926534;\n double b = 2006.0;\n double c = 1.0e-10;\n\n std::cout.precision(5);\n\n std::cout << \"default:\\n\";\n std::cout << a << '\\n' << b << '\\n' << c << '\\n';\n\n std::cout << '\\n';\n\n std::cout << \"fixed:\\n\" << std::fixed;\n std::cout << a << '\\n' << b << '\\n' << c << '\\n';\n\n std::cout << '\\n';\n\n std::cout << \"scientific:\\n\" << std::scientific;\n std::cout << a << '\\n' << b << '\\n' << c << '\\n';\n return 0;\n}" }, { "code": null, "e": 4414, "s": 4331, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4530, "s": 4414, "text": "default:\n3.1416\n2006\n1e-010\n\nfixed:\n3.14159\n2006.00000\n0.00000\n\nscientific:\n3.14159e+000\n2.00600e+003\n1.00000e-010\n" }, { "code": null, "e": 4537, "s": 4530, "text": " Print" }, { "code": null, "e": 4548, "s": 4537, "text": " Add Notes" } ]
C++ Program for Derivative of a Polynomial
Given a string containing the polynomial term, the task is to evaluate the derivative of that polynomial. What is a Polynomial? Polynomial comes from two words: - “Poly” which means “many” and “nomial” means “terms”, which comprises many terms. Polynomial expression is an expression containing variables, coefficients and exponents, which only involves operations such as, addition, multiplication and subtraction of variable(s). Example of polynomial x2+x+1 Derivative of the polynomial p(x) = mx^n will be − m * n * x^(n-1) Input: str = "2x^3 +1x^1 + 3x^2" val = 2 Output: 37 Explanation: 6x^2 + 1x^0 + 6x^1 Putting x = 2 6*4 + 1 + 6*2 = 24 + 1 + 12 = 37 Input: str = “1x^3” val = 2 Output: 12 Explanation: 1 * 3 *x^2 Putting x = 2 3 * 4 = 12 Approach we will be using to solve the above problem − Take the input as a string and a value of x Now traverse the string and check for the digits, and variables. Keep adding and traversing the string till we find ‘+’. Then m * n * x^(n-1). Return the result. Start Step 1-> In function long long term(string polyterm, long long val) Declare and initialize coeffStr = "” Declare i Loop For i = 0 and polyterm[i] != 'x' and i++ Call coeffStr.push_back(polyterm[i]) Set coeff = atol(coeffStr.c_str() Declare and initialize powStr = "" Loop For i = i + 2 and i != polyterm.size() and i++ powStr.push_back(polyterm[i]) Set power = atol(powStr.c_str()); Return coeff * power * pow(val, power - 1) Step 2-> In function long long value(string& str, int val) Set ans = 0 Call istringstream is(str) Declare string polyterm Loop While is >> polyterm If polyterm == "+” then, Continue Else Set ans = (ans + term(polyterm, val)) Return ans Step 3-> In function int main() Declare and initialize str = "2x^3 + 1x^1 + 3x^2" Declare and initialize val = 2 Print the value received by value(str, val) Stop Live Demo #include using namespace std; long long term(string polyterm, long long val) { //to find the coefficient string coeffStr = ""; int i; for (i = 0; polyterm[i] != 'x'; i++) coeffStr.push_back(polyterm[i]); long long coeff = atol(coeffStr.c_str()); // to get the power value string powStr = ""; for (i = i + 2; i != polyterm.size(); i++) powStr.push_back(polyterm[i]); long long power = atol(powStr.c_str()); // For ax^n, we return a(n-1)x^(n-1) return coeff * power * pow(val, power - 1); } long long value(string& str, int val) { long long ans = 0; // using istringstream to get input in tokens istringstream is(str); string polyterm; while (is >> polyterm) { // check if the token is equal to '+' then // continue with the string if (polyterm == "+") continue; // Otherwise find the derivative of that // particular term else ans = (ans + term(polyterm, val)); } return ans; } // main function int main() { string str = "2x^3 + 1x^1 + 3x^2"; int val = 2; cout << value(str, val); return 0; } 37
[ { "code": null, "e": 1168, "s": 1062, "text": "Given a string containing the polynomial term, the task is to evaluate the derivative of that polynomial." }, { "code": null, "e": 1190, "s": 1168, "text": "What is a Polynomial?" }, { "code": null, "e": 1493, "s": 1190, "text": "Polynomial comes from two words: - “Poly” which means “many” and “nomial” means “terms”, which comprises many terms. Polynomial expression is an expression containing variables, coefficients and exponents, which only involves operations such as, addition, multiplication and subtraction of variable(s)." }, { "code": null, "e": 1515, "s": 1493, "text": "Example of polynomial" }, { "code": null, "e": 1522, "s": 1515, "text": "x2+x+1" }, { "code": null, "e": 1574, "s": 1522, "text": "Derivative of the polynomial p(x) = mx^n will be −" }, { "code": null, "e": 1590, "s": 1574, "text": "m * n * x^(n-1)" }, { "code": null, "e": 1828, "s": 1590, "text": "Input: str = \"2x^3 +1x^1 + 3x^2\"\n val = 2\nOutput: 37\nExplanation: 6x^2 + 1x^0 + 6x^1\n Putting x = 2\n 6*4 + 1 + 6*2 = 24 + 1 + 12 = 37\n\nInput: str = “1x^3”\n val = 2\nOutput: 12\nExplanation: 1 * 3 *x^2\n Putting x = 2\n 3 * 4 = 12" }, { "code": null, "e": 1883, "s": 1828, "text": "Approach we will be using to solve the above problem −" }, { "code": null, "e": 1928, "s": 1883, "text": "Take the input as a string and a value of x" }, { "code": null, "e": 1993, "s": 1928, "text": "Now traverse the string and check for the digits, and variables." }, { "code": null, "e": 2049, "s": 1993, "text": "Keep adding and traversing the string till we find ‘+’." }, { "code": null, "e": 2071, "s": 2049, "text": "Then m * n * x^(n-1)." }, { "code": null, "e": 2090, "s": 2071, "text": "Return the result." }, { "code": null, "e": 3019, "s": 2090, "text": "Start\nStep 1-> In function long long term(string polyterm, long long val)\n Declare and initialize coeffStr = \"”\n Declare i\n Loop For i = 0 and polyterm[i] != 'x' and i++\n Call coeffStr.push_back(polyterm[i])\n Set coeff = atol(coeffStr.c_str()\n Declare and initialize powStr = \"\"\n Loop For i = i + 2 and i != polyterm.size() and i++ powStr.push_back(polyterm[i])\n Set power = atol(powStr.c_str());\n Return coeff * power * pow(val, power - 1)\nStep 2-> In function long long value(string& str, int val)\n Set ans = 0\n Call istringstream is(str)\n Declare string polyterm\n Loop While is >> polyterm\n If polyterm == \"+” then,\n Continue\n Else\n Set ans = (ans + term(polyterm, val))\n Return ans\nStep 3-> In function int main()\n Declare and initialize str = \"2x^3 + 1x^1 + 3x^2\"\n Declare and initialize val = 2\n Print the value received by value(str, val)\nStop" }, { "code": null, "e": 3030, "s": 3019, "text": " Live Demo" }, { "code": null, "e": 4160, "s": 3030, "text": "#include\nusing namespace std;\nlong long term(string polyterm, long long val) {\n //to find the coefficient\n string coeffStr = \"\";\n int i;\n for (i = 0; polyterm[i] != 'x'; i++)\n coeffStr.push_back(polyterm[i]);\n long long coeff = atol(coeffStr.c_str());\n // to get the power value\n string powStr = \"\";\n for (i = i + 2; i != polyterm.size(); i++)\n powStr.push_back(polyterm[i]);\n long long power = atol(powStr.c_str());\n // For ax^n, we return a(n-1)x^(n-1)\n return coeff * power * pow(val, power - 1);\n}\nlong long value(string& str, int val) {\n long long ans = 0;\n // using istringstream to get input in tokens\n istringstream is(str);\n string polyterm;\n while (is >> polyterm) {\n // check if the token is equal to '+' then\n // continue with the string\n if (polyterm == \"+\")\n continue;\n // Otherwise find the derivative of that\n // particular term\n else\n ans = (ans + term(polyterm, val));\n }\n return ans;\n}\n// main function\nint main() {\n string str = \"2x^3 + 1x^1 + 3x^2\";\n int val = 2;\n cout << value(str, val);\n return 0;\n}" }, { "code": null, "e": 4163, "s": 4160, "text": "37" } ]
The complete guide to start your Data Science and AI journey. | by Defend Intelligence | Towards Data Science
AI & Data Science are already skills that everyone should develop. With this guide we will go through a fast tutorial to present you how to start this technical journey (platforms to learn and apply skills, installation on your computer, useful software). At the end of this article you will be able to run your first Machine Learning program ! This guide is made for the non expert, so no worries ! :-) You are all set now to start your Data Science & Artificial Intelligence journey. Welcome aboard ! Faculty to learn by yourself Data Science / AI / Machine Learning / Deep Learning, all those fields are currently being defined. So the first thing to learn is the faculty to be always active in learning. Not sure about something ? Looking for the definition of a supervised algorithm ? A bug in your program ? Google it (or use any other search engine as Qwant or Ecosia) !Be careful about your sources, since AI is a new field you may see a lot of different and sometimes contradictory information. No one has the absolute truth here about definitions or knowledge. Search, interact and construct your own ideas ! It is why I recommend to learn from collaborative platform. On hot topic such as AI, collaborative platforms are a good source of information as you can go across the discussion thread, identify the person, and be able to challenge any answer or ask for more details.If you have an issue or an interrogation, you can be sure that someone before you already asked for it on some website. You may also already be able to help people so do not hesitate to contribute : Stack Overflow your new best friend for coding Quora sharing knowledge platform Wikipedia the universal encyclopedia Medium by the way When you will be a little more advanced in machine learning your key sources references will be documentations from libraries as for example this documentation from scikit-learn here or Tensorflow and Pytorch. Mathematical and statistical knowledge Machine Learning, Data Science and Artificial Intelligence requires strong mathematical and statistical knowledge. Here are the fields of knowledge you have to go through to start to understand Data Science(please do not hesitate to comment with some other field to complete the list) : Common Algebraic Theory (Linear model and matrix Algebra) Probability and Bayesian Theory Decision Theory Graph Theory Functional Analysis Game Theory Algorithm Logic Resources : Data Science Math Skills by Duke University Introduction to Mathematical Thinking by Stanford University Introduction to Linear Models and Matrix Algebra by Harvard University Mathematical lessons by Khan Academy Python for Data Science Python is a language used for many things (websites, games, applications, back-ends, database administration...). To use Python for Data Science you will need to: understand the common logic of the language learn how to use libraries What are the most common librairies in Data Science ?Pandas for data manipulation, seaborn/matplotlib for data visualization, numpy for mathematical manipulation, sklearn for algorithms use, keras, pytorch and tensorflow for more advanced use (like neural network for example). Resources : Introduction to Python by Microsoft Python Data Science Handbook by Jake Vanderplas Applied Data Science with Python by University of Michigan Data Science courses Once you have all those mathematical and code knowledge, it’s time to go into the Data Science field. You will need to learn new skills. A Data Scientist should be able to have a wide overview of all those skills listed below. But depending on what you want to specialize in only a few should be mastered. Database Management: To access different kind of data from different kind of sources (SQL, No SQL, structured, not structured, cluster, file...). Data Structure: To easily manipulate and prepare your data including features engineering. Data Visualizations: To understand your data by visualising it rather than reading it. Algorithms: There is nothing worse than trying all algorithms available and take the one that seems “better” regarding specific metrics, this is a waste of time. Each well trained Data Scientist should know how commons algorithms of Machine Learning work. From this knowledge the Data Scientist will be able to choose an algorithm from the data analysis. Evaluation: Combining data visualization and metrics knowledge a Data Scientist have to know if a model works well or not. Interpretability: We have to solve the myth of the “Black Box”. Machine Learning interpretability (with some libraries such as Shap or Lime ) help us understand how a Data Science solution works. Knowledge about web and infrastructure security : To not save, run or deploy a solution that could be dangerous for an organisation or your private laptop. Resources : Machine Learning by Stanford University Data Science: Machine Learning by Harvard University Learn by applying you Skills ! Perhaps my favorite method of learning, is to directly learn by applying immediate skills (and by applying skill I mean coding !). You will meet many people talking of Machine Learning, Data Science, Analytics or Artificial Intelligence without having ever touched a single line of code, and I think thzt it is not relevant. Like Google says about learning Data Science: Get your hands dirty ! Two popular platforms are here to help you to (truly) develop your Data Science coding skills: Kaggle : the most popular Data Science platform with an awesome community that learns from each other. At the end of this guide you will be able to run a Machine learning project on Kaggle ! :-) Hackerrank : This platform is really useful to learn, not from competition, but from courses specialisation with different challenges for different levels, go take a look ! Algorithm ? Model ? This common distinction has to be done before going any further. Machine Learning is made of algorithms like Random Forest or the famous XGBoost. Currently some geniuses around the world are developing more and more complex algorithms. Thanks to open-source libraries, you will not have to code them, just to know how to use them ! ;)A model is something more general, a model is made of several steps (including algorithms) to help you solve a specific problem. A Machine Learning project (I include here Deep Learning) can be of different types: Classification (i.e. discrete value): The goal of this kind of problem is to predict the “class” of an event, object, person... For example if you want to predict which brand a phone is using its performance, materials, country etc.Regression (i.e. continuous value): IThe goal of this kind of problem is to predict a specific value. For example if you want to predict the price of a phone. Classification (i.e. discrete value): The goal of this kind of problem is to predict the “class” of an event, object, person... For example if you want to predict which brand a phone is using its performance, materials, country etc. Regression (i.e. continuous value): IThe goal of this kind of problem is to predict a specific value. For example if you want to predict the price of a phone. Inside those two common problems in Machine Learning, you have three kind of approaches: Supervised: In supervised learning you have two different kind of columns. Features columns are columns that you will learn from to predict label columns (most of the time you will have to predict one label column). For example predicting the price of a phone for the next June regarding its past prices on previous months of June (and more other details as for example competitors, materials of the current version of the phone...) Unsupervised: An unsupervised learning is more tricky, you have many features and you have to find a way to classify some events or values. For example predicting the price of a new phone in June, but since it is a new phone you don’t have any past data. You will have to find a price using other data you have, for instance data from other phones that will match the best our new phone. Reinforcement: Most of the time during a reinforcement learning you don’t have any data, you have just some metrics that you want to maximize/minimize. Using different methods such as genetic algorithms, you will be able to perform an automatic task. For example to find the perfect combination of materials to maximize the margin of your new phone. Once that you are data science ready, let’s use a machine that will be your ally during this AI journey. Starting data science everyone’s first question is: Do I have enough power in my laptop to build and create a Terminator ? Well... Good question ! The first step is to know the resource of your computer. After that it depends on which kind of task you want to do. If you want to do Deep learning, by training your own neural networks from thousands of images, you will need to have a high level computer (with at least a Nvidia GPU 1080 and 32Go of RAM). But wait... Stay here! Most current laptops can run basic machine learning problems with data coming from a database (.csv to begin with) with around 100.000 rows. If you are going to deal with more data and more complexes data(such as image or sound), you will need to upgrade your laptop. From my point of view, a starting machine learning laptop should have at least 16Go of RAM and 8 processor cores, you can have less but it will take more time... If you need more resources for limited time , you can use cloud solutions, which may be more difficult for beginners to handle, as they require some advanced configuration. Do not hesitate to visit popular cloud solution providers for Machine Learning like Google Cloud Platform, Amazon Web Service or Microsoft Azur. As this guide is for beginners we will install all the needed stuff directly on your computer. Perhaps the first weirdest thing a beginner may see. You will find several word to define this black window : shell / bash / cmd / prompt, let’s call it just a terminal.The terminal allows you to access to access each folders and config of your computer and, believe it or not, it is faster than a mouse navigator when you master it ! Before the democratization of the mouse controller in each computer, everything was accessed using several terminal “command”. Unix ? Windows ? MacOS ? Linux ? Is it all the same regarding the terminal ? Unix is the core system of OSX and the inspiration of Linux, this mean that all commands are the same. Macbook and Linux users, you are already all set , jump to the next section !For Windows users stay here a little bit longer :-). Since Windows 10, Windows allow users to install unix command on the terminal, a huge success for many developers !You can install the unix terminal on windows with several methods, we will see below (Git section) the simplest I use, but here is a tutorial to allow you to install Unix command line with windows process : https://goo.gl/kYm1XC Once you have unix command installed on your machine, open a search bar. Type pwd in you terminal. pwd allows you to see in which folder you are. Type ls to list visible folders and files. And type ls --all to list each file included the dissimulated ones (Why are they dissimulated ? To simplify the navigation you do not see all files and folders by default. Most of the time hidden files are some config files you do not need to touch, but with your terminal, everything is accessible now, awesome no ?) choose a folder and type cd THE_NAME_OF_THE_FOLDER_HERE type again pwd and you should see that you just jumped inside this folder, congrats you made your first terminal navigation ! Take a look at the complete set of commands of Unix (type man COMMAND to get the manual entry for the command) Do not hesitate to play with it to feel more comfortable and Enjoy ! Now that you master the terminal, let’s install all the stuff we need to start to play with Artificial Intelligence ! Yes all it’s about Snakes, but no worries you will be fine, let’s become a snake charmer ;). Anaconda is a framework that install in your system all the basics stuff (libraries, modules, packages, language) needed on your computer in a simple way. Libraries ? Module ? Package ? Language ? Here we will use as “code language” , Python. But you have several others languages available for coding. To choose of the language depends on what you want to do (javascript for web development, SQL for database access, Java for app development, Swift for iOS app...). Python is one of the most famous language by its faculty to be human readable with an easy and understandable logic. As you may expect several programming functionalities have already been coded in Python. To not develop again functionalities others may have already developed, a common way to share code is to use libraries (i.e. modules, packages...) and code in open-source. The most famous platform to get all this open-source code is GitHub, and we will see how to install and use it later, no worries. Anaconda already installs all basic libraries listed below required to begin Data science. Let’s install Anaconda. Jump to their website here to download the installer and follow the installation process (available for all platforms — Windows / macOS / Linux) : I recommend to use the Python 3.7 version, as all libraries stop supporting Python 2.7. All libraries are not again already all set in this latest version, but do not hesitate to Google any difficulties you may encounter. For information, once Python is installed on your computer, you will really often use the command pip . pip is a libraries system management used from the terminal. After installing Anaconda, you will be able to use conda instead of thepip command line.I highly recommend you to use environments to manage all your projects, take a look here . With an environment you can choose the version of python you want and which librairies and versions of each you want to use. But you can come back later on this point when you will have more hours of practice in Data Science and coding. Let’s start to go a little bit deeper ! Git is an awesome system to manage and share code. As you may except when sometimes hundreds of people are working on the same project you cannot merge all your code manually by USB or worse with e-mail transfers. Git brings the system of code management, or versioning. To install Git on your machine download the installer here, depending of your system (MacOs, Linux, Windows). And here are the tutorial to install git on your machine. Remembering how to manage Unix command on windows ?Windows users please follow the few lines under to get Unix commands ! Open the installer Information > Click Next Select Components > Click Next Choosing the default editor used by Git > Use the Nano editor by default Adjusting your PATH environment : STOP ! Choose “Use Git and optional Unix tools from the Command Prompt” Choosing HTTPS transport backend > Use the OpenSSL library Configuring the line ending conversion > Checkout Windows-Style, commit Unix-style line endings Configuring the terminal emulator to use with Git Bash: STOP ! Choose “Use windows’ default console windows” Configuring extra options > Enable file system caching & Enable Git Credential Manager Install and welcome in this amazing new world of billions of line of code ! A fast guide here to allow you to install Git and understand how it works with your new terminal command line skills ;) : Git PlatformAround Git several platforms have been built to allow in a simple view to manage “repositories”. (wut ?) A repository is a project in the Git world :-). Some of those platforms : Bitbucket , GitLab, CodeBase, Assembla ...The most famous platform which allows you to find all you need is Github.First step: go on Github and create an account, for regular use all everything is free by the way.You are now able to access billions of lines of code, some of them are from top tech companies, like Google and it will simplify your first step in DataScience. Do not hesitate to go across the platform and discover awesome projects as the Dense Pose project from Facebook. Never forget that we all use open-source projects. Please do not hesitate to share your code with the community and contribute to open-source projects, thousand of projects are waiting for you ! Code is an awesome tool for sharing knowledge, sharing before thinking to make money is so much more profitable for everyone, let’s follow this mindset. As .docx is for Word Office, .xlsx for Excel, .png for images, .py is the extension for Python Script. To access and manage a Python Script, you have several software with different levels of complexity and different features, most of them are called IDEs for Integrated Development Environments. Let’s present four of them but again do not hesitate to try and search on the internet for some others, find the one that fits best with you : Pycharm : The most complete, stable but the most complex, allowing you to view, stop, run, follow the process of your code, including Git and automtic error control. Spyder : Less features than Pycharm but easier to install and has complete features for beginners. Visual Studio Code : An IDE really simple of use, with less features than others used by professionals but also perfect for beginners. Sublime text : The most simple of use, but Sublime text allow you just to edit your code you will need to go back on your terminal to run your script. Once Python is installed on your computer, to run a .py script you will just need to type on your terminal inside the folder which contains your script: python my_awesome_script.py .ipynb is the extension for notebooks. The most famous notebook runner is Jupyter. Notebook ? Script? They are both useful for Data Science projects. Here is an image from Kaggle, the most famous Data Science platform that explain you the difference. When you start a new project (named a kernel) you have to choose between script or notebook. Globally a notebook is used for Data exploration / Analytics and run models and lines several times step by step without going back to the beginning of your code execution. But as you have to start a local server, it is slower and less scalable than a script. To install notebook in the terminal, we will install jupyter lab: with conda:conda install -c conda-forge jupyterlab with pip: pip install jupyterlab Here is the full website documentation but with your new git skills you can also access to Github repo ! :-) Once installed you can run Jupyter Lab with the command line : jupyter lab Let’s apply all this new stuff ! Time to practice all this new knowledge. This final part contains a tutorial to run your first machine learning project through all steps required : Init a project Mission understanding : We are gonna to work with the famous titanic dataset “to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy”. (thanks to the Kaggle Challenge here ) Data Exploration / Analytics Data Visualization Features Engineering Modeling Prediction I made a project that will help you to start this journey. We are going to use this github repo.I highly recommend you to fork the project to be able to modify it and play with it as you want. What is a fork ? Jump on this support Github website here. Open a terminal Navigate to the location desired and clone the repository, you can use the direct url of the repo (https://github.com/anisayari/your_first_machine_learning_project.git), but I recommend you to switch with your forked url which should look like : https://github.com/YOURUSERNAME/your_first_machine_learning_project.git C:\Users\AAyari> cd DesktopC:\Users\AAyari> git clone https://github.com/anisayari/your_first_machine_learning_project.gitCloning into 'your_first_machine_learning_project'...remote: Enumerating objects: 22, done.remote: Counting objects: 100% (22/22), done.remote: Compressing objects: 100% (19/19), done.remote: Total 22 (delta 4), reused 11 (delta 0), pack-reused 0Unpacking objects: 100% (22/22), done. Navigate to the file and start jupyter lab to see the notebook : C:\Users\AAyari> cd your_first_machine_learning_projectC:\Users\AAyari\Desktop\your_first_machine_learning_project> cd my_first_machine_learning_projectC:\Users\AAyari\Desktop\your_first_machine_learning_project\my_first_machine_learning_project> jupyter lab[I 11:11:57.121 LabApp] The Jupyter Notebook is running at: Great ! Our Jupyter Lab is running and you are now able to access your notebook. The Jupyter Lab should have opened in a new browser tab, click onthe file my_first_machine_learning_program_notebook.ipynb.The browser window should look like the image below : Enjoy this notebook ! It is well commented, do not hesitate to go through those lines and try to reproduce them and improve them. You should have noticed my_first_machine_learning_program.pyit is the script version of the kernel. Try to run it and see the differences ! You will better understand the difference between a notebook and a script. To run this script : C:\Users\AAyari\Desktop\your_first_machine_learning_project\my_first_machine_learning_project> python my_first_machine_learning_program.py Want to use it on Kaggle ? The notebook is available on kaggle here, do not hesitate to “Fork” it and to run it to submit your first Machine Learning program on Kaggle ! Now you should be able to : know which skills and knowledge you have to develop, and where to learn them understand basic words used in Data Science (such as notebook, supervised, model...) got all basic software required to run and manage python code on your laptop And last but not least, you should be able to say to your colleagues that you ran your first machine learning program ! Again ,congratulation and thank you for reading this guide. The Data Science and Artificial Intelligence fields are exciting areas of knowledge, be curious and go around the internet to discover always more. Welcome to your Data Science/AI journey.
[ { "code": null, "e": 575, "s": 171, "text": "AI & Data Science are already skills that everyone should develop. With this guide we will go through a fast tutorial to present you how to start this technical journey (platforms to learn and apply skills, installation on your computer, useful software). At the end of this article you will be able to run your first Machine Learning program ! This guide is made for the non expert, so no worries ! :-)" }, { "code": null, "e": 674, "s": 575, "text": "You are all set now to start your Data Science & Artificial Intelligence journey. Welcome aboard !" }, { "code": null, "e": 703, "s": 674, "text": "Faculty to learn by yourself" }, { "code": null, "e": 1756, "s": 703, "text": "Data Science / AI / Machine Learning / Deep Learning, all those fields are currently being defined. So the first thing to learn is the faculty to be always active in learning. Not sure about something ? Looking for the definition of a supervised algorithm ? A bug in your program ? Google it (or use any other search engine as Qwant or Ecosia) !Be careful about your sources, since AI is a new field you may see a lot of different and sometimes contradictory information. No one has the absolute truth here about definitions or knowledge. Search, interact and construct your own ideas ! It is why I recommend to learn from collaborative platform. On hot topic such as AI, collaborative platforms are a good source of information as you can go across the discussion thread, identify the person, and be able to challenge any answer or ask for more details.If you have an issue or an interrogation, you can be sure that someone before you already asked for it on some website. You may also already be able to help people so do not hesitate to contribute :" }, { "code": null, "e": 1803, "s": 1756, "text": "Stack Overflow your new best friend for coding" }, { "code": null, "e": 1836, "s": 1803, "text": "Quora sharing knowledge platform" }, { "code": null, "e": 1873, "s": 1836, "text": "Wikipedia the universal encyclopedia" }, { "code": null, "e": 1891, "s": 1873, "text": "Medium by the way" }, { "code": null, "e": 2101, "s": 1891, "text": "When you will be a little more advanced in machine learning your key sources references will be documentations from libraries as for example this documentation from scikit-learn here or Tensorflow and Pytorch." }, { "code": null, "e": 2140, "s": 2101, "text": "Mathematical and statistical knowledge" }, { "code": null, "e": 2427, "s": 2140, "text": "Machine Learning, Data Science and Artificial Intelligence requires strong mathematical and statistical knowledge. Here are the fields of knowledge you have to go through to start to understand Data Science(please do not hesitate to comment with some other field to complete the list) :" }, { "code": null, "e": 2485, "s": 2427, "text": "Common Algebraic Theory (Linear model and matrix Algebra)" }, { "code": null, "e": 2517, "s": 2485, "text": "Probability and Bayesian Theory" }, { "code": null, "e": 2533, "s": 2517, "text": "Decision Theory" }, { "code": null, "e": 2546, "s": 2533, "text": "Graph Theory" }, { "code": null, "e": 2566, "s": 2546, "text": "Functional Analysis" }, { "code": null, "e": 2578, "s": 2566, "text": "Game Theory" }, { "code": null, "e": 2594, "s": 2578, "text": "Algorithm Logic" }, { "code": null, "e": 2606, "s": 2594, "text": "Resources :" }, { "code": null, "e": 2650, "s": 2606, "text": "Data Science Math Skills by Duke University" }, { "code": null, "e": 2711, "s": 2650, "text": "Introduction to Mathematical Thinking by Stanford University" }, { "code": null, "e": 2782, "s": 2711, "text": "Introduction to Linear Models and Matrix Algebra by Harvard University" }, { "code": null, "e": 2819, "s": 2782, "text": "Mathematical lessons by Khan Academy" }, { "code": null, "e": 2843, "s": 2819, "text": "Python for Data Science" }, { "code": null, "e": 3006, "s": 2843, "text": "Python is a language used for many things (websites, games, applications, back-ends, database administration...). To use Python for Data Science you will need to:" }, { "code": null, "e": 3050, "s": 3006, "text": "understand the common logic of the language" }, { "code": null, "e": 3077, "s": 3050, "text": "learn how to use libraries" }, { "code": null, "e": 3355, "s": 3077, "text": "What are the most common librairies in Data Science ?Pandas for data manipulation, seaborn/matplotlib for data visualization, numpy for mathematical manipulation, sklearn for algorithms use, keras, pytorch and tensorflow for more advanced use (like neural network for example)." }, { "code": null, "e": 3367, "s": 3355, "text": "Resources :" }, { "code": null, "e": 3403, "s": 3367, "text": "Introduction to Python by Microsoft" }, { "code": null, "e": 3451, "s": 3403, "text": "Python Data Science Handbook by Jake Vanderplas" }, { "code": null, "e": 3510, "s": 3451, "text": "Applied Data Science with Python by University of Michigan" }, { "code": null, "e": 3531, "s": 3510, "text": "Data Science courses" }, { "code": null, "e": 3837, "s": 3531, "text": "Once you have all those mathematical and code knowledge, it’s time to go into the Data Science field. You will need to learn new skills. A Data Scientist should be able to have a wide overview of all those skills listed below. But depending on what you want to specialize in only a few should be mastered." }, { "code": null, "e": 3983, "s": 3837, "text": "Database Management: To access different kind of data from different kind of sources (SQL, No SQL, structured, not structured, cluster, file...)." }, { "code": null, "e": 4074, "s": 3983, "text": "Data Structure: To easily manipulate and prepare your data including features engineering." }, { "code": null, "e": 4161, "s": 4074, "text": "Data Visualizations: To understand your data by visualising it rather than reading it." }, { "code": null, "e": 4516, "s": 4161, "text": "Algorithms: There is nothing worse than trying all algorithms available and take the one that seems “better” regarding specific metrics, this is a waste of time. Each well trained Data Scientist should know how commons algorithms of Machine Learning work. From this knowledge the Data Scientist will be able to choose an algorithm from the data analysis." }, { "code": null, "e": 4639, "s": 4516, "text": "Evaluation: Combining data visualization and metrics knowledge a Data Scientist have to know if a model works well or not." }, { "code": null, "e": 4835, "s": 4639, "text": "Interpretability: We have to solve the myth of the “Black Box”. Machine Learning interpretability (with some libraries such as Shap or Lime ) help us understand how a Data Science solution works." }, { "code": null, "e": 4991, "s": 4835, "text": "Knowledge about web and infrastructure security : To not save, run or deploy a solution that could be dangerous for an organisation or your private laptop." }, { "code": null, "e": 5003, "s": 4991, "text": "Resources :" }, { "code": null, "e": 5043, "s": 5003, "text": "Machine Learning by Stanford University" }, { "code": null, "e": 5096, "s": 5043, "text": "Data Science: Machine Learning by Harvard University" }, { "code": null, "e": 5127, "s": 5096, "text": "Learn by applying you Skills !" }, { "code": null, "e": 5521, "s": 5127, "text": "Perhaps my favorite method of learning, is to directly learn by applying immediate skills (and by applying skill I mean coding !). You will meet many people talking of Machine Learning, Data Science, Analytics or Artificial Intelligence without having ever touched a single line of code, and I think thzt it is not relevant. Like Google says about learning Data Science: Get your hands dirty !" }, { "code": null, "e": 5616, "s": 5521, "text": "Two popular platforms are here to help you to (truly) develop your Data Science coding skills:" }, { "code": null, "e": 5811, "s": 5616, "text": "Kaggle : the most popular Data Science platform with an awesome community that learns from each other. At the end of this guide you will be able to run a Machine learning project on Kaggle ! :-)" }, { "code": null, "e": 5984, "s": 5811, "text": "Hackerrank : This platform is really useful to learn, not from competition, but from courses specialisation with different challenges for different levels, go take a look !" }, { "code": null, "e": 6467, "s": 5984, "text": "Algorithm ? Model ? This common distinction has to be done before going any further. Machine Learning is made of algorithms like Random Forest or the famous XGBoost. Currently some geniuses around the world are developing more and more complex algorithms. Thanks to open-source libraries, you will not have to code them, just to know how to use them ! ;)A model is something more general, a model is made of several steps (including algorithms) to help you solve a specific problem." }, { "code": null, "e": 6552, "s": 6467, "text": "A Machine Learning project (I include here Deep Learning) can be of different types:" }, { "code": null, "e": 6943, "s": 6552, "text": "Classification (i.e. discrete value): The goal of this kind of problem is to predict the “class” of an event, object, person... For example if you want to predict which brand a phone is using its performance, materials, country etc.Regression (i.e. continuous value): IThe goal of this kind of problem is to predict a specific value. For example if you want to predict the price of a phone." }, { "code": null, "e": 7176, "s": 6943, "text": "Classification (i.e. discrete value): The goal of this kind of problem is to predict the “class” of an event, object, person... For example if you want to predict which brand a phone is using its performance, materials, country etc." }, { "code": null, "e": 7335, "s": 7176, "text": "Regression (i.e. continuous value): IThe goal of this kind of problem is to predict a specific value. For example if you want to predict the price of a phone." }, { "code": null, "e": 7424, "s": 7335, "text": "Inside those two common problems in Machine Learning, you have three kind of approaches:" }, { "code": null, "e": 7857, "s": 7424, "text": "Supervised: In supervised learning you have two different kind of columns. Features columns are columns that you will learn from to predict label columns (most of the time you will have to predict one label column). For example predicting the price of a phone for the next June regarding its past prices on previous months of June (and more other details as for example competitors, materials of the current version of the phone...)" }, { "code": null, "e": 8245, "s": 7857, "text": "Unsupervised: An unsupervised learning is more tricky, you have many features and you have to find a way to classify some events or values. For example predicting the price of a new phone in June, but since it is a new phone you don’t have any past data. You will have to find a price using other data you have, for instance data from other phones that will match the best our new phone." }, { "code": null, "e": 8595, "s": 8245, "text": "Reinforcement: Most of the time during a reinforcement learning you don’t have any data, you have just some metrics that you want to maximize/minimize. Using different methods such as genetic algorithms, you will be able to perform an automatic task. For example to find the perfect combination of materials to maximize the margin of your new phone." }, { "code": null, "e": 8700, "s": 8595, "text": "Once that you are data science ready, let’s use a machine that will be your ally during this AI journey." }, { "code": null, "e": 8823, "s": 8700, "text": "Starting data science everyone’s first question is: Do I have enough power in my laptop to build and create a Terminator ?" }, { "code": null, "e": 9608, "s": 8823, "text": "Well... Good question ! The first step is to know the resource of your computer. After that it depends on which kind of task you want to do. If you want to do Deep learning, by training your own neural networks from thousands of images, you will need to have a high level computer (with at least a Nvidia GPU 1080 and 32Go of RAM). But wait... Stay here! Most current laptops can run basic machine learning problems with data coming from a database (.csv to begin with) with around 100.000 rows. If you are going to deal with more data and more complexes data(such as image or sound), you will need to upgrade your laptop. From my point of view, a starting machine learning laptop should have at least 16Go of RAM and 8 processor cores, you can have less but it will take more time..." }, { "code": null, "e": 9926, "s": 9608, "text": "If you need more resources for limited time , you can use cloud solutions, which may be more difficult for beginners to handle, as they require some advanced configuration. Do not hesitate to visit popular cloud solution providers for Machine Learning like Google Cloud Platform, Amazon Web Service or Microsoft Azur." }, { "code": null, "e": 10021, "s": 9926, "text": "As this guide is for beginners we will install all the needed stuff directly on your computer." }, { "code": null, "e": 10483, "s": 10021, "text": "Perhaps the first weirdest thing a beginner may see. You will find several word to define this black window : shell / bash / cmd / prompt, let’s call it just a terminal.The terminal allows you to access to access each folders and config of your computer and, believe it or not, it is faster than a mouse navigator when you master it ! Before the democratization of the mouse controller in each computer, everything was accessed using several terminal “command”." }, { "code": null, "e": 10560, "s": 10483, "text": "Unix ? Windows ? MacOS ? Linux ? Is it all the same regarding the terminal ?" }, { "code": null, "e": 11137, "s": 10560, "text": "Unix is the core system of OSX and the inspiration of Linux, this mean that all commands are the same. Macbook and Linux users, you are already all set , jump to the next section !For Windows users stay here a little bit longer :-). Since Windows 10, Windows allow users to install unix command on the terminal, a huge success for many developers !You can install the unix terminal on windows with several methods, we will see below (Git section) the simplest I use, but here is a tutorial to allow you to install Unix command line with windows process : https://goo.gl/kYm1XC" }, { "code": null, "e": 11210, "s": 11137, "text": "Once you have unix command installed on your machine, open a search bar." }, { "code": null, "e": 11283, "s": 11210, "text": "Type pwd in you terminal. pwd allows you to see in which folder you are." }, { "code": null, "e": 11644, "s": 11283, "text": "Type ls to list visible folders and files. And type ls --all to list each file included the dissimulated ones (Why are they dissimulated ? To simplify the navigation you do not see all files and folders by default. Most of the time hidden files are some config files you do not need to touch, but with your terminal, everything is accessible now, awesome no ?)" }, { "code": null, "e": 11700, "s": 11644, "text": "choose a folder and type cd THE_NAME_OF_THE_FOLDER_HERE" }, { "code": null, "e": 11826, "s": 11700, "text": "type again pwd and you should see that you just jumped inside this folder, congrats you made your first terminal navigation !" }, { "code": null, "e": 11937, "s": 11826, "text": "Take a look at the complete set of commands of Unix (type man COMMAND to get the manual entry for the command)" }, { "code": null, "e": 12006, "s": 11937, "text": "Do not hesitate to play with it to feel more comfortable and Enjoy !" }, { "code": null, "e": 12124, "s": 12006, "text": "Now that you master the terminal, let’s install all the stuff we need to start to play with Artificial Intelligence !" }, { "code": null, "e": 12217, "s": 12124, "text": "Yes all it’s about Snakes, but no worries you will be fine, let’s become a snake charmer ;)." }, { "code": null, "e": 12372, "s": 12217, "text": "Anaconda is a framework that install in your system all the basics stuff (libraries, modules, packages, language) needed on your computer in a simple way." }, { "code": null, "e": 12414, "s": 12372, "text": "Libraries ? Module ? Package ? Language ?" }, { "code": null, "e": 12801, "s": 12414, "text": "Here we will use as “code language” , Python. But you have several others languages available for coding. To choose of the language depends on what you want to do (javascript for web development, SQL for database access, Java for app development, Swift for iOS app...). Python is one of the most famous language by its faculty to be human readable with an easy and understandable logic." }, { "code": null, "e": 13283, "s": 12801, "text": "As you may expect several programming functionalities have already been coded in Python. To not develop again functionalities others may have already developed, a common way to share code is to use libraries (i.e. modules, packages...) and code in open-source. The most famous platform to get all this open-source code is GitHub, and we will see how to install and use it later, no worries. Anaconda already installs all basic libraries listed below required to begin Data science." }, { "code": null, "e": 13454, "s": 13283, "text": "Let’s install Anaconda. Jump to their website here to download the installer and follow the installation process (available for all platforms — Windows / macOS / Linux) :" }, { "code": null, "e": 13676, "s": 13454, "text": "I recommend to use the Python 3.7 version, as all libraries stop supporting Python 2.7. All libraries are not again already all set in this latest version, but do not hesitate to Google any difficulties you may encounter." }, { "code": null, "e": 13841, "s": 13676, "text": "For information, once Python is installed on your computer, you will really often use the command pip . pip is a libraries system management used from the terminal." }, { "code": null, "e": 14257, "s": 13841, "text": "After installing Anaconda, you will be able to use conda instead of thepip command line.I highly recommend you to use environments to manage all your projects, take a look here . With an environment you can choose the version of python you want and which librairies and versions of each you want to use. But you can come back later on this point when you will have more hours of practice in Data Science and coding." }, { "code": null, "e": 14568, "s": 14257, "text": "Let’s start to go a little bit deeper ! Git is an awesome system to manage and share code. As you may except when sometimes hundreds of people are working on the same project you cannot merge all your code manually by USB or worse with e-mail transfers. Git brings the system of code management, or versioning." }, { "code": null, "e": 14736, "s": 14568, "text": "To install Git on your machine download the installer here, depending of your system (MacOs, Linux, Windows). And here are the tutorial to install git on your machine." }, { "code": null, "e": 14858, "s": 14736, "text": "Remembering how to manage Unix command on windows ?Windows users please follow the few lines under to get Unix commands !" }, { "code": null, "e": 14877, "s": 14858, "text": "Open the installer" }, { "code": null, "e": 14902, "s": 14877, "text": "Information > Click Next" }, { "code": null, "e": 14933, "s": 14902, "text": "Select Components > Click Next" }, { "code": null, "e": 15006, "s": 14933, "text": "Choosing the default editor used by Git > Use the Nano editor by default" }, { "code": null, "e": 15112, "s": 15006, "text": "Adjusting your PATH environment : STOP ! Choose “Use Git and optional Unix tools from the Command Prompt”" }, { "code": null, "e": 15171, "s": 15112, "text": "Choosing HTTPS transport backend > Use the OpenSSL library" }, { "code": null, "e": 15267, "s": 15171, "text": "Configuring the line ending conversion > Checkout Windows-Style, commit Unix-style line endings" }, { "code": null, "e": 15376, "s": 15267, "text": "Configuring the terminal emulator to use with Git Bash: STOP ! Choose “Use windows’ default console windows”" }, { "code": null, "e": 15463, "s": 15376, "text": "Configuring extra options > Enable file system caching & Enable Git Credential Manager" }, { "code": null, "e": 15539, "s": 15463, "text": "Install and welcome in this amazing new world of billions of line of code !" }, { "code": null, "e": 15661, "s": 15539, "text": "A fast guide here to allow you to install Git and understand how it works with your new terminal command line skills ;) :" }, { "code": null, "e": 16339, "s": 15661, "text": "Git PlatformAround Git several platforms have been built to allow in a simple view to manage “repositories”. (wut ?) A repository is a project in the Git world :-). Some of those platforms : Bitbucket , GitLab, CodeBase, Assembla ...The most famous platform which allows you to find all you need is Github.First step: go on Github and create an account, for regular use all everything is free by the way.You are now able to access billions of lines of code, some of them are from top tech companies, like Google and it will simplify your first step in DataScience. Do not hesitate to go across the platform and discover awesome projects as the Dense Pose project from Facebook." }, { "code": null, "e": 16687, "s": 16339, "text": "Never forget that we all use open-source projects. Please do not hesitate to share your code with the community and contribute to open-source projects, thousand of projects are waiting for you ! Code is an awesome tool for sharing knowledge, sharing before thinking to make money is so much more profitable for everyone, let’s follow this mindset." }, { "code": null, "e": 16790, "s": 16687, "text": "As .docx is for Word Office, .xlsx for Excel, .png for images, .py is the extension for Python Script." }, { "code": null, "e": 17127, "s": 16790, "text": "To access and manage a Python Script, you have several software with different levels of complexity and different features, most of them are called IDEs for Integrated Development Environments. Let’s present four of them but again do not hesitate to try and search on the internet for some others, find the one that fits best with you :" }, { "code": null, "e": 17293, "s": 17127, "text": "Pycharm : The most complete, stable but the most complex, allowing you to view, stop, run, follow the process of your code, including Git and automtic error control." }, { "code": null, "e": 17392, "s": 17293, "text": "Spyder : Less features than Pycharm but easier to install and has complete features for beginners." }, { "code": null, "e": 17527, "s": 17392, "text": "Visual Studio Code : An IDE really simple of use, with less features than others used by professionals but also perfect for beginners." }, { "code": null, "e": 17678, "s": 17527, "text": "Sublime text : The most simple of use, but Sublime text allow you just to edit your code you will need to go back on your terminal to run your script." }, { "code": null, "e": 17859, "s": 17678, "text": "Once Python is installed on your computer, to run a .py script you will just need to type on your terminal inside the folder which contains your script: python my_awesome_script.py" }, { "code": null, "e": 17942, "s": 17859, "text": ".ipynb is the extension for notebooks. The most famous notebook runner is Jupyter." }, { "code": null, "e": 17961, "s": 17942, "text": "Notebook ? Script?" }, { "code": null, "e": 18203, "s": 17961, "text": "They are both useful for Data Science projects. Here is an image from Kaggle, the most famous Data Science platform that explain you the difference. When you start a new project (named a kernel) you have to choose between script or notebook." }, { "code": null, "e": 18463, "s": 18203, "text": "Globally a notebook is used for Data exploration / Analytics and run models and lines several times step by step without going back to the beginning of your code execution. But as you have to start a local server, it is slower and less scalable than a script." }, { "code": null, "e": 18529, "s": 18463, "text": "To install notebook in the terminal, we will install jupyter lab:" }, { "code": null, "e": 18580, "s": 18529, "text": "with conda:conda install -c conda-forge jupyterlab" }, { "code": null, "e": 18613, "s": 18580, "text": "with pip: pip install jupyterlab" }, { "code": null, "e": 18722, "s": 18613, "text": "Here is the full website documentation but with your new git skills you can also access to Github repo ! :-)" }, { "code": null, "e": 18797, "s": 18722, "text": "Once installed you can run Jupyter Lab with the command line : jupyter lab" }, { "code": null, "e": 18830, "s": 18797, "text": "Let’s apply all this new stuff !" }, { "code": null, "e": 18979, "s": 18830, "text": "Time to practice all this new knowledge. This final part contains a tutorial to run your first machine learning project through all steps required :" }, { "code": null, "e": 18994, "s": 18979, "text": "Init a project" }, { "code": null, "e": 19300, "s": 18994, "text": "Mission understanding : We are gonna to work with the famous titanic dataset “to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy”. (thanks to the Kaggle Challenge here )" }, { "code": null, "e": 19329, "s": 19300, "text": "Data Exploration / Analytics" }, { "code": null, "e": 19348, "s": 19329, "text": "Data Visualization" }, { "code": null, "e": 19369, "s": 19348, "text": "Features Engineering" }, { "code": null, "e": 19378, "s": 19369, "text": "Modeling" }, { "code": null, "e": 19389, "s": 19378, "text": "Prediction" }, { "code": null, "e": 19641, "s": 19389, "text": "I made a project that will help you to start this journey. We are going to use this github repo.I highly recommend you to fork the project to be able to modify it and play with it as you want. What is a fork ? Jump on this support Github website here." }, { "code": null, "e": 19657, "s": 19641, "text": "Open a terminal" }, { "code": null, "e": 19975, "s": 19657, "text": "Navigate to the location desired and clone the repository, you can use the direct url of the repo (https://github.com/anisayari/your_first_machine_learning_project.git), but I recommend you to switch with your forked url which should look like : https://github.com/YOURUSERNAME/your_first_machine_learning_project.git" }, { "code": null, "e": 20382, "s": 19975, "text": "C:\\Users\\AAyari> cd DesktopC:\\Users\\AAyari> git clone https://github.com/anisayari/your_first_machine_learning_project.gitCloning into 'your_first_machine_learning_project'...remote: Enumerating objects: 22, done.remote: Counting objects: 100% (22/22), done.remote: Compressing objects: 100% (19/19), done.remote: Total 22 (delta 4), reused 11 (delta 0), pack-reused 0Unpacking objects: 100% (22/22), done." }, { "code": null, "e": 20447, "s": 20382, "text": "Navigate to the file and start jupyter lab to see the notebook :" }, { "code": null, "e": 20765, "s": 20447, "text": "C:\\Users\\AAyari> cd your_first_machine_learning_projectC:\\Users\\AAyari\\Desktop\\your_first_machine_learning_project> cd my_first_machine_learning_projectC:\\Users\\AAyari\\Desktop\\your_first_machine_learning_project\\my_first_machine_learning_project> jupyter lab[I 11:11:57.121 LabApp] The Jupyter Notebook is running at:" }, { "code": null, "e": 21023, "s": 20765, "text": "Great ! Our Jupyter Lab is running and you are now able to access your notebook. The Jupyter Lab should have opened in a new browser tab, click onthe file my_first_machine_learning_program_notebook.ipynb.The browser window should look like the image below :" }, { "code": null, "e": 21153, "s": 21023, "text": "Enjoy this notebook ! It is well commented, do not hesitate to go through those lines and try to reproduce them and improve them." }, { "code": null, "e": 21389, "s": 21153, "text": "You should have noticed my_first_machine_learning_program.pyit is the script version of the kernel. Try to run it and see the differences ! You will better understand the difference between a notebook and a script. To run this script :" }, { "code": null, "e": 21528, "s": 21389, "text": "C:\\Users\\AAyari\\Desktop\\your_first_machine_learning_project\\my_first_machine_learning_project> python my_first_machine_learning_program.py" }, { "code": null, "e": 21698, "s": 21528, "text": "Want to use it on Kaggle ? The notebook is available on kaggle here, do not hesitate to “Fork” it and to run it to submit your first Machine Learning program on Kaggle !" }, { "code": null, "e": 21726, "s": 21698, "text": "Now you should be able to :" }, { "code": null, "e": 21803, "s": 21726, "text": "know which skills and knowledge you have to develop, and where to learn them" }, { "code": null, "e": 21888, "s": 21803, "text": "understand basic words used in Data Science (such as notebook, supervised, model...)" }, { "code": null, "e": 21965, "s": 21888, "text": "got all basic software required to run and manage python code on your laptop" }, { "code": null, "e": 22145, "s": 21965, "text": "And last but not least, you should be able to say to your colleagues that you ran your first machine learning program ! Again ,congratulation and thank you for reading this guide." }, { "code": null, "e": 22293, "s": 22145, "text": "The Data Science and Artificial Intelligence fields are exciting areas of knowledge, be curious and go around the internet to discover always more." } ]
Advanced SQL Interview Questions - GeeksforGeeks
18 Sep, 2019 Different companies have a different approach to their interviewing process. Some would be concentrating on work experience and knowledge; others might focus on personality, while the rest fall somewhere in between. Therefore, finding and learning from different interview questions and answers can help see different perspectives of what might be most important in different marketplaces. So, here’s a list of advanced SQL interview questions by blockchain-based eLearning platform. Que-1: Explain the meaning of ‘index’.Explanation:Indexes help retrieve information from the database faster and with higher efficiency. In other words, it’s a method that enhances performance and there are 3 types of indexes:Clustered – reorders the table and searches for information with the use of key valuesNon-clustered – maintains the order of the tableUnique – forbids fields to have duplicated valuesMoreover, a table can have multiple non-cluster indexes, but only 1 single clustered one. Clustered – reorders the table and searches for information with the use of key values Non-clustered – maintains the order of the table Unique – forbids fields to have duplicated values Moreover, a table can have multiple non-cluster indexes, but only 1 single clustered one. Que-2: You forgot your root password, what do you do ?Explanation:Start the database with the command of “skip-grants-table”.After you set the new password, restart the database in normal mode and enter the new password. Start the database with the command of “skip-grants-table”.After you set the new password, restart the database in normal mode and enter the new password. Start the database with the command of “skip-grants-table”. After you set the new password, restart the database in normal mode and enter the new password. Que-3: Are NULL values equal to a zero ?Explanation:No, because a “zero” has a numerical manner and NULL represent the absence of a character. This happens when the character is unknown or unavailable. Additionally, NULL shouldn’t be confused with blank space because data record without any value assigned is not the same as a plain blank space, with no data records attached. Que-4: Data disk gets overloaded, what do you do ?Explanation:You should apply a soft link: these links create a location where you are able to store your .frm and .idb files. This will resolve the overload problem. Que-5: Explain what‘auto increment’ is?Explanation:This command allows you to generate a unique number when a new record is written to a table. When you want to the primary key field value to be generated automatically each time you insert a new record, this is when this function comes in handy.Another thing worth noting is that the command can be used on various platforms. For SQL Servers the “auto increment” command is “identity”. Another thing worth noting is that the command can be used on various platforms. For SQL Servers the “auto increment” command is “identity”. Que-6: What are the most basic MySQL architecture components ?Explanation:There are three main components:Query optimizer;Connection manager;Pluggable engine. Query optimizer;Connection manager;Pluggable engine. Query optimizer; Connection manager; Pluggable engine. Que-7: Using an existing table, make an empty one.Explanation:Select * into employeecopy from employee where 1=2 Select * into employeecopy from employee where 1=2 Que-8: How would you check your current SQL version ?Explanation:You can get the most current SQL version by issuing this command:SELECT VERSION() SELECT VERSION() Que-9: Get alternative odd records from the table.Explanation:This can be achieved using the command:Select employeeId from (Select rowno, employeetId from employee) where mod(rowno, 2)=1 Select employeeId from (Select rowno, employeetId from employee) where mod(rowno, 2)=1 Que-10: What command would select a unique record from the table ?Explanation:The “distinct” command. Here’s an example:Select DISTINCT employeeID from Employee Select DISTINCT employeeID from Employee Que-11: What are variables of SQL ?Explanation:In SQL, there are two different variables:Local – these variables can only exist in one single functionGlobal – are the opposite of local, which means they can be located through ought the entire program. Local – these variables can only exist in one single function Global – are the opposite of local, which means they can be located through ought the entire program. Que-12: What is a ‘datawarehouse’ and what it does ?Explanation:A “datawarehouse” is a system used for data analysis and reporting. Basically, it’s a warehouse of data. Data in DWs can be stored from various areas and sources and thus makes them central repositories of integrated data that is ready for usage. Que-13: For what ‘recursive stored procedure’ is mainly used ?Explanation:A recursive stored procedure is a procedure that will make the code calls itself until specific boundary condition is reached. This is a productivity type of thing, that allows programmers to use the same code a number of times. Que-14: Retrieve the first 3 characters from a character string.Explanation:There are a few ways to do this. Nevertheless, the command presented below can be treated as a more popular and easier one:Select SUBSTRING(EmployeeSurname, 1, 5) as employeesurname from employee Select SUBSTRING(EmployeeSurname, 1, 5) as employeesurname from employee Que-15: How would you retrieve common records from two tables ?Explanation:By performing the task below:Select employeeID from employee. INTERSECT Select EmployeeID from WorkShift Select employeeID from employee. INTERSECT Select EmployeeID from WorkShift Interview Tips interview-preparation placement preparation DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of ER Model SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) SQL Trigger | Student Database SQL | Views
[ { "code": null, "e": 24011, "s": 23983, "text": "\n18 Sep, 2019" }, { "code": null, "e": 24227, "s": 24011, "text": "Different companies have a different approach to their interviewing process. Some would be concentrating on work experience and knowledge; others might focus on personality, while the rest fall somewhere in between." }, { "code": null, "e": 24495, "s": 24227, "text": "Therefore, finding and learning from different interview questions and answers can help see different perspectives of what might be most important in different marketplaces. So, here’s a list of advanced SQL interview questions by blockchain-based eLearning platform." }, { "code": null, "e": 24994, "s": 24495, "text": "Que-1: Explain the meaning of ‘index’.Explanation:Indexes help retrieve information from the database faster and with higher efficiency. In other words, it’s a method that enhances performance and there are 3 types of indexes:Clustered – reorders the table and searches for information with the use of key valuesNon-clustered – maintains the order of the tableUnique – forbids fields to have duplicated valuesMoreover, a table can have multiple non-cluster indexes, but only 1 single clustered one." }, { "code": null, "e": 25081, "s": 24994, "text": "Clustered – reorders the table and searches for information with the use of key values" }, { "code": null, "e": 25130, "s": 25081, "text": "Non-clustered – maintains the order of the table" }, { "code": null, "e": 25180, "s": 25130, "text": "Unique – forbids fields to have duplicated values" }, { "code": null, "e": 25270, "s": 25180, "text": "Moreover, a table can have multiple non-cluster indexes, but only 1 single clustered one." }, { "code": null, "e": 25491, "s": 25270, "text": "Que-2: You forgot your root password, what do you do ?Explanation:Start the database with the command of “skip-grants-table”.After you set the new password, restart the database in normal mode and enter the new password." }, { "code": null, "e": 25646, "s": 25491, "text": "Start the database with the command of “skip-grants-table”.After you set the new password, restart the database in normal mode and enter the new password." }, { "code": null, "e": 25706, "s": 25646, "text": "Start the database with the command of “skip-grants-table”." }, { "code": null, "e": 25802, "s": 25706, "text": "After you set the new password, restart the database in normal mode and enter the new password." }, { "code": null, "e": 26180, "s": 25802, "text": "Que-3: Are NULL values equal to a zero ?Explanation:No, because a “zero” has a numerical manner and NULL represent the absence of a character. This happens when the character is unknown or unavailable. Additionally, NULL shouldn’t be confused with blank space because data record without any value assigned is not the same as a plain blank space, with no data records attached." }, { "code": null, "e": 26396, "s": 26180, "text": "Que-4: Data disk gets overloaded, what do you do ?Explanation:You should apply a soft link: these links create a location where you are able to store your .frm and .idb files. This will resolve the overload problem." }, { "code": null, "e": 26833, "s": 26396, "text": "Que-5: Explain what‘auto increment’ is?Explanation:This command allows you to generate a unique number when a new record is written to a table. When you want to the primary key field value to be generated automatically each time you insert a new record, this is when this function comes in handy.Another thing worth noting is that the command can be used on various platforms. For SQL Servers the “auto increment” command is “identity”." }, { "code": null, "e": 26974, "s": 26833, "text": "Another thing worth noting is that the command can be used on various platforms. For SQL Servers the “auto increment” command is “identity”." }, { "code": null, "e": 27133, "s": 26974, "text": "Que-6: What are the most basic MySQL architecture components ?Explanation:There are three main components:Query optimizer;Connection manager;Pluggable engine." }, { "code": null, "e": 27186, "s": 27133, "text": "Query optimizer;Connection manager;Pluggable engine." }, { "code": null, "e": 27203, "s": 27186, "text": "Query optimizer;" }, { "code": null, "e": 27223, "s": 27203, "text": "Connection manager;" }, { "code": null, "e": 27241, "s": 27223, "text": "Pluggable engine." }, { "code": null, "e": 27355, "s": 27241, "text": "Que-7: Using an existing table, make an empty one.Explanation:Select * into employeecopy from employee where 1=2 " }, { "code": null, "e": 27407, "s": 27355, "text": "Select * into employeecopy from employee where 1=2 " }, { "code": null, "e": 27554, "s": 27407, "text": "Que-8: How would you check your current SQL version ?Explanation:You can get the most current SQL version by issuing this command:SELECT VERSION()" }, { "code": null, "e": 27571, "s": 27554, "text": "SELECT VERSION()" }, { "code": null, "e": 27760, "s": 27571, "text": "Que-9: Get alternative odd records from the table.Explanation:This can be achieved using the command:Select employeeId from (Select rowno, employeetId from employee) where mod(rowno, 2)=1 " }, { "code": null, "e": 27848, "s": 27760, "text": "Select employeeId from (Select rowno, employeetId from employee) where mod(rowno, 2)=1 " }, { "code": null, "e": 28010, "s": 27848, "text": "Que-10: What command would select a unique record from the table ?Explanation:The “distinct” command. Here’s an example:Select DISTINCT employeeID from Employee " }, { "code": null, "e": 28052, "s": 28010, "text": "Select DISTINCT employeeID from Employee " }, { "code": null, "e": 28304, "s": 28052, "text": "Que-11: What are variables of SQL ?Explanation:In SQL, there are two different variables:Local – these variables can only exist in one single functionGlobal – are the opposite of local, which means they can be located through ought the entire program." }, { "code": null, "e": 28366, "s": 28304, "text": "Local – these variables can only exist in one single function" }, { "code": null, "e": 28468, "s": 28366, "text": "Global – are the opposite of local, which means they can be located through ought the entire program." }, { "code": null, "e": 28779, "s": 28468, "text": "Que-12: What is a ‘datawarehouse’ and what it does ?Explanation:A “datawarehouse” is a system used for data analysis and reporting. Basically, it’s a warehouse of data. Data in DWs can be stored from various areas and sources and thus makes them central repositories of integrated data that is ready for usage." }, { "code": null, "e": 29082, "s": 28779, "text": "Que-13: For what ‘recursive stored procedure’ is mainly used ?Explanation:A recursive stored procedure is a procedure that will make the code calls itself until specific boundary condition is reached. This is a productivity type of thing, that allows programmers to use the same code a number of times." }, { "code": null, "e": 29355, "s": 29082, "text": "Que-14: Retrieve the first 3 characters from a character string.Explanation:There are a few ways to do this. Nevertheless, the command presented below can be treated as a more popular and easier one:Select SUBSTRING(EmployeeSurname, 1, 5) as employeesurname from employee " }, { "code": null, "e": 29429, "s": 29355, "text": "Select SUBSTRING(EmployeeSurname, 1, 5) as employeesurname from employee " }, { "code": null, "e": 29610, "s": 29429, "text": "Que-15: How would you retrieve common records from two tables ?Explanation:By performing the task below:Select employeeID from employee. INTERSECT Select EmployeeID from WorkShift " }, { "code": null, "e": 29687, "s": 29610, "text": "Select employeeID from employee. INTERSECT Select EmployeeID from WorkShift " }, { "code": null, "e": 29702, "s": 29687, "text": "Interview Tips" }, { "code": null, "e": 29724, "s": 29702, "text": "interview-preparation" }, { "code": null, "e": 29746, "s": 29724, "text": "placement preparation" }, { "code": null, "e": 29751, "s": 29746, "text": "DBMS" }, { "code": null, "e": 29755, "s": 29751, "text": "SQL" }, { "code": null, "e": 29760, "s": 29755, "text": "DBMS" }, { "code": null, "e": 29764, "s": 29760, "text": "SQL" }, { "code": null, "e": 29862, "s": 29764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29871, "s": 29862, "text": "Comments" }, { "code": null, "e": 29884, "s": 29871, "text": "Old Comments" }, { "code": null, "e": 29915, "s": 29884, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 29938, "s": 29915, "text": "Introduction of B-Tree" }, { "code": null, "e": 29991, "s": 29938, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 30049, "s": 29991, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 30074, "s": 30049, "text": "Introduction of ER Model" }, { "code": null, "e": 30116, "s": 30074, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 30160, "s": 30116, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 30181, "s": 30160, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 30212, "s": 30181, "text": "SQL Trigger | Student Database" } ]
Node.js assert.deepStrictEqual() Function - GeeksforGeeks
07 Aug, 2020 The assert module provides a set of assertion functions for verifying invariants. The assert.deepStrictEqual() function tests for deep equality between the actual and expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.deepStrictEqual(actual, expected[, message]) Parameters: This function accepts the following parameters as mentioned above and described below: actual: This parameter holds the actual value that need to be evaluated. It is of any type. expected: This parameter holds the expected value which is matched against actual value. It is of any type. message: This parameter holds the error message of string or error type. It is an optional parameter. Return Value: This function returns assertion error of object type. Installation of assert module: You can visit the link to Install assert module. You can install this package by using this command. npm install assertNote: Installation is an optional step as it is inbuilt Node.js module. After installing the assert module, you can check your assert version in command prompt using the command. npm version assertAfter that, you can just create a folder and add a file for example, index.js as shown below.Example 1: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' });} catch(error) { console.log("Error: ", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\Users\Lenovo\Downloads\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}Example 2: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' }); console.log("No Error Occured")} catch(error) { console.log("Error: ", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: No Error OccuredReference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_deepstrictequal_actual_expected_message My Personal Notes arrow_drop_upSave You can visit the link to Install assert module. You can install this package by using this command. npm install assert npm install assert Note: Installation is an optional step as it is inbuilt Node.js module. After installing the assert module, you can check your assert version in command prompt using the command. npm version assert npm version assert After that, you can just create a folder and add a file for example, index.js as shown below.Example 1: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' });} catch(error) { console.log("Error: ", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\Users\Lenovo\Downloads\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}Example 2: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' }); console.log("No Error Occured")} catch(error) { console.log("Error: ", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: No Error OccuredReference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_deepstrictequal_actual_expected_message My Personal Notes arrow_drop_upSave Example 1: Filename: index.js javascript // Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' });} catch(error) { console.log("Error: ", error)} Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\Users\Lenovo\Downloads\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’} The project structure will look like this: Run index.js file using below command: node index.js node index.js Output: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\Users\Lenovo\Downloads\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’} Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\Users\Lenovo\Downloads\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’} Example 2: Filename: index.js javascript // Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' }); console.log("No Error Occured")} catch(error) { console.log("Error: ", error)} Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: No Error Occured The project structure will look like this: Run index.js file using below command: node index.js node index.js Output: No Error Occured No Error Occured Reference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_deepstrictequal_actual_expected_message Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 38501, "s": 38473, "text": "\n07 Aug, 2020" }, { "code": null, "e": 38780, "s": 38501, "text": "The assert module provides a set of assertion functions for verifying invariants. The assert.deepStrictEqual() function tests for deep equality between the actual and expected parameters. If the condition is true it will not produce an output else an assertion error is raised. " }, { "code": null, "e": 38789, "s": 38780, "text": "Syntax: " }, { "code": null, "e": 38841, "s": 38789, "text": "assert.deepStrictEqual(actual, expected[, message])" }, { "code": null, "e": 38941, "s": 38841, "text": "Parameters: This function accepts the following parameters as mentioned above and described below: " }, { "code": null, "e": 39033, "s": 38941, "text": "actual: This parameter holds the actual value that need to be evaluated. It is of any type." }, { "code": null, "e": 39141, "s": 39033, "text": "expected: This parameter holds the expected value which is matched against actual value. It is of any type." }, { "code": null, "e": 39243, "s": 39141, "text": "message: This parameter holds the error message of string or error type. It is an optional parameter." }, { "code": null, "e": 39312, "s": 39243, "text": "Return Value: This function returns assertion error of object type. " }, { "code": null, "e": 39344, "s": 39312, "text": "Installation of assert module: " }, { "code": null, "e": 41400, "s": 39344, "text": "You can visit the link to Install assert module. You can install this package by using this command. npm install assertNote: Installation is an optional step as it is inbuilt Node.js module. After installing the assert module, you can check your assert version in command prompt using the command. npm version assertAfter that, you can just create a folder and add a file for example, index.js as shown below.Example 1: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' });} catch(error) { console.log(\"Error: \", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\\Users\\Lenovo\\Downloads\\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}Example 2: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' }); console.log(\"No Error Occured\")} catch(error) { console.log(\"Error: \", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: No Error OccuredReference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_deepstrictequal_actual_expected_message My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 41520, "s": 41400, "text": "You can visit the link to Install assert module. You can install this package by using this command. npm install assert" }, { "code": null, "e": 41539, "s": 41520, "text": "npm install assert" }, { "code": null, "e": 41612, "s": 41539, "text": "Note: Installation is an optional step as it is inbuilt Node.js module. " }, { "code": null, "e": 41738, "s": 41612, "text": "After installing the assert module, you can check your assert version in command prompt using the command. npm version assert" }, { "code": null, "e": 41757, "s": 41738, "text": "npm version assert" }, { "code": null, "e": 43497, "s": 41757, "text": "After that, you can just create a folder and add a file for example, index.js as shown below.Example 1: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' });} catch(error) { console.log(\"Error: \", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\\Users\\Lenovo\\Downloads\\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}Example 2: Filename: index.js javascriptjavascript// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' }); console.log(\"No Error Occured\")} catch(error) { console.log(\"Error: \", error)}Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.jsOutput: No Error OccuredReference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_deepstrictequal_actual_expected_message My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 43529, "s": 43497, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 43540, "s": 43529, "text": "javascript" }, { "code": "// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' });} catch(error) { console.log(\"Error: \", error)}", "e": 43731, "s": 43540, "text": null }, { "code": null, "e": 43759, "s": 43731, "text": "Steps to run the program: " }, { "code": null, "e": 44553, "s": 43759, "text": "The project structure will look like this: Run index.js file using below command: node index.jsOutput: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\\Users\\Lenovo\\Downloads\\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}" }, { "code": null, "e": 44598, "s": 44553, "text": "The project structure will look like this: " }, { "code": null, "e": 44652, "s": 44598, "text": "Run index.js file using below command: node index.js" }, { "code": null, "e": 44666, "s": 44652, "text": "node index.js" }, { "code": null, "e": 45363, "s": 44666, "text": "Output: Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected {+ a: 1– a: ‘1’ } at Object. (C:\\Users\\Lenovo\\Downloads\\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}" }, { "code": null, "e": 45465, "s": 45363, "text": "Error: AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual – expected" }, { "code": null, "e": 46052, "s": 45465, "text": " {+ a: 1– a: ‘1’ } at Object. (C:\\Users\\Lenovo\\Downloads\\index.js:14:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: [Object], expected: [Object], operator: ‘deepStrictEqual’}" }, { "code": null, "e": 46084, "s": 46052, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 46095, "s": 46084, "text": "javascript" }, { "code": "// Requiring the moduleconst assert = require('assert').strict; // Function calltry { assert.deepStrictEqual({ a: '5' }, { a: '5' }); console.log(\"No Error Occured\")} catch(error) { console.log(\"Error: \", error)}", "e": 46323, "s": 46095, "text": null }, { "code": null, "e": 46351, "s": 46323, "text": "Steps to run the program: " }, { "code": null, "e": 46474, "s": 46351, "text": "The project structure will look like this: Run index.js file using below command: node index.jsOutput: No Error Occured" }, { "code": null, "e": 46519, "s": 46474, "text": "The project structure will look like this: " }, { "code": null, "e": 46573, "s": 46519, "text": "Run index.js file using below command: node index.js" }, { "code": null, "e": 46587, "s": 46573, "text": "node index.js" }, { "code": null, "e": 46613, "s": 46587, "text": "Output: No Error Occured" }, { "code": null, "e": 46630, "s": 46613, "text": "No Error Occured" }, { "code": null, "e": 46754, "s": 46630, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_deepstrictequal_actual_expected_message " }, { "code": null, "e": 46770, "s": 46754, "text": "Node.js-Methods" }, { "code": null, "e": 46778, "s": 46770, "text": "Node.js" }, { "code": null, "e": 46795, "s": 46778, "text": "Web Technologies" }, { "code": null, "e": 46893, "s": 46795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46941, "s": 46893, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 46974, "s": 46941, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 47004, "s": 46974, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 47024, "s": 47004, "text": "How to update NPM ?" }, { "code": null, "e": 47078, "s": 47024, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 47118, "s": 47078, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47163, "s": 47118, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47206, "s": 47163, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 47256, "s": 47206, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Fractional Knapsack Problem - GeeksforGeeks
25 Apr, 2022 Given the weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In the 0-1 Knapsack problem, we are not allowed to break items. We either take the whole item or don’t take it. Input: Items as (value, weight) pairs arr[] = {{60, 10}, {100, 20}, {120, 30}} Knapsack Capacity, W = 50; Output: Maximum possible value = 240 by taking items of weight 10 and 20 kg and 2/3 fraction of 30 kg. Hence total price will be 60+100+(2/3)(120) = 240 In Fractional Knapsack, we can break items for maximizing the total value of knapsack. This problem in which we can break an item is also called the fractional knapsack problem. Input : Same as above Output : Maximum possible value = 240 By taking full items of 10 kg, 20 kg and 2/3rd of last item of 30 kg A brute-force solution would be to try all possible subset with all different fraction but that will be too much time taking. An efficient solution is to use the Greedy approach. The basic idea of the greedy approach is to calculate the ratio value/weight for each item and sort the item on basis of this ratio. Then take the item with the highest ratio and add them until we can’t add the next item as a whole and at the end add the next item as much as we can. Which will always be the optimal solution to this problem.A simple code with our own comparison function can be written as follows, please see the sort function more closely, the third argument to sort function is our comparison function which sorts the item according to value/weight ratio in non-decreasing order. After sorting we need to loop over these items and add them in our knapsack satisfying above-mentioned criteria. Below is the implementation of the above idea: C++ Java Python3 C# // C/C++ program to solve fractional Knapsack Problem#include <bits/stdc++.h> using namespace std; // Structure for an item which stores weight and// corresponding value of Itemstruct Item { int value, weight; // Constructor Item(int value, int weight) { this->value = value; this->weight = weight; }}; // Comparison function to sort Item according to val/weight// ratiobool cmp(struct Item a, struct Item b){ double r1 = (double)a.value / (double)a.weight; double r2 = (double)b.value / (double)b.weight; return r1 > r2;} // Main greedy function to solve problemdouble fractionalKnapsack(int W, struct Item arr[], int n){ // sorting Item on basis of ratio sort(arr, arr + n, cmp); // Uncomment to see new order of Items with their // ratio /* for (int i = 0; i < n; i++) { cout << arr[i].value << " " << arr[i].weight << " : " << ((double)arr[i].value / arr[i].weight) << endl; } */ double finalvalue = 0.0; // Result (value in Knapsack) // Looping through all Items for (int i = 0; i < n; i++) { // If adding Item won't overflow, add it completely if (arr[i].weight <= W) { W -= arr[i].weight; finalvalue += arr[i].value; } // If we can't add current Item, add fractional part // of it else { finalvalue += arr[i].value * ((double)W / (double)arr[i].weight); break; } } // Returning final value return finalvalue;} // Driver codeint main(){ int W = 50; // Weight of knapsack Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Maximum value we can obtain = " << fractionalKnapsack(W, arr, n); return 0;} // Java program to solve fractional Knapsack Problemimport java.util.Arrays;import java.util.Comparator; // Greedy approachpublic class FractionalKnapSack { // function to get maximum value private static double getMaxValue(int[] wt, int[] val, int capacity) { ItemValue[] iVal = new ItemValue[wt.length]; for (int i = 0; i < wt.length; i++) { iVal[i] = new ItemValue(wt[i], val[i], i); } // sorting items by value; Arrays.sort(iVal, new Comparator<ItemValue>() { @Override public int compare(ItemValue o1, ItemValue o2) { return o2.cost.compareTo(o1.cost); } }); double totalValue = 0d; for (ItemValue i : iVal) { int curWt = (int)i.wt; int curVal = (int)i.val; if (capacity - curWt >= 0) { // this weight can be picked while capacity = capacity - curWt; totalValue += curVal; } else { // item cant be picked whole double fraction = ((double)capacity / (double)curWt); totalValue += (curVal * fraction); capacity = (int)(capacity - (curWt * fraction)); break; } } return totalValue; } // item value class static class ItemValue { Double cost; double wt, val, ind; // item value function public ItemValue(int wt, int val, int ind) { this.wt = wt; this.val = val; this.ind = ind; cost = new Double((double)val / (double)wt); } } // Driver code public static void main(String[] args) { int[] wt = { 10, 40, 20, 30 }; int[] val = { 60, 40, 100, 120 }; int capacity = 50; double maxValue = getMaxValue(wt, val, capacity); // Function call System.out.println("Maximum value we can obtain = " + maxValue); }} # Python3 program to solve fractional# Knapsack Problem class ItemValue: """Item Value DataClass""" def __init__(self, wt, val, ind): self.wt = wt self.val = val self.ind = ind self.cost = val // wt def __lt__(self, other): return self.cost < other.cost # Greedy Approach class FractionalKnapSack: """Time Complexity O(n log n)""" @staticmethod def getMaxValue(wt, val, capacity): """function to get maximum value """ iVal = [] for i in range(len(wt)): iVal.append(ItemValue(wt[i], val[i], i)) # sorting items by value iVal.sort(reverse=True) totalValue = 0 for i in iVal: curWt = int(i.wt) curVal = int(i.val) if capacity - curWt >= 0: capacity -= curWt totalValue += curVal else: fraction = capacity / curWt totalValue += curVal * fraction capacity = int(capacity - (curWt * fraction)) break return totalValue # Driver Codeif __name__ == "__main__": wt = [10, 40, 20, 30] val = [60, 40, 100, 120] capacity = 50 # Function call maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity) print("Maximum value in Knapsack =", maxValue) # This code is contributed by vibhu4agarwal // C# program to solve fractional Knapsack Problemusing System;using System.Collections; class GFG { // Class for an item which stores weight and // corresponding value of Item class item { public int value; public int weight; public item(int value, int weight) { this.value = value; this.weight = weight; } } // Comparison function to sort Item according // to val/weight ratio class cprCompare : IComparer { public int Compare(Object x, Object y) { item item1 = (item)x; item item2 = (item)y; double cpr1 = (double)item1.value / (double)item1.weight; double cpr2 = (double)item2.value / (double)item2.weight; if (cpr1 < cpr2) return 1; return cpr1 > cpr2 ? -1 : 0; } } // Main greedy function to solve problem static double FracKnapSack(item[] items, int w) { // Sort items based on cost per units cprCompare cmp = new cprCompare(); Array.Sort(items, cmp); // Traverse items, if it can fit, // take it all, else take fraction double totalVal = 0f; int currW = 0; foreach(item i in items) { float remaining = w - currW; // If the whole item can be // taken, take it if (i.weight <= remaining) { totalVal += (double)i.value; currW += i.weight; } // dd fraction until we run out of space else { if (remaining == 0) break; double fraction = remaining / (double)i.weight; totalVal += fraction * (double)i.value; currW += (int)(fraction * (double)i.weight); } } return totalVal; } // Driver code static void Main(string[] args) { item[] arr = { new item(60, 10), new item(100, 20), new item(120, 30) }; Console.WriteLine("Maximum value we can obtain = " + FracKnapSack(arr, 50)); }} // This code is contributed by Mohamed Adel Maximum value we can obtain = 240 As main time taking step is sorting, the whole problem can be solved in O(n log n) only. This article is contributed by Utkarsh Trivedi. YouTubeGeeksforGeeks507K subscribersFractional Knapsack Problem | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=m1p-eWxrt6g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Prashant Mishra 9 vibhu4agarwal jigyansu salonikyal firoz_baba mahmd3adel adnanirshad158 rajatsingh0805 Fraction knapsack Greedy Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Activity Selection Problem | Greedy Algo-1 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Job Sequencing Problem Difference between Prim's and Kruskal's algorithm for MST Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Program for Least Recently Used (LRU) Page Replacement algorithm Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm Graph Coloring | Set 2 (Greedy Algorithm) Program for Page Replacement Algorithms | Set 2 (FIFO)
[ { "code": null, "e": 26065, "s": 26037, "text": "\n25 Apr, 2022" }, { "code": null, "e": 26209, "s": 26065, "text": "Given the weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack." }, { "code": null, "e": 26322, "s": 26209, "text": "In the 0-1 Knapsack problem, we are not allowed to break items. We either take the whole item or don’t take it. " }, { "code": null, "e": 26429, "s": 26322, "text": "Input: Items as (value, weight) pairs arr[] = {{60, 10}, {100, 20}, {120, 30}} Knapsack Capacity, W = 50; " }, { "code": null, "e": 26582, "s": 26429, "text": "Output: Maximum possible value = 240 by taking items of weight 10 and 20 kg and 2/3 fraction of 30 kg. Hence total price will be 60+100+(2/3)(120) = 240" }, { "code": null, "e": 26761, "s": 26582, "text": "In Fractional Knapsack, we can break items for maximizing the total value of knapsack. This problem in which we can break an item is also called the fractional knapsack problem. " }, { "code": null, "e": 26893, "s": 26761, "text": "Input : \nSame as above\n\nOutput :\nMaximum possible value = 240\nBy taking full items of 10 kg, 20 kg and \n2/3rd of last item of 30 kg" }, { "code": null, "e": 27020, "s": 26893, "text": "A brute-force solution would be to try all possible subset with all different fraction but that will be too much time taking. " }, { "code": null, "e": 27786, "s": 27020, "text": "An efficient solution is to use the Greedy approach. The basic idea of the greedy approach is to calculate the ratio value/weight for each item and sort the item on basis of this ratio. Then take the item with the highest ratio and add them until we can’t add the next item as a whole and at the end add the next item as much as we can. Which will always be the optimal solution to this problem.A simple code with our own comparison function can be written as follows, please see the sort function more closely, the third argument to sort function is our comparison function which sorts the item according to value/weight ratio in non-decreasing order. After sorting we need to loop over these items and add them in our knapsack satisfying above-mentioned criteria." }, { "code": null, "e": 27833, "s": 27786, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 27837, "s": 27833, "text": "C++" }, { "code": null, "e": 27842, "s": 27837, "text": "Java" }, { "code": null, "e": 27850, "s": 27842, "text": "Python3" }, { "code": null, "e": 27853, "s": 27850, "text": "C#" }, { "code": "// C/C++ program to solve fractional Knapsack Problem#include <bits/stdc++.h> using namespace std; // Structure for an item which stores weight and// corresponding value of Itemstruct Item { int value, weight; // Constructor Item(int value, int weight) { this->value = value; this->weight = weight; }}; // Comparison function to sort Item according to val/weight// ratiobool cmp(struct Item a, struct Item b){ double r1 = (double)a.value / (double)a.weight; double r2 = (double)b.value / (double)b.weight; return r1 > r2;} // Main greedy function to solve problemdouble fractionalKnapsack(int W, struct Item arr[], int n){ // sorting Item on basis of ratio sort(arr, arr + n, cmp); // Uncomment to see new order of Items with their // ratio /* for (int i = 0; i < n; i++) { cout << arr[i].value << \" \" << arr[i].weight << \" : \" << ((double)arr[i].value / arr[i].weight) << endl; } */ double finalvalue = 0.0; // Result (value in Knapsack) // Looping through all Items for (int i = 0; i < n; i++) { // If adding Item won't overflow, add it completely if (arr[i].weight <= W) { W -= arr[i].weight; finalvalue += arr[i].value; } // If we can't add current Item, add fractional part // of it else { finalvalue += arr[i].value * ((double)W / (double)arr[i].weight); break; } } // Returning final value return finalvalue;} // Driver codeint main(){ int W = 50; // Weight of knapsack Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << \"Maximum value we can obtain = \" << fractionalKnapsack(W, arr, n); return 0;}", "e": 29727, "s": 27853, "text": null }, { "code": "// Java program to solve fractional Knapsack Problemimport java.util.Arrays;import java.util.Comparator; // Greedy approachpublic class FractionalKnapSack { // function to get maximum value private static double getMaxValue(int[] wt, int[] val, int capacity) { ItemValue[] iVal = new ItemValue[wt.length]; for (int i = 0; i < wt.length; i++) { iVal[i] = new ItemValue(wt[i], val[i], i); } // sorting items by value; Arrays.sort(iVal, new Comparator<ItemValue>() { @Override public int compare(ItemValue o1, ItemValue o2) { return o2.cost.compareTo(o1.cost); } }); double totalValue = 0d; for (ItemValue i : iVal) { int curWt = (int)i.wt; int curVal = (int)i.val; if (capacity - curWt >= 0) { // this weight can be picked while capacity = capacity - curWt; totalValue += curVal; } else { // item cant be picked whole double fraction = ((double)capacity / (double)curWt); totalValue += (curVal * fraction); capacity = (int)(capacity - (curWt * fraction)); break; } } return totalValue; } // item value class static class ItemValue { Double cost; double wt, val, ind; // item value function public ItemValue(int wt, int val, int ind) { this.wt = wt; this.val = val; this.ind = ind; cost = new Double((double)val / (double)wt); } } // Driver code public static void main(String[] args) { int[] wt = { 10, 40, 20, 30 }; int[] val = { 60, 40, 100, 120 }; int capacity = 50; double maxValue = getMaxValue(wt, val, capacity); // Function call System.out.println(\"Maximum value we can obtain = \" + maxValue); }}", "e": 31830, "s": 29727, "text": null }, { "code": "# Python3 program to solve fractional# Knapsack Problem class ItemValue: \"\"\"Item Value DataClass\"\"\" def __init__(self, wt, val, ind): self.wt = wt self.val = val self.ind = ind self.cost = val // wt def __lt__(self, other): return self.cost < other.cost # Greedy Approach class FractionalKnapSack: \"\"\"Time Complexity O(n log n)\"\"\" @staticmethod def getMaxValue(wt, val, capacity): \"\"\"function to get maximum value \"\"\" iVal = [] for i in range(len(wt)): iVal.append(ItemValue(wt[i], val[i], i)) # sorting items by value iVal.sort(reverse=True) totalValue = 0 for i in iVal: curWt = int(i.wt) curVal = int(i.val) if capacity - curWt >= 0: capacity -= curWt totalValue += curVal else: fraction = capacity / curWt totalValue += curVal * fraction capacity = int(capacity - (curWt * fraction)) break return totalValue # Driver Codeif __name__ == \"__main__\": wt = [10, 40, 20, 30] val = [60, 40, 100, 120] capacity = 50 # Function call maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity) print(\"Maximum value in Knapsack =\", maxValue) # This code is contributed by vibhu4agarwal", "e": 33193, "s": 31830, "text": null }, { "code": "// C# program to solve fractional Knapsack Problemusing System;using System.Collections; class GFG { // Class for an item which stores weight and // corresponding value of Item class item { public int value; public int weight; public item(int value, int weight) { this.value = value; this.weight = weight; } } // Comparison function to sort Item according // to val/weight ratio class cprCompare : IComparer { public int Compare(Object x, Object y) { item item1 = (item)x; item item2 = (item)y; double cpr1 = (double)item1.value / (double)item1.weight; double cpr2 = (double)item2.value / (double)item2.weight; if (cpr1 < cpr2) return 1; return cpr1 > cpr2 ? -1 : 0; } } // Main greedy function to solve problem static double FracKnapSack(item[] items, int w) { // Sort items based on cost per units cprCompare cmp = new cprCompare(); Array.Sort(items, cmp); // Traverse items, if it can fit, // take it all, else take fraction double totalVal = 0f; int currW = 0; foreach(item i in items) { float remaining = w - currW; // If the whole item can be // taken, take it if (i.weight <= remaining) { totalVal += (double)i.value; currW += i.weight; } // dd fraction until we run out of space else { if (remaining == 0) break; double fraction = remaining / (double)i.weight; totalVal += fraction * (double)i.value; currW += (int)(fraction * (double)i.weight); } } return totalVal; } // Driver code static void Main(string[] args) { item[] arr = { new item(60, 10), new item(100, 20), new item(120, 30) }; Console.WriteLine(\"Maximum value we can obtain = \" + FracKnapSack(arr, 50)); }} // This code is contributed by Mohamed Adel", "e": 35441, "s": 33193, "text": null }, { "code": null, "e": 35475, "s": 35441, "text": "Maximum value we can obtain = 240" }, { "code": null, "e": 35612, "s": 35475, "text": "As main time taking step is sorting, the whole problem can be solved in O(n log n) only. This article is contributed by Utkarsh Trivedi." }, { "code": null, "e": 36438, "s": 35612, "text": "YouTubeGeeksforGeeks507K subscribersFractional Knapsack Problem | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=m1p-eWxrt6g\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36564, "s": 36438, "text": " Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36582, "s": 36564, "text": "Prashant Mishra 9" }, { "code": null, "e": 36596, "s": 36582, "text": "vibhu4agarwal" }, { "code": null, "e": 36605, "s": 36596, "text": "jigyansu" }, { "code": null, "e": 36616, "s": 36605, "text": "salonikyal" }, { "code": null, "e": 36627, "s": 36616, "text": "firoz_baba" }, { "code": null, "e": 36638, "s": 36627, "text": "mahmd3adel" }, { "code": null, "e": 36653, "s": 36638, "text": "adnanirshad158" }, { "code": null, "e": 36668, "s": 36653, "text": "rajatsingh0805" }, { "code": null, "e": 36677, "s": 36668, "text": "Fraction" }, { "code": null, "e": 36686, "s": 36677, "text": "knapsack" }, { "code": null, "e": 36693, "s": 36686, "text": "Greedy" }, { "code": null, "e": 36700, "s": 36693, "text": "Greedy" }, { "code": null, "e": 36798, "s": 36700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36829, "s": 36798, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 36872, "s": 36829, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 36953, "s": 36872, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 36976, "s": 36953, "text": "Job Sequencing Problem" }, { "code": null, "e": 37034, "s": 36976, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 37105, "s": 37034, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 37170, "s": 37105, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" }, { "code": null, "e": 37238, "s": 37170, "text": "Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm" }, { "code": null, "e": 37280, "s": 37238, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" } ]
How to move an array element from one array position to another in JavaScript? - GeeksforGeeks
23 Mar, 2022 In JavaScript we can access an array element as other programming languages like C, C++, Java etc. Also there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another we can splice() method or we can simply use array indexing ([]). Example : Simple code for moving an array element from one array position to another, without using any functions. javascript <script> var arr = ["C++", "Java", "JS", "Python"]; document.write("Original array: "+arr+"<br>"); // Position where from the element is // going to move here 'python' is moved var x = 3; // Position at which element is to be // moved here 'python' is moved to // index 1 which is index of 'Java' var pos = 1; // Store the moved element in a temp // variable var temp = arr[x]; // shift elements forward var i; for (i = x; i >= pos; i--) { arr[i] = arr[i - 1]; } // Insert moved element at position arr[pos] = temp; document.write("<br>After move: "+arr+"<br>"); </script> Output : Original array: C++,Java,JS,Python After move: C++,Python,Java,JS Example : Now move an array element from one array position to another using functions, javascript <script> var arr = ["C++ ", "Java ", "JS ", "Ruby ", "Python "]; // Print the array before moving document.write("Original array: "+arr+"<br>"); // Position where from the element is // going to move here 'Ruby' is moved var moveEle = 3; // Position at which element is to be moved // here 'Ruby' is moved to index 1 which is // index of 'Java' var moveToIndx = 1; // If actual index of moved element is // less than 0 when 'moveEle += array size' while (moveEle < 0) { moveEle += arr.length; } // Where the element to be moved f that // index is less than 0 when // 'moveToIndx += array size' while (moveToIndx < 0) { moveToIndx = moveToIndx + arr.length; } // If 'moveToIndx' is greater than the // size of the array then with need to // push 'undefined' in the array. if (moveToIndx >= arr.length) { var un = moveToIndx - arr.length + 1; while (un--) { arr.push(undefined); } } // Here element of 'moveEle' is removed and // pushed at 'moveToIndx' index arr.splice(moveToIndx, 0, arr.splice(moveEle, 1)); // Print the array after moving document.write("<br>After move: "+arr+"<br>");</script> Output : Original array: C++ ,Java ,JS ,Ruby ,Python After move: C++ ,Ruby ,Java ,JS ,Python simmytarika5 javascript-array Picked JavaScript Web Technologies Web technologies Questions 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 ? 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 Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25897, "s": 25869, "text": "\n23 Mar, 2022" }, { "code": null, "e": 26258, "s": 25897, "text": "In JavaScript we can access an array element as other programming languages like C, C++, Java etc. Also there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another we can splice() method or we can simply use array indexing ([]). " }, { "code": null, "e": 26374, "s": 26258, "text": "Example : Simple code for moving an array element from one array position to another, without using any functions. " }, { "code": null, "e": 26385, "s": 26374, "text": "javascript" }, { "code": "<script> var arr = [\"C++\", \"Java\", \"JS\", \"Python\"]; document.write(\"Original array: \"+arr+\"<br>\"); // Position where from the element is // going to move here 'python' is moved var x = 3; // Position at which element is to be // moved here 'python' is moved to // index 1 which is index of 'Java' var pos = 1; // Store the moved element in a temp // variable var temp = arr[x]; // shift elements forward var i; for (i = x; i >= pos; i--) { arr[i] = arr[i - 1]; } // Insert moved element at position arr[pos] = temp; document.write(\"<br>After move: \"+arr+\"<br>\"); </script>", "e": 27047, "s": 26385, "text": null }, { "code": null, "e": 27057, "s": 27047, "text": "Output : " }, { "code": null, "e": 27124, "s": 27057, "text": "Original array: C++,Java,JS,Python\n\nAfter move: C++,Python,Java,JS" }, { "code": null, "e": 27213, "s": 27124, "text": "Example : Now move an array element from one array position to another using functions, " }, { "code": null, "e": 27224, "s": 27213, "text": "javascript" }, { "code": "<script> var arr = [\"C++ \", \"Java \", \"JS \", \"Ruby \", \"Python \"]; // Print the array before moving document.write(\"Original array: \"+arr+\"<br>\"); // Position where from the element is // going to move here 'Ruby' is moved var moveEle = 3; // Position at which element is to be moved // here 'Ruby' is moved to index 1 which is // index of 'Java' var moveToIndx = 1; // If actual index of moved element is // less than 0 when 'moveEle += array size' while (moveEle < 0) { moveEle += arr.length; } // Where the element to be moved f that // index is less than 0 when // 'moveToIndx += array size' while (moveToIndx < 0) { moveToIndx = moveToIndx + arr.length; } // If 'moveToIndx' is greater than the // size of the array then with need to // push 'undefined' in the array. if (moveToIndx >= arr.length) { var un = moveToIndx - arr.length + 1; while (un--) { arr.push(undefined); } } // Here element of 'moveEle' is removed and // pushed at 'moveToIndx' index arr.splice(moveToIndx, 0, arr.splice(moveEle, 1)); // Print the array after moving document.write(\"<br>After move: \"+arr+\"<br>\");</script>", "e": 28505, "s": 27224, "text": null }, { "code": null, "e": 28514, "s": 28505, "text": "Output :" }, { "code": null, "e": 28599, "s": 28514, "text": "Original array: C++ ,Java ,JS ,Ruby ,Python\n\nAfter move: C++ ,Ruby ,Java ,JS ,Python" }, { "code": null, "e": 28612, "s": 28599, "text": "simmytarika5" }, { "code": null, "e": 28629, "s": 28612, "text": "javascript-array" }, { "code": null, "e": 28636, "s": 28629, "text": "Picked" }, { "code": null, "e": 28647, "s": 28636, "text": "JavaScript" }, { "code": null, "e": 28664, "s": 28647, "text": "Web Technologies" }, { "code": null, "e": 28691, "s": 28664, "text": "Web technologies Questions" }, { "code": null, "e": 28789, "s": 28691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28834, "s": 28789, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28895, "s": 28834, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28967, "s": 28895, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29019, "s": 28967, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29065, "s": 29019, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29098, "s": 29065, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29143, "s": 29098, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29186, "s": 29143, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29248, "s": 29186, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Joining of Dataframes in R Programming - GeeksforGeeks
28 Jul, 2020 In R Language, dataframes are generic data objects which are used to store the tabular data. Dataframes are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Dataframes can also be taught as mattresses where each column of a matrix can be of the different data types. Dataframe is made up of three principal components, the data, rows, and columns. In R we use merge() function to merge two dataframes in R. This function is present inside join() function of dplyr package. The most important condition for joining two dataframes is that the column type should be the same on which the merging happens. merge() function works similarly like join in DBMS. Types of Merging Available in R are, Natural Join or Inner JoinLeft Outer JoinRight Outer JoinFull Outer JoinCross JoinSemi JoinAnti Join Natural Join or Inner Join Left Outer Join Right Outer Join Full Outer Join Cross Join Semi Join Anti Join Basic Syntax of merge() function in R: Syntax:merge(df1, df2, by.df1, by.df2, all.df1, all.df2, sort = TRUE) Parameters:df1: one dataframedf2: another dataframeby.df1, by.df2: The names of the columns that are common to both df1 and df2.all, all.df1, all.df2: Logical values that actually specify the type of merging happens. Now let’s try to understand all types of merging one by one. First of all, we will create two dataframes that will help us to understand each join easily.# Data frame 1 df1 = data.frame(StudentId = c(101:106), Product = c("Hindi", "English", "Maths", "Science", "Political Science", "Physics"))df1 Output: StudentId Product 1 101 Hindi 2 102 English 3 103 Maths 4 104 Science 5 105 Political Science 6 106 Physics # Data frame 2 df2 = data.frame(StudentId = c(102, 104, 106, 107, 108), State = c("Manglore", "Mysore", "Pune", "Dehradun", "Delhi")) df2 Output: StudentId State 1 102 Manglore 2 104 Mysore 3 106 Pune 4 107 Dehradun 5 108 Delhi Inner join is used to keep only those rows that are matched from the dataframes, in this, we actually specify the argument all = FALSE. If we try to understand this using set theory then we can say here we are actually performing the intersection operation. For example: A = [1, 2, 3, 4, 5] B = [2, 3, 5, 6] Then the output of natural join will be (2, 3, 5) It is the most simplest and common type of joins available in R. Now let us try to understand this using R program: Example: # R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = "StudentId")df Output: StudentId Product State 1 102 English Manglore 2 104 Science Mysore 3 106 Physics Pune Left Outer Join is basically to include all the rows of your dataframe x and only those from y that match, in this, we actually specify the argument x = TRUE. If we try to understand this using a basic set theory then we can say here we are actually displaying complete set x. Now let us try to understand this using R program:Example: # R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = "StudentId", all.x = TRUE)df Output: StudentId Product State 1 101 Hindi NA 2 102 English Manglore 3 103 Maths NA 4 104 Science Mysore 5 105 Political Science NA 6 106 Physics Pune Right, Outer Join is basically to include all the rows of your dataframe y and only those from x that match, in this, we actually specify the argument y = TRUE. If we try to understand this using a basic set theory then we can say here we are actually displaying a complete set y. Now let us try to understand this using R program:Example: # R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = "StudentId", all.y = TRUE)df Output: StudentId Product State 1 102 English Manglore 2 104 Science Mysore 3 106 Physics Pune 4 107 NA Dehradun 5 108 NA Delhi Outer Join is basically used to keep all rows from both dataframes, in this, we actually specify the arguments all = TRUE. If we try to understand this using a basic set theory then we can say here we are actually performing the union option. Now let us try to understand this using R program:Example: # R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = "StudentId", all = TRUE)df Output: StudentId Product State 1 101 Hindi NA 2 102 English Manglore 3 103 Maths NA 4 104 Science Mysore 5 105 Political Science NA 6 106 Physics Pune 7 107 NA Dehradun 8 108 NA Delhi A Cross Join also known as cartesian join results in every row of one dataframe is being joined to every other row of another dataframe. In set theory, this type of joins is known as the cartesian product between two sets. Now let us try to understand this using R program:Example: # R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = NULL)df Output: StudentId.x Product StudentId.y State 1 101 Hindi 102 Manglore 2 102 English 102 Manglore 3 103 Maths 102 Manglore 4 104 Science 102 Manglore 5 105 Political Science 102 Manglore 6 106 Physics 102 Manglore 7 101 Hindi 104 Mysore 8 102 English 104 Mysore 9 103 Maths 104 Mysore 10 104 Science 104 Mysore 11 105 Political Science 104 Mysore 12 106 Physics 104 Mysore 13 101 Hindi 106 Pune 14 102 English 106 Pune 15 103 Maths 106 Pune 16 104 Science 106 Pune 17 105 Political Science 106 Pune 18 106 Physics 106 Pune 19 101 Hindi 107 Dehradun 20 102 English 107 Dehradun 21 103 Maths 107 Dehradun 22 104 Science 107 Dehradun 23 105 Political Science 107 Dehradun 24 106 Physics 107 Dehradun 25 101 Hindi 108 Delhi 26 102 English 108 Delhi 27 103 Maths 108 Delhi 28 104 Science 108 Delhi 29 105 Political Science 108 Delhi 30 106 Physics 108 Delhi This join is somewhat like inner join, with only the left dataframe columns and values are selected. Now let us try to understand this using R program:Example: # R program to illustrate# Joining of dataframes # Import required librarylibrary(dplyr) df = df1 %>% semi_join(df2, by = "StudentId")df Output: StudentId Product 1 102 English 2 104 Science 3 106 Physics In terms of set theory, we can say anti-join as set difference operation, for example, A = (1, 2, 3, 4) B = (2, 3, 5) then the output of A-B will be set (1, 4). This join is somewhat like df1 – df2, as it basically selects all rows from df1 that are actually not present in df2. Now let us try to understand this using R program:Example: # R program to illustrate# Joining of dataframes # Import required librarylibrary(dplyr) df = df1 %>% anti_join(df2, by = "StudentId")df Output: StudentId Product 1 101 Hindi 2 103 Maths 3 105 Political Science Picked R-DataFrame 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 Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Printing Output of an R Program K-Means Clustering in R Programming
[ { "code": null, "e": 25980, "s": 25952, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26415, "s": 25980, "text": "In R Language, dataframes are generic data objects which are used to store the tabular data. Dataframes are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Dataframes can also be taught as mattresses where each column of a matrix can be of the different data types. Dataframe is made up of three principal components, the data, rows, and columns." }, { "code": null, "e": 26758, "s": 26415, "text": "In R we use merge() function to merge two dataframes in R. This function is present inside join() function of dplyr package. The most important condition for joining two dataframes is that the column type should be the same on which the merging happens. merge() function works similarly like join in DBMS. Types of Merging Available in R are," }, { "code": null, "e": 26859, "s": 26758, "text": "Natural Join or Inner JoinLeft Outer JoinRight Outer JoinFull Outer JoinCross JoinSemi JoinAnti Join" }, { "code": null, "e": 26886, "s": 26859, "text": "Natural Join or Inner Join" }, { "code": null, "e": 26902, "s": 26886, "text": "Left Outer Join" }, { "code": null, "e": 26919, "s": 26902, "text": "Right Outer Join" }, { "code": null, "e": 26935, "s": 26919, "text": "Full Outer Join" }, { "code": null, "e": 26946, "s": 26935, "text": "Cross Join" }, { "code": null, "e": 26956, "s": 26946, "text": "Semi Join" }, { "code": null, "e": 26966, "s": 26956, "text": "Anti Join" }, { "code": null, "e": 27005, "s": 26966, "text": "Basic Syntax of merge() function in R:" }, { "code": null, "e": 27075, "s": 27005, "text": "Syntax:merge(df1, df2, by.df1, by.df2, all.df1, all.df2, sort = TRUE)" }, { "code": null, "e": 27292, "s": 27075, "text": "Parameters:df1: one dataframedf2: another dataframeby.df1, by.df2: The names of the columns that are common to both df1 and df2.all, all.df1, all.df2: Logical values that actually specify the type of merging happens." }, { "code": null, "e": 27461, "s": 27292, "text": "Now let’s try to understand all types of merging one by one. First of all, we will create two dataframes that will help us to understand each join easily.# Data frame 1" }, { "code": "df1 = data.frame(StudentId = c(101:106), Product = c(\"Hindi\", \"English\", \"Maths\", \"Science\", \"Political Science\", \"Physics\"))df1 ", "e": 27695, "s": 27461, "text": null }, { "code": null, "e": 27703, "s": 27695, "text": "Output:" }, { "code": null, "e": 27915, "s": 27703, "text": " StudentId Product\n1 101 Hindi\n2 102 English\n3 103 Maths\n4 104 Science\n5 105 Political Science\n6 106 Physics\n" }, { "code": null, "e": 27930, "s": 27915, "text": "# Data frame 2" }, { "code": "df2 = data.frame(StudentId = c(102, 104, 106, 107, 108), State = c(\"Manglore\", \"Mysore\", \"Pune\", \"Dehradun\", \"Delhi\")) df2 ", "e": 28127, "s": 27930, "text": null }, { "code": null, "e": 28135, "s": 28127, "text": "Output:" }, { "code": null, "e": 28262, "s": 28135, "text": " StudentId State\n1 102 Manglore\n2 104 Mysore\n3 106 Pune\n4 107 Dehradun\n5 108 Delhi\n" }, { "code": null, "e": 28533, "s": 28262, "text": "Inner join is used to keep only those rows that are matched from the dataframes, in this, we actually specify the argument all = FALSE. If we try to understand this using set theory then we can say here we are actually performing the intersection operation. For example:" }, { "code": null, "e": 28621, "s": 28533, "text": "A = [1, 2, 3, 4, 5]\nB = [2, 3, 5, 6]\nThen the output of natural join will be (2, 3, 5)\n" }, { "code": null, "e": 28737, "s": 28621, "text": "It is the most simplest and common type of joins available in R. Now let us try to understand this using R program:" }, { "code": null, "e": 28746, "s": 28737, "text": "Example:" }, { "code": "# R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = \"StudentId\")df", "e": 28845, "s": 28746, "text": null }, { "code": null, "e": 28853, "s": 28845, "text": "Output:" }, { "code": null, "e": 28971, "s": 28853, "text": " StudentId Product State\n1 102 English Manglore\n2 104 Science Mysore\n3 106 Physics Pune\n" }, { "code": null, "e": 29307, "s": 28971, "text": "Left Outer Join is basically to include all the rows of your dataframe x and only those from y that match, in this, we actually specify the argument x = TRUE. If we try to understand this using a basic set theory then we can say here we are actually displaying complete set x. Now let us try to understand this using R program:Example:" }, { "code": "# R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = \"StudentId\", all.x = TRUE)df", "e": 29452, "s": 29307, "text": null }, { "code": null, "e": 29460, "s": 29452, "text": "Output:" }, { "code": null, "e": 29730, "s": 29460, "text": " StudentId Product State\n1 101 Hindi NA\n2 102 English Manglore\n3 103 Maths NA\n4 104 Science Mysore\n5 105 Political Science NA\n6 106 Physics Pune\n" }, { "code": null, "e": 30070, "s": 29730, "text": "Right, Outer Join is basically to include all the rows of your dataframe y and only those from x that match, in this, we actually specify the argument y = TRUE. If we try to understand this using a basic set theory then we can say here we are actually displaying a complete set y. Now let us try to understand this using R program:Example:" }, { "code": "# R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = \"StudentId\", all.y = TRUE)df", "e": 30215, "s": 30070, "text": null }, { "code": null, "e": 30223, "s": 30215, "text": "Output:" }, { "code": null, "e": 30397, "s": 30223, "text": " StudentId Product State\n1 102 English Manglore\n2 104 Science Mysore\n3 106 Physics Pune\n4 107 NA Dehradun\n5 108 NA Delhi\n" }, { "code": null, "e": 30699, "s": 30397, "text": "Outer Join is basically used to keep all rows from both dataframes, in this, we actually specify the arguments all = TRUE. If we try to understand this using a basic set theory then we can say here we are actually performing the union option. Now let us try to understand this using R program:Example:" }, { "code": "# R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = \"StudentId\", all = TRUE)df", "e": 30844, "s": 30699, "text": null }, { "code": null, "e": 30852, "s": 30844, "text": "Output:" }, { "code": null, "e": 31202, "s": 30852, "text": " StudentId Product State\n1 101 Hindi NA\n2 102 English Manglore\n3 103 Maths NA\n4 104 Science Mysore\n5 105 Political Science NA\n6 106 Physics Pune\n7 107 NA Dehradun\n8 108 NA Delhi\n" }, { "code": null, "e": 31484, "s": 31202, "text": "A Cross Join also known as cartesian join results in every row of one dataframe is being joined to every other row of another dataframe. In set theory, this type of joins is known as the cartesian product between two sets. Now let us try to understand this using R program:Example:" }, { "code": "# R program to illustrate# Joining of dataframes df = merge(x = df1, y = df2, by = NULL)df", "e": 31576, "s": 31484, "text": null }, { "code": null, "e": 31584, "s": 31576, "text": "Output:" }, { "code": null, "e": 33256, "s": 31584, "text": "StudentId.x Product StudentId.y State\n1 101 Hindi 102 Manglore\n2 102 English 102 Manglore\n3 103 Maths 102 Manglore\n4 104 Science 102 Manglore\n5 105 Political Science 102 Manglore\n6 106 Physics 102 Manglore\n7 101 Hindi 104 Mysore\n8 102 English 104 Mysore\n9 103 Maths 104 Mysore\n10 104 Science 104 Mysore\n11 105 Political Science 104 Mysore\n12 106 Physics 104 Mysore\n13 101 Hindi 106 Pune\n14 102 English 106 Pune\n15 103 Maths 106 Pune\n16 104 Science 106 Pune\n17 105 Political Science 106 Pune\n18 106 Physics 106 Pune\n19 101 Hindi 107 Dehradun\n20 102 English 107 Dehradun\n21 103 Maths 107 Dehradun\n22 104 Science 107 Dehradun\n23 105 Political Science 107 Dehradun\n24 106 Physics 107 Dehradun\n25 101 Hindi 108 Delhi\n26 102 English 108 Delhi\n27 103 Maths 108 Delhi\n28 104 Science 108 Delhi\n29 105 Political Science 108 Delhi\n30 106 Physics 108 Delhi\n" }, { "code": null, "e": 33416, "s": 33256, "text": "This join is somewhat like inner join, with only the left dataframe columns and values are selected. Now let us try to understand this using R program:Example:" }, { "code": "# R program to illustrate# Joining of dataframes # Import required librarylibrary(dplyr) df = df1 %>% semi_join(df2, by = \"StudentId\")df", "e": 33555, "s": 33416, "text": null }, { "code": null, "e": 33563, "s": 33555, "text": "Output:" }, { "code": null, "e": 33644, "s": 33563, "text": " StudentId Product\n1 102 English\n2 104 Science\n3 106 Physics\n" }, { "code": null, "e": 33982, "s": 33644, "text": "In terms of set theory, we can say anti-join as set difference operation, for example, A = (1, 2, 3, 4) B = (2, 3, 5) then the output of A-B will be set (1, 4). This join is somewhat like df1 – df2, as it basically selects all rows from df1 that are actually not present in df2. Now let us try to understand this using R program:Example:" }, { "code": "# R program to illustrate# Joining of dataframes # Import required librarylibrary(dplyr) df = df1 %>% anti_join(df2, by = \"StudentId\")df", "e": 34121, "s": 33982, "text": null }, { "code": null, "e": 34129, "s": 34121, "text": "Output:" }, { "code": null, "e": 34250, "s": 34129, "text": " StudentId Product\n1 101 Hindi\n2 103 Maths\n3 105 Political Science\n" }, { "code": null, "e": 34257, "s": 34250, "text": "Picked" }, { "code": null, "e": 34269, "s": 34257, "text": "R-DataFrame" }, { "code": null, "e": 34280, "s": 34269, "text": "R Language" }, { "code": null, "e": 34378, "s": 34280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34436, "s": 34378, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 34488, "s": 34436, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 34520, "s": 34488, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 34564, "s": 34520, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 34616, "s": 34564, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 34651, "s": 34616, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 34689, "s": 34651, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 34747, "s": 34689, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 34779, "s": 34747, "text": "Printing Output of an R Program" } ]
HTML | DOM getBoundingClientRect() Method - GeeksforGeeks
25 Jul, 2019 HTML DOM getBoundingClientRect() Method returns the relative positioning to the viewport.It returns eight properties: left, top, right, bottom, x, y, width, height.Scrolling will change the position value. Syntax: var rect = div.getBoundingClientRect(); Example: <!DOCTYPE html><html> <head> <title> HTML | DOM getBoundingClientRect() Method </title> <script> function myFunction() { var div = document.getElementById("myDiv"); var rectangle = div.getBoundingClientRect(); x = rectangle.left; y = rectangle.top; w = rectangle.width; h = rectangle.height; alert("Left:" + x + ", Top:" + y + ", Width:" + w + ", Height:" + h); } </script></head> <body> <button onclick="myFunction()"> GET POSITION </button> <div style="height:300px; width:400px; overflow:auto;"> <div id="myDiv" style="width:350px; height:250px; background-color:lightgreen; border:2px SOLID green;"> Use scrollbar to change the position. </div> <div style="width:1500px; height:1500px; "> </div> </div> <br> </body> </html> Output:Before Click: After Click: Supported Browsers: Chrome 1.0 Internet Explorer 9.0 FireFox 3.0 Opera 9.5 Safari 4.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26979, "s": 26951, "text": "\n25 Jul, 2019" }, { "code": null, "e": 27185, "s": 26979, "text": "HTML DOM getBoundingClientRect() Method returns the relative positioning to the viewport.It returns eight properties: left, top, right, bottom, x, y, width, height.Scrolling will change the position value." }, { "code": null, "e": 27193, "s": 27185, "text": "Syntax:" }, { "code": null, "e": 27233, "s": 27193, "text": "var rect = div.getBoundingClientRect();" }, { "code": null, "e": 27242, "s": 27233, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML | DOM getBoundingClientRect() Method </title> <script> function myFunction() { var div = document.getElementById(\"myDiv\"); var rectangle = div.getBoundingClientRect(); x = rectangle.left; y = rectangle.top; w = rectangle.width; h = rectangle.height; alert(\"Left:\" + x + \", Top:\" + y + \", Width:\" + w + \", Height:\" + h); } </script></head> <body> <button onclick=\"myFunction()\"> GET POSITION </button> <div style=\"height:300px; width:400px; overflow:auto;\"> <div id=\"myDiv\" style=\"width:350px; height:250px; background-color:lightgreen; border:2px SOLID green;\"> Use scrollbar to change the position. </div> <div style=\"width:1500px; height:1500px; \"> </div> </div> <br> </body> </html>", "e": 28307, "s": 27242, "text": null }, { "code": null, "e": 28328, "s": 28307, "text": "Output:Before Click:" }, { "code": null, "e": 28341, "s": 28328, "text": "After Click:" }, { "code": null, "e": 28361, "s": 28341, "text": "Supported Browsers:" }, { "code": null, "e": 28372, "s": 28361, "text": "Chrome 1.0" }, { "code": null, "e": 28394, "s": 28372, "text": "Internet Explorer 9.0" }, { "code": null, "e": 28406, "s": 28394, "text": "FireFox 3.0" }, { "code": null, "e": 28416, "s": 28406, "text": "Opera 9.5" }, { "code": null, "e": 28427, "s": 28416, "text": "Safari 4.0" }, { "code": null, "e": 28564, "s": 28427, "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": 28573, "s": 28564, "text": "HTML-DOM" }, { "code": null, "e": 28580, "s": 28573, "text": "Picked" }, { "code": null, "e": 28587, "s": 28580, "text": "JQuery" }, { "code": null, "e": 28604, "s": 28587, "text": "Web Technologies" }, { "code": null, "e": 28702, "s": 28604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28757, "s": 28702, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 28830, "s": 28757, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 28853, "s": 28830, "text": "jQuery | ajax() Method" }, { "code": null, "e": 28889, "s": 28853, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 28946, "s": 28889, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 28986, "s": 28946, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29019, "s": 28986, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29064, "s": 29019, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29107, "s": 29064, "text": "How to fetch data from an API in ReactJS ?" } ]
Pointer Expressions in C with Examples - GeeksforGeeks
27 Feb, 2020 Prerequisite: Pointers in C Pointers are used to point to address the location of a variable. A pointer is declared by preceding the name of the pointer by an asterisk(*).Syntax: datatype *pointer_name; When we need to initialize a pointer with variable’s location, we use ampersand sign(&) before the variable name.Example: // Declaration of integer variableint var=10; // Initialization of pointer variableint *pointer=&var; The ampersand (&) is used to get the address of a variable. We can directly find the location of any identifier by just preceding it with an ampersand(&) sign.Example: // This code prints the address of x#include <stdio.h> int main(){ int x = 10; // Prints address of x printf( "Address of variable x = %p", &x); return 0;} Address of variable x = 0x7fff3b690fd4 C supports a rich set of built-in operations like arithmetic, relational, assignment, conditional, etc. which can be performed on identifiers. Just like any other variable, these operations can be also performed on pointer variables. Arithmetic Operators We can perform arithmetic operations to pointer variables using arithmetic operators. We can add an integer or subtract an integer using a pointer pointing to that integer variable. The given table shows the arithmetic operators that can be performed on pointer variables: Examples: *ptr1 + *ptr2 *ptr1 * *ptr2 *ptr1 + *ptr2 - *ptr3 We can also directly perform arithmetic expression using integers. Lets look at the example given below where p1 and p2 are pointers. p1+10, p2-5, p1-p2+10, p1/2 Below diagram represents how exactly the expression/operators work with pointers. As seen in the diagram, pointer ‘pa’ and ‘pb’ points to integer variable ‘a’ and ‘b’ respectively. The addition is performed directly between integer variables and pointer variable and the results are stored in integer variable ‘c’ and ‘x’ respectively. Both the results are the same. Let us understand pointer arithmetic expression better with given code: // Program showing pointer expressions// during Arithmetic Operations#include <stdio.h> int main(){ // Integer variables int a = 20, b = 10; // Variables for storing arithmetic // operations solution int add, sub, div, mul, mod; // Pointer variables for variables // a and b int *ptr_a, *ptr_b; // Initialization of pointers ptr_a = &a; ptr_b = &b; // Performing arithmetic Operations // on pointers add = *ptr_a + *ptr_b; sub = *ptr_a - *ptr_b; mul = *ptr_a * *ptr_b; div = *ptr_a / *ptr_b; mod = *ptr_a % *ptr_b; // Printing values printf("Addition = %d\n", add); printf("Subtraction = %d\n", sub); printf("Multiplication = %d\n", mul); printf("Division = %d\n", div); printf("Modulo = %d\n", mod); return 0;} Addition = 30 Subtraction = 10 Multiplication = 200 Division = 2 Modulo = 0 Note: While performing division, make sure you put a blank space between ‘/’ and ‘*’ of the pointer as together it would make a multi-line comment(‘/*’).Example: Incorrect: *ptr_a/*ptr_b; Correct: *ptr_a / *ptr_b; Correct: (*ptr_a)/(*ptr_b); Relational Operators Relational operations are often used to compare the values of the variable based on which we can take decisions. The given table shows the relational operators that can be performed on pointer variables.Example: *ptr1 > *ptr2 *ptr1 < *ptr2 The value of the relational expression is either 0 or 1 that is false or true. The expression will return value 1 if the expression is true and it’ll return value 0 if false. Let us understand relational expression on pointer better with the code given below: // Program showing pointer expressions// during Relational Operations#include <stdio.h>int main(){ // Initializing integer variables int a = 20, b = 10; // Declaring pointer variables int* ptr_a; int* ptr_b; // Initializing pointer variables ptr_a = &a; ptr_b = &b; // Performing relational operations // less than operator if (*ptr_a < *ptr_b) { printf( "%d is less than %d.", *ptr_a, *ptr_b); } // Greater than operator if (*ptr_a > *ptr_b) { printf( "%d is greater than %d.", *ptr_a, *ptr_b); } // Equal to if (*ptr_a == *ptr_b) { printf( "%d is equal to %d.", *ptr_a, *ptr_b); } return 0;} 20 is greater than 10. Output: 20 is greater than 10. Assignment Operators Assignment operators are used to assign values to the identifiers. There are multiple shorthand operations available. A table is given below showing the actual assignment statement with its shorthand statement.Examples: *a=10 *b+=20 *z=3.5 *s=4.56743 Let us understand assignment operator in better way with the help of code given below: // Program showing pointer expressions// during Assignment Operations#include <stdio.h>int main(){ // Initializing integer variable int a = 30; // Declaring pointer variable int* ptr_a; // Initializing pointer using // assignment operator ptr_a = &a; // Changing the variable's value using // assignment operator *ptr_a = 50; // Printing value of 'a' after // updating its value printf("Value of variable a = %d", *ptr_a); return 0;} Value of variable a = 50 Conditional Operators There is only one mostly used conditional operator in C known as Ternary operator. Ternary operator first checks the expression and depending on its return value returns true or false, which triggers/selects another expression. Syntax: expression1 ? expression2 : expression3; Example: c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2; As shown in example, assuming *ptr1=20 and *ptr2=10 then the condition here becomes true for the expression, so it’ll return value of true expression i.e. *ptr1, so variable ‘c’ will now contain value of 20. Considering same example, assume *ptr1=30 and *ptr2=50 then the condition is false for the expression, so it’ll return value of false expression i.e. *ptr2, so variable ‘c’ will now contain value 50. Let us understand the concept through the given code: // Program showing pointer expressions// during Conditional Operations#include <stdio.h>int main(){ // Initializing integer variables int a = 15, b = 20, result = 0; // Declaring pointer variables int *ptr_a, *ptr_b; // Initializing pointer variables ptr_a = &a; ptr_b = &b; // Performing ternary operator result = ((*ptr_a > *ptr_b) ? *ptr_a : *ptr_b); // Printing result of ternary operator printf("%d is the greatest.", result); return 0;} 20 is the greatest. Unary Operators There are mainly two operators which are given as follows. Examples: (*ptr1)++ (*ptr1)-- Let us understand the use of the unary operator through the given code: // Program showing pointer expressions// during Unary Operations#include <stdio.h>int main(){ // Initializing integer variable int a = 34; // Declaring pointer variable int* ptr_a; // Initializing pointer variable ptr_a = &a; // Value of a before increment printf("Increment:\n"); printf( "Before increment a = %d\n", *ptr_a); // Unary increment operation (*ptr_a)++; // Value of a after increment printf( "After increment a = %d", *ptr_a); // Value before decrement printf("\n\nDecrement:\n"); printf( "Before decrement a = %d\n", *ptr_a); // unary decrement operation (*ptr_a)--; // Value after decrement printf("After decrement a=%d", *ptr_a); return 0;} Increment: Before increment a = 34 After increment a = 35 Decrement: Before decrement a = 35 After decrement a=34 Bitwise Operators Binary operators are also known as bitwise operators. It is used to manipulate data at bit level. Bitwise operators can’t be used for float and double datatype. A table is shown below with all bitwise operators: Examples: *ptr1 & *ptr2 *ptr1 | *ptr2 *ptr1 ^ *ptr2 Let us understand the concept through the given code: // Program showing pointer expressions// during Bitwise Operations#include <stdio.h>int main(){ // Declaring integer variable for // storing result int and, or, ex_or; // Initializing integer variable int a = 1, b = 2; // Performing bitwise operations // AND operation and = a & b; // OR operation or = a | b; // EX-OR operation ex_or = a ^ b; // Printing result of operations printf("\na AND b = %d", and); printf("\na OR b = %d", or); printf("\na Exclusive-OR b = %d", ex_or); return 0;} a AND b = 0 a OR b = 3 a Exclusive-OR b = 3 C-Pointers C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Substring in C++ Core Dump (Segmentation fault) in C/C++ rand() and srand() in C/C++ Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25671, "s": 25643, "text": "\n27 Feb, 2020" }, { "code": null, "e": 25699, "s": 25671, "text": "Prerequisite: Pointers in C" }, { "code": null, "e": 25850, "s": 25699, "text": "Pointers are used to point to address the location of a variable. A pointer is declared by preceding the name of the pointer by an asterisk(*).Syntax:" }, { "code": null, "e": 25875, "s": 25850, "text": "datatype *pointer_name;\n" }, { "code": null, "e": 25997, "s": 25875, "text": "When we need to initialize a pointer with variable’s location, we use ampersand sign(&) before the variable name.Example:" }, { "code": "// Declaration of integer variableint var=10; // Initialization of pointer variableint *pointer=&var;", "e": 26100, "s": 25997, "text": null }, { "code": null, "e": 26268, "s": 26100, "text": "The ampersand (&) is used to get the address of a variable. We can directly find the location of any identifier by just preceding it with an ampersand(&) sign.Example:" }, { "code": "// This code prints the address of x#include <stdio.h> int main(){ int x = 10; // Prints address of x printf( \"Address of variable x = %p\", &x); return 0;}", "e": 26448, "s": 26268, "text": null }, { "code": null, "e": 26488, "s": 26448, "text": "Address of variable x = 0x7fff3b690fd4\n" }, { "code": null, "e": 26722, "s": 26488, "text": "C supports a rich set of built-in operations like arithmetic, relational, assignment, conditional, etc. which can be performed on identifiers. Just like any other variable, these operations can be also performed on pointer variables." }, { "code": null, "e": 26743, "s": 26722, "text": "Arithmetic Operators" }, { "code": null, "e": 27016, "s": 26743, "text": "We can perform arithmetic operations to pointer variables using arithmetic operators. We can add an integer or subtract an integer using a pointer pointing to that integer variable. The given table shows the arithmetic operators that can be performed on pointer variables:" }, { "code": null, "e": 27026, "s": 27016, "text": "Examples:" }, { "code": null, "e": 27077, "s": 27026, "text": "*ptr1 + *ptr2\n*ptr1 * *ptr2\n*ptr1 + *ptr2 - *ptr3\n" }, { "code": null, "e": 27211, "s": 27077, "text": "We can also directly perform arithmetic expression using integers. Lets look at the example given below where p1 and p2 are pointers." }, { "code": null, "e": 27241, "s": 27211, "text": "p1+10, p2-5, p1-p2+10, p1/2 \n" }, { "code": null, "e": 27323, "s": 27241, "text": "Below diagram represents how exactly the expression/operators work with pointers." }, { "code": null, "e": 27608, "s": 27323, "text": "As seen in the diagram, pointer ‘pa’ and ‘pb’ points to integer variable ‘a’ and ‘b’ respectively. The addition is performed directly between integer variables and pointer variable and the results are stored in integer variable ‘c’ and ‘x’ respectively. Both the results are the same." }, { "code": null, "e": 27680, "s": 27608, "text": "Let us understand pointer arithmetic expression better with given code:" }, { "code": "// Program showing pointer expressions// during Arithmetic Operations#include <stdio.h> int main(){ // Integer variables int a = 20, b = 10; // Variables for storing arithmetic // operations solution int add, sub, div, mul, mod; // Pointer variables for variables // a and b int *ptr_a, *ptr_b; // Initialization of pointers ptr_a = &a; ptr_b = &b; // Performing arithmetic Operations // on pointers add = *ptr_a + *ptr_b; sub = *ptr_a - *ptr_b; mul = *ptr_a * *ptr_b; div = *ptr_a / *ptr_b; mod = *ptr_a % *ptr_b; // Printing values printf(\"Addition = %d\\n\", add); printf(\"Subtraction = %d\\n\", sub); printf(\"Multiplication = %d\\n\", mul); printf(\"Division = %d\\n\", div); printf(\"Modulo = %d\\n\", mod); return 0;}", "e": 28478, "s": 27680, "text": null }, { "code": null, "e": 28555, "s": 28478, "text": "Addition = 30\nSubtraction = 10\nMultiplication = 200\nDivision = 2\nModulo = 0\n" }, { "code": null, "e": 28717, "s": 28555, "text": "Note: While performing division, make sure you put a blank space between ‘/’ and ‘*’ of the pointer as together it would make a multi-line comment(‘/*’).Example:" }, { "code": null, "e": 28809, "s": 28717, "text": " Incorrect: *ptr_a/*ptr_b;\n Correct: *ptr_a / *ptr_b; \n Correct: (*ptr_a)/(*ptr_b);\n" }, { "code": null, "e": 28830, "s": 28809, "text": "Relational Operators" }, { "code": null, "e": 29042, "s": 28830, "text": "Relational operations are often used to compare the values of the variable based on which we can take decisions. The given table shows the relational operators that can be performed on pointer variables.Example:" }, { "code": null, "e": 29071, "s": 29042, "text": "*ptr1 > *ptr2\n*ptr1 < *ptr2\n" }, { "code": null, "e": 29246, "s": 29071, "text": "The value of the relational expression is either 0 or 1 that is false or true. The expression will return value 1 if the expression is true and it’ll return value 0 if false." }, { "code": null, "e": 29331, "s": 29246, "text": "Let us understand relational expression on pointer better with the code given below:" }, { "code": "// Program showing pointer expressions// during Relational Operations#include <stdio.h>int main(){ // Initializing integer variables int a = 20, b = 10; // Declaring pointer variables int* ptr_a; int* ptr_b; // Initializing pointer variables ptr_a = &a; ptr_b = &b; // Performing relational operations // less than operator if (*ptr_a < *ptr_b) { printf( \"%d is less than %d.\", *ptr_a, *ptr_b); } // Greater than operator if (*ptr_a > *ptr_b) { printf( \"%d is greater than %d.\", *ptr_a, *ptr_b); } // Equal to if (*ptr_a == *ptr_b) { printf( \"%d is equal to %d.\", *ptr_a, *ptr_b); } return 0;}", "e": 30048, "s": 29331, "text": null }, { "code": null, "e": 30072, "s": 30048, "text": "20 is greater than 10.\n" }, { "code": null, "e": 30080, "s": 30072, "text": "Output:" }, { "code": null, "e": 30104, "s": 30080, "text": "20 is greater than 10.\n" }, { "code": null, "e": 30125, "s": 30104, "text": "Assignment Operators" }, { "code": null, "e": 30345, "s": 30125, "text": "Assignment operators are used to assign values to the identifiers. There are multiple shorthand operations available. A table is given below showing the actual assignment statement with its shorthand statement.Examples:" }, { "code": null, "e": 30377, "s": 30345, "text": "*a=10\n*b+=20\n*z=3.5\n*s=4.56743\n" }, { "code": null, "e": 30464, "s": 30377, "text": "Let us understand assignment operator in better way with the help of code given below:" }, { "code": "// Program showing pointer expressions// during Assignment Operations#include <stdio.h>int main(){ // Initializing integer variable int a = 30; // Declaring pointer variable int* ptr_a; // Initializing pointer using // assignment operator ptr_a = &a; // Changing the variable's value using // assignment operator *ptr_a = 50; // Printing value of 'a' after // updating its value printf(\"Value of variable a = %d\", *ptr_a); return 0;}", "e": 30950, "s": 30464, "text": null }, { "code": null, "e": 30976, "s": 30950, "text": "Value of variable a = 50\n" }, { "code": null, "e": 30998, "s": 30976, "text": "Conditional Operators" }, { "code": null, "e": 31226, "s": 30998, "text": "There is only one mostly used conditional operator in C known as Ternary operator. Ternary operator first checks the expression and depending on its return value returns true or false, which triggers/selects another expression." }, { "code": null, "e": 31234, "s": 31226, "text": "Syntax:" }, { "code": null, "e": 31276, "s": 31234, "text": "expression1 ? expression2 : expression3;\n" }, { "code": null, "e": 31285, "s": 31276, "text": "Example:" }, { "code": null, "e": 31323, "s": 31285, "text": "c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2;\n" }, { "code": null, "e": 31531, "s": 31323, "text": "As shown in example, assuming *ptr1=20 and *ptr2=10 then the condition here becomes true for the expression, so it’ll return value of true expression i.e. *ptr1, so variable ‘c’ will now contain value of 20." }, { "code": null, "e": 31731, "s": 31531, "text": "Considering same example, assume *ptr1=30 and *ptr2=50 then the condition is false for the expression, so it’ll return value of false expression i.e. *ptr2, so variable ‘c’ will now contain value 50." }, { "code": null, "e": 31785, "s": 31731, "text": "Let us understand the concept through the given code:" }, { "code": "// Program showing pointer expressions// during Conditional Operations#include <stdio.h>int main(){ // Initializing integer variables int a = 15, b = 20, result = 0; // Declaring pointer variables int *ptr_a, *ptr_b; // Initializing pointer variables ptr_a = &a; ptr_b = &b; // Performing ternary operator result = ((*ptr_a > *ptr_b) ? *ptr_a : *ptr_b); // Printing result of ternary operator printf(\"%d is the greatest.\", result); return 0;}", "e": 32272, "s": 31785, "text": null }, { "code": null, "e": 32293, "s": 32272, "text": "20 is the greatest.\n" }, { "code": null, "e": 32309, "s": 32293, "text": "Unary Operators" }, { "code": null, "e": 32368, "s": 32309, "text": "There are mainly two operators which are given as follows." }, { "code": null, "e": 32378, "s": 32368, "text": "Examples:" }, { "code": null, "e": 32399, "s": 32378, "text": "(*ptr1)++\n(*ptr1)--\n" }, { "code": null, "e": 32471, "s": 32399, "text": "Let us understand the use of the unary operator through the given code:" }, { "code": "// Program showing pointer expressions// during Unary Operations#include <stdio.h>int main(){ // Initializing integer variable int a = 34; // Declaring pointer variable int* ptr_a; // Initializing pointer variable ptr_a = &a; // Value of a before increment printf(\"Increment:\\n\"); printf( \"Before increment a = %d\\n\", *ptr_a); // Unary increment operation (*ptr_a)++; // Value of a after increment printf( \"After increment a = %d\", *ptr_a); // Value before decrement printf(\"\\n\\nDecrement:\\n\"); printf( \"Before decrement a = %d\\n\", *ptr_a); // unary decrement operation (*ptr_a)--; // Value after decrement printf(\"After decrement a=%d\", *ptr_a); return 0;}", "e": 33231, "s": 32471, "text": null }, { "code": null, "e": 33347, "s": 33231, "text": "Increment:\nBefore increment a = 34\nAfter increment a = 35\n\nDecrement:\nBefore decrement a = 35\nAfter decrement a=34\n" }, { "code": null, "e": 33365, "s": 33347, "text": "Bitwise Operators" }, { "code": null, "e": 33577, "s": 33365, "text": "Binary operators are also known as bitwise operators. It is used to manipulate data at bit level. Bitwise operators can’t be used for float and double datatype. A table is shown below with all bitwise operators:" }, { "code": null, "e": 33587, "s": 33577, "text": "Examples:" }, { "code": null, "e": 33630, "s": 33587, "text": "*ptr1 & *ptr2\n*ptr1 | *ptr2\n*ptr1 ^ *ptr2\n" }, { "code": null, "e": 33684, "s": 33630, "text": "Let us understand the concept through the given code:" }, { "code": "// Program showing pointer expressions// during Bitwise Operations#include <stdio.h>int main(){ // Declaring integer variable for // storing result int and, or, ex_or; // Initializing integer variable int a = 1, b = 2; // Performing bitwise operations // AND operation and = a & b; // OR operation or = a | b; // EX-OR operation ex_or = a ^ b; // Printing result of operations printf(\"\\na AND b = %d\", and); printf(\"\\na OR b = %d\", or); printf(\"\\na Exclusive-OR b = %d\", ex_or); return 0;}", "e": 34235, "s": 33684, "text": null }, { "code": null, "e": 34280, "s": 34235, "text": "a AND b = 0\na OR b = 3\na Exclusive-OR b = 3\n" }, { "code": null, "e": 34291, "s": 34280, "text": "C-Pointers" }, { "code": null, "e": 34302, "s": 34291, "text": "C Language" }, { "code": null, "e": 34313, "s": 34302, "text": "C Programs" }, { "code": null, "e": 34411, "s": 34313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34446, "s": 34411, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 34492, "s": 34446, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 34509, "s": 34492, "text": "Substring in C++" }, { "code": null, "e": 34549, "s": 34509, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 34577, "s": 34549, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 34590, "s": 34577, "text": "Strings in C" }, { "code": null, "e": 34631, "s": 34590, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 34672, "s": 34631, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 34707, "s": 34672, "text": "Header files in C/C++ and its uses" } ]
View Binding with Fragments in Android Jetpack - GeeksforGeeks
25 Feb, 2021 In the Previous article View Binding in Android Jetpack, it’s been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of activity is different Here also things go the same as discussed in the above article the naming conventions of the fragment layout are changed to pascal case and properties of the fragment layout to camel case. For Example, fragment1.xml -> Fragment1Binding and edit_text(id) which is under the fragment’s layout changes to eEditText(camel case) So in this article ViewBinding is discussed using Fragments. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a new empty activity project Using Android Studio create an empty Activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?. Step 2: Enable the ViewBinding feature Enable the ViewBinding feature by invoking the following code snippet inside the app-level build.gradle file, and click on the “Sync Now” buttons which appear on the top-right corner. buildFeatures { viewBinding = true } Refer to the following image if unable to locate the app-level build.gradle file invokes the above build feature. Step 3: Working with the activity_main.xml file The main layout of the activity contains two buttons, to toggle fragment 1 and fragment 2, and one Framelayout to hold the fragments inside the CardView. And one Submit button to check when pressed whose fragment’s data is submitted. To implement the same invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText" tools:viewBindingIgnore="true"> <Button android:id="@+id/fragment_1B" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="FRAGMENT 1" app:layout_constraintEnd_toStartOf="@+id/fragment_2B" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/fragment_2B" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="FRAGMENT 2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toEndOf="@+id/fragment_1B" app:layout_constraintTop_toTopOf="parent" /> <androidx.cardview.widget.CardView android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="256dp" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/fragment_1B"> <FrameLayout android:id="@+id/fragment_holder" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" /> </androidx.cardview.widget.CardView> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="SUBMIT" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/card_view" /> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: Step 4: Creating two fragments Create two fragments, which include text view to represent fragment number edit text and a button. To implement the UI of each fragment you may refer to the following codes. Fragment 1: XML <?xml version="1.0" encoding="utf-8"?><!--fragment 1--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ExampleFragment1" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="Fragment 1" android:textSize="18sp" /> <EditText android:id="@+id/edit_text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" /> <Button android:id="@+id/done_button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="DONE" /> </LinearLayout> Fragment 2: XML <?xml version="1.0" encoding="utf-8"?><!--fragment 2--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ExampleFragment2" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="Fragment 2" android:textSize="18sp" /> <EditText android:id="@+id/edit_text2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" /> <Button android:id="@+id/done_button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="DONE" /> </LinearLayout> Step 5: Working with the Fragments.kt files Firstly the binding variable which is nullable is assigned to null initially, and also when the view of the fragment gets destroyed, again it has to be set null (which in this case _binding). And to avoid the null check of the nullable binding object, by using the backing property of the kotlin we make another copy of the binding variable (which in this case binding). However, if the fragment wants to access the views from the host activity, can be done using the findViewById() method. Invoke the following code inside each of the fragment’s .kt files. Comments are added for better understanding. Fragment 1: Kotlin import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.Toastimport androidx.fragment.app.Fragment // Enter your package name hereimport com.adityamshidlyali.gfgarticle.databinding.Fragment1Binding class ExampleFragment1 : Fragment() { // assign the _binding variable initially to null and // also when the view is destroyed again it has to be set to null private var _binding: Fragment1Binding? = null // with the backing property of the kotlin we extract // the non null value of the _binding private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // inflate the layout and bind to the _binding _binding = Fragment1Binding.inflate(inflater, container, false) // retrieve the entered data by the user binding.doneButton1.setOnClickListener { val str: String = binding.editText1.text.toString() if (str.isNotEmpty()) { Toast.makeText(activity, str, Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity, "Please Enter Data", Toast.LENGTH_SHORT).show() } } // handle the button from the host activity using findViewById method val submitButton: Button = activity!!.findViewById(R.id.submit_button) submitButton.setOnClickListener { Toast.makeText(activity, "Host Activity Element Clicked from Fragment 1", Toast.LENGTH_SHORT).show() } // Inflate the layout for this fragment return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null }} Fragment 2: Kotlin import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.Toastimport androidx.fragment.app.Fragment // Enter your package name hereimport com.adityamshidlyali.gfgarticle.databinding.Fragment2Binding class ExampleFragment2 : Fragment() { // assign the _binding variable initially to null and // also when the view is destroyed again it has to be // set to null private var _binding: Fragment2Binding? = null // with the backing property of the kotlin // we extract // the non null value of the _binding private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // inflate the layout and bind to the _binding _binding = Fragment2Binding.inflate(inflater, container, false) // retrieve the entered data by the user binding.doneButton2.setOnClickListener { val str: String = binding.editText2.text.toString() if (str.isNotEmpty()) { Toast.makeText(activity, str, Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity, "Please Enter Data", Toast.LENGTH_SHORT).show() } } // handle the button from the host activity using findViewById method val submitButton: Button = activity!!.findViewById(R.id.submit_button) submitButton.setOnClickListener { Toast.makeText(activity, "Host Activity Element Clicked from Fragment 2", Toast.LENGTH_SHORT).show() } // Inflate the layout for this fragment return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null }} Step 6: Working with the MainActivity.kt file In the MainActivity.kt file only the transaction functionality of the fragments is implemented. Refer to the following code and its output for better understanding. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.fragment.app.Fragmentimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // create binding instance for the activity_main.xml private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // when app is initially opened the Fragment 1 should be visible supportFragmentManager.beginTransaction().apply { replace(binding.fragmentHolder.id, ExampleFragment1()) addToBackStack(null) commit() } // handle the fragment 2 button to toggle the fragment 2 binding.fragment1B.setOnClickListener { changeFragment(ExampleFragment1()) } // handle the fragment 2 button to toggle the fragment 2 binding.fragment2B.setOnClickListener { changeFragment(ExampleFragment1()) } } // function to change the fragment which is used to reduce the lines of code private fun changeFragment(fragmentToChange: Fragment): Unit { supportFragmentManager.beginTransaction().apply { replace(binding.fragmentHolder.id, fragmentToChange) addToBackStack(null) commit() } }} Android-Jetpack Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Kotlin Array Android UI Layouts Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26381, "s": 26353, "text": "\n25 Feb, 2021" }, { "code": null, "e": 27256, "s": 26381, "text": "In the Previous article View Binding in Android Jetpack, it’s been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of activity is different Here also things go the same as discussed in the above article the naming conventions of the fragment layout are changed to pascal case and properties of the fragment layout to camel case. For Example, fragment1.xml -> Fragment1Binding and edit_text(id) which is under the fragment’s layout changes to eEditText(camel case) So in this article ViewBinding is discussed using Fragments. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 27300, "s": 27256, "text": "Step 1: Create a new empty activity project" }, { "code": null, "e": 27443, "s": 27300, "text": "Using Android Studio create an empty Activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?." }, { "code": null, "e": 27482, "s": 27443, "text": "Step 2: Enable the ViewBinding feature" }, { "code": null, "e": 27666, "s": 27482, "text": "Enable the ViewBinding feature by invoking the following code snippet inside the app-level build.gradle file, and click on the “Sync Now” buttons which appear on the top-right corner." }, { "code": null, "e": 27682, "s": 27666, "text": "buildFeatures {" }, { "code": null, "e": 27708, "s": 27682, "text": " viewBinding = true" }, { "code": null, "e": 27710, "s": 27708, "text": "}" }, { "code": null, "e": 27824, "s": 27710, "text": "Refer to the following image if unable to locate the app-level build.gradle file invokes the above build feature." }, { "code": null, "e": 27872, "s": 27824, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 28106, "s": 27872, "text": "The main layout of the activity contains two buttons, to toggle fragment 1 and fragment 2, and one Framelayout to hold the fragments inside the CardView. And one Submit button to check when pressed whose fragment’s data is submitted." }, { "code": null, "e": 28189, "s": 28106, "text": "To implement the same invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 28193, "s": 28189, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\" tools:viewBindingIgnore=\"true\"> <Button android:id=\"@+id/fragment_1B\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"FRAGMENT 1\" app:layout_constraintEnd_toStartOf=\"@+id/fragment_2B\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/fragment_2B\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"FRAGMENT 2\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintStart_toEndOf=\"@+id/fragment_1B\" app:layout_constraintTop_toTopOf=\"parent\" /> <androidx.cardview.widget.CardView android:id=\"@+id/card_view\" android:layout_width=\"match_parent\" android:layout_height=\"256dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/fragment_1B\"> <FrameLayout android:id=\"@+id/fragment_holder\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"8dp\" android:layout_marginEnd=\"8dp\" /> </androidx.cardview.widget.CardView> <Button android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:text=\"SUBMIT\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/card_view\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 30674, "s": 28193, "text": null }, { "code": null, "e": 30685, "s": 30674, "text": "Output UI:" }, { "code": null, "e": 30716, "s": 30685, "text": "Step 4: Creating two fragments" }, { "code": null, "e": 30890, "s": 30716, "text": "Create two fragments, which include text view to represent fragment number edit text and a button. To implement the UI of each fragment you may refer to the following codes." }, { "code": null, "e": 30902, "s": 30890, "text": "Fragment 1:" }, { "code": null, "e": 30906, "s": 30902, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--fragment 1--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".ExampleFragment1\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"Fragment 1\" android:textSize=\"18sp\" /> <EditText android:id=\"@+id/edit_text1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" /> <Button android:id=\"@+id/done_button1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"end\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" android:text=\"DONE\" /> </LinearLayout>", "e": 32116, "s": 30906, "text": null }, { "code": null, "e": 32128, "s": 32116, "text": "Fragment 2:" }, { "code": null, "e": 32132, "s": 32128, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--fragment 2--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".ExampleFragment2\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"Fragment 2\" android:textSize=\"18sp\" /> <EditText android:id=\"@+id/edit_text2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" /> <Button android:id=\"@+id/done_button2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"end\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" android:text=\"DONE\" /> </LinearLayout>", "e": 33342, "s": 32132, "text": null }, { "code": null, "e": 33386, "s": 33342, "text": "Step 5: Working with the Fragments.kt files" }, { "code": null, "e": 33578, "s": 33386, "text": "Firstly the binding variable which is nullable is assigned to null initially, and also when the view of the fragment gets destroyed, again it has to be set null (which in this case _binding)." }, { "code": null, "e": 33757, "s": 33578, "text": "And to avoid the null check of the nullable binding object, by using the backing property of the kotlin we make another copy of the binding variable (which in this case binding)." }, { "code": null, "e": 33877, "s": 33757, "text": "However, if the fragment wants to access the views from the host activity, can be done using the findViewById() method." }, { "code": null, "e": 33989, "s": 33877, "text": "Invoke the following code inside each of the fragment’s .kt files. Comments are added for better understanding." }, { "code": null, "e": 34001, "s": 33989, "text": "Fragment 1:" }, { "code": null, "e": 34008, "s": 34001, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.Toastimport androidx.fragment.app.Fragment // Enter your package name hereimport com.adityamshidlyali.gfgarticle.databinding.Fragment1Binding class ExampleFragment1 : Fragment() { // assign the _binding variable initially to null and // also when the view is destroyed again it has to be set to null private var _binding: Fragment1Binding? = null // with the backing property of the kotlin we extract // the non null value of the _binding private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // inflate the layout and bind to the _binding _binding = Fragment1Binding.inflate(inflater, container, false) // retrieve the entered data by the user binding.doneButton1.setOnClickListener { val str: String = binding.editText1.text.toString() if (str.isNotEmpty()) { Toast.makeText(activity, str, Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity, \"Please Enter Data\", Toast.LENGTH_SHORT).show() } } // handle the button from the host activity using findViewById method val submitButton: Button = activity!!.findViewById(R.id.submit_button) submitButton.setOnClickListener { Toast.makeText(activity, \"Host Activity Element Clicked from Fragment 1\", Toast.LENGTH_SHORT).show() } // Inflate the layout for this fragment return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null }}", "e": 35834, "s": 34008, "text": null }, { "code": null, "e": 35846, "s": 35834, "text": "Fragment 2:" }, { "code": null, "e": 35853, "s": 35846, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.Toastimport androidx.fragment.app.Fragment // Enter your package name hereimport com.adityamshidlyali.gfgarticle.databinding.Fragment2Binding class ExampleFragment2 : Fragment() { // assign the _binding variable initially to null and // also when the view is destroyed again it has to be // set to null private var _binding: Fragment2Binding? = null // with the backing property of the kotlin // we extract // the non null value of the _binding private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // inflate the layout and bind to the _binding _binding = Fragment2Binding.inflate(inflater, container, false) // retrieve the entered data by the user binding.doneButton2.setOnClickListener { val str: String = binding.editText2.text.toString() if (str.isNotEmpty()) { Toast.makeText(activity, str, Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity, \"Please Enter Data\", Toast.LENGTH_SHORT).show() } } // handle the button from the host activity using findViewById method val submitButton: Button = activity!!.findViewById(R.id.submit_button) submitButton.setOnClickListener { Toast.makeText(activity, \"Host Activity Element Clicked from Fragment 2\", Toast.LENGTH_SHORT).show() } // Inflate the layout for this fragment return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null }}", "e": 37692, "s": 35853, "text": null }, { "code": null, "e": 37738, "s": 37692, "text": "Step 6: Working with the MainActivity.kt file" }, { "code": null, "e": 37903, "s": 37738, "text": "In the MainActivity.kt file only the transaction functionality of the fragments is implemented. Refer to the following code and its output for better understanding." }, { "code": null, "e": 37910, "s": 37903, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.fragment.app.Fragmentimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // create binding instance for the activity_main.xml private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // when app is initially opened the Fragment 1 should be visible supportFragmentManager.beginTransaction().apply { replace(binding.fragmentHolder.id, ExampleFragment1()) addToBackStack(null) commit() } // handle the fragment 2 button to toggle the fragment 2 binding.fragment1B.setOnClickListener { changeFragment(ExampleFragment1()) } // handle the fragment 2 button to toggle the fragment 2 binding.fragment2B.setOnClickListener { changeFragment(ExampleFragment1()) } } // function to change the fragment which is used to reduce the lines of code private fun changeFragment(fragmentToChange: Fragment): Unit { supportFragmentManager.beginTransaction().apply { replace(binding.fragmentHolder.id, fragmentToChange) addToBackStack(null) commit() } }}", "e": 39376, "s": 37910, "text": null }, { "code": null, "e": 39392, "s": 39376, "text": "Android-Jetpack" }, { "code": null, "e": 39416, "s": 39392, "text": "Technical Scripter 2020" }, { "code": null, "e": 39424, "s": 39416, "text": "Android" }, { "code": null, "e": 39431, "s": 39424, "text": "Kotlin" }, { "code": null, "e": 39450, "s": 39431, "text": "Technical Scripter" }, { "code": null, "e": 39458, "s": 39450, "text": "Android" }, { "code": null, "e": 39556, "s": 39458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39594, "s": 39556, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 39633, "s": 39594, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 39683, "s": 39633, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 39725, "s": 39683, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 39776, "s": 39725, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 39789, "s": 39776, "text": "Kotlin Array" }, { "code": null, "e": 39808, "s": 39789, "text": "Android UI Layouts" }, { "code": null, "e": 39850, "s": 39808, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 39890, "s": 39850, "text": "How to Get Current Location in Android?" } ]
Creating PDF Documents With Python - GeeksforGeeks
05 May, 2021 In this article, we will be learning how to create PDFs in Python. A very famous module named pypdf2 is used to modify and read existing pdfs but its major disadvantage is that it cannot create new pdf files. So Today we are looking to learn about another python module named reportlab that helps us to create new pdf files and edit our heart’s content on it. Module Required: Reportlab: This module is used to handle PDF files. pip install reportlab Step-by-step Approach: Step 1: We start by importing the modules and classes. Canvas is used to draw things on the pdf, ttfonts and pdfmetrics will help us to use custom TTF fonts in the pdf, and colors would help us to pick colours easily without remembering their hex values. Python3 # importing modulesfrom reportlab.pdfgen import canvasfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetricsfrom reportlab.lib import colors Step 2: Next, we initialize all the things we would b writing and drawing in the document to specific variables to easily call them when needed. Python3 # initializing variables with valuesfileName = 'sample.pdf'documentTitle = 'sample'title = 'Technology'subTitle = 'The largest thing now!!'textLines = [ 'Technology makes us aware of', 'the world around us.',]image = 'image.jpg' Step 3: Next, we initialize a canvas object with the name of the pdf and set the title to be documentTitle. Python3 # creating a pdf objectpdf = canvas.Canvas(fileName) # setting the title of the documentpdf.setTitle(documentTitle) Step 4: Next, we register our external font to the reportlab fonts using pdfmetrics and TTFont and assigned it a name. Next, we set the new font with a size. Then we draw the string on the pdf using the drawCentredString function that takes the x and y values as the center of the text to the written and the left, right, top and bottom of the text are adjusted accordingly. Note that we need the TTF file to be present in the folder to execute the commands. Python3 # registering a external font in pythonpdfmetrics.registerFont( TTFont('abc', 'SakBunderan.ttf')) # creating the title by setting it's font# and putting it on the canvaspdf.setFont('abc', 36)pdf.drawCentredString(300, 770, title) Step 5: Next for the subtitle, we do the same thing except for this time the colour of the subtitle to be blue, and this time we use a standard font that ships in natively with reportlab. Python3 # creating the subtitle by setting it's font,# colour and putting it on the canvaspdf.setFillColorRGB(0, 0, 255)pdf.setFont("Courier-Bold", 24)pdf.drawCentredString(290, 720, subTitle) Step 6: Next, we draw a line and then enter several lines of text that we defined earlier inside a list. The first line defines the starting x and y position of the text. The next two lines set the font, font-size and font-color of the text. The next two lines traverse through each element in the list and add it as a line to the text. The last line draws the text to the screen. Python3 # drawing a linepdf.line(30, 710, 550, 710) # creating a multiline text using# textline and for looptext = pdf.beginText(40, 680)text.setFont("Courier", 18)text.setFillColor(colors.red) for line in textLines: text.textLine(line) pdf.drawText(text) Step 7: At last, we draw a picture on the pdf using the drawInlineImage function in which the parameters are the path of the image and the x and y coordinates of the image. In this case, the image was in the same directory as the py file, so according to the relative path, we need to write only the name of the file with the extension, if it was in some other directory, a relevant correct relative path should be used. Python3 # drawing a image at the# specified (x.y) positionpdf.drawInlineImage(image, 130, 400) # saving the pdfpdf.save() Below is the complete program: Python3 # importing modulesfrom reportlab.pdfgen import canvasfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetricsfrom reportlab.lib import colors # initializing variables with valuesfileName = 'sample.pdf'documentTitle = 'sample'title = 'Technology'subTitle = 'The largest thing now!!'textLines = [ 'Technology makes us aware of', 'the world around us.',]image = 'image.jpg' # creating a pdf objectpdf = canvas.Canvas(fileName) # setting the title of the documentpdf.setTitle(documentTitle) # registering a external font in pythonpdfmetrics.registerFont( TTFont('abc', 'SakBunderan.ttf')) # creating the title by setting it's font# and putting it on the canvaspdf.setFont('abc', 36)pdf.drawCentredString(300, 770, title) # creating the subtitle by setting it's font,# colour and putting it on the canvaspdf.setFillColorRGB(0, 0, 255)pdf.setFont("Courier-Bold", 24)pdf.drawCentredString(290, 720, subTitle) # drawing a linepdf.line(30, 710, 550, 710) # creating a multiline text using# textline and for looptext = pdf.beginText(40, 680)text.setFont("Courier", 18)text.setFillColor(colors.red)for line in textLines: text.textLine(line)pdf.drawText(text) # drawing a image at the# specified (x.y) positionpdf.drawInlineImage(image, 130, 400) # saving the pdfpdf.save() Output: simranarora5sos Picked python-utility 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": 25561, "s": 25533, "text": "\n05 May, 2021" }, { "code": null, "e": 25921, "s": 25561, "text": "In this article, we will be learning how to create PDFs in Python. A very famous module named pypdf2 is used to modify and read existing pdfs but its major disadvantage is that it cannot create new pdf files. So Today we are looking to learn about another python module named reportlab that helps us to create new pdf files and edit our heart’s content on it." }, { "code": null, "e": 25938, "s": 25921, "text": "Module Required:" }, { "code": null, "e": 25990, "s": 25938, "text": "Reportlab: This module is used to handle PDF files." }, { "code": null, "e": 26012, "s": 25990, "text": "pip install reportlab" }, { "code": null, "e": 26035, "s": 26012, "text": "Step-by-step Approach:" }, { "code": null, "e": 26043, "s": 26035, "text": "Step 1:" }, { "code": null, "e": 26290, "s": 26043, "text": "We start by importing the modules and classes. Canvas is used to draw things on the pdf, ttfonts and pdfmetrics will help us to use custom TTF fonts in the pdf, and colors would help us to pick colours easily without remembering their hex values." }, { "code": null, "e": 26298, "s": 26290, "text": "Python3" }, { "code": "# importing modulesfrom reportlab.pdfgen import canvasfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetricsfrom reportlab.lib import colors", "e": 26469, "s": 26298, "text": null }, { "code": null, "e": 26477, "s": 26469, "text": "Step 2:" }, { "code": null, "e": 26614, "s": 26477, "text": "Next, we initialize all the things we would b writing and drawing in the document to specific variables to easily call them when needed." }, { "code": null, "e": 26622, "s": 26614, "text": "Python3" }, { "code": "# initializing variables with valuesfileName = 'sample.pdf'documentTitle = 'sample'title = 'Technology'subTitle = 'The largest thing now!!'textLines = [ 'Technology makes us aware of', 'the world around us.',]image = 'image.jpg'", "e": 26857, "s": 26622, "text": null }, { "code": null, "e": 26865, "s": 26857, "text": "Step 3:" }, { "code": null, "e": 26966, "s": 26865, "text": "Next, we initialize a canvas object with the name of the pdf and set the title to be documentTitle. " }, { "code": null, "e": 26974, "s": 26966, "text": "Python3" }, { "code": "# creating a pdf objectpdf = canvas.Canvas(fileName) # setting the title of the documentpdf.setTitle(documentTitle)", "e": 27090, "s": 26974, "text": null }, { "code": null, "e": 27098, "s": 27090, "text": "Step 4:" }, { "code": null, "e": 27549, "s": 27098, "text": "Next, we register our external font to the reportlab fonts using pdfmetrics and TTFont and assigned it a name. Next, we set the new font with a size. Then we draw the string on the pdf using the drawCentredString function that takes the x and y values as the center of the text to the written and the left, right, top and bottom of the text are adjusted accordingly. Note that we need the TTF file to be present in the folder to execute the commands." }, { "code": null, "e": 27557, "s": 27549, "text": "Python3" }, { "code": "# registering a external font in pythonpdfmetrics.registerFont( TTFont('abc', 'SakBunderan.ttf')) # creating the title by setting it's font# and putting it on the canvaspdf.setFont('abc', 36)pdf.drawCentredString(300, 770, title)", "e": 27790, "s": 27557, "text": null }, { "code": null, "e": 27800, "s": 27790, "text": " Step 5:" }, { "code": null, "e": 27982, "s": 27800, "text": "Next for the subtitle, we do the same thing except for this time the colour of the subtitle to be blue, and this time we use a standard font that ships in natively with reportlab. " }, { "code": null, "e": 27990, "s": 27982, "text": "Python3" }, { "code": "# creating the subtitle by setting it's font,# colour and putting it on the canvaspdf.setFillColorRGB(0, 0, 255)pdf.setFont(\"Courier-Bold\", 24)pdf.drawCentredString(290, 720, subTitle)", "e": 28175, "s": 27990, "text": null }, { "code": null, "e": 28183, "s": 28175, "text": "Step 6:" }, { "code": null, "e": 28556, "s": 28183, "text": "Next, we draw a line and then enter several lines of text that we defined earlier inside a list. The first line defines the starting x and y position of the text. The next two lines set the font, font-size and font-color of the text. The next two lines traverse through each element in the list and add it as a line to the text. The last line draws the text to the screen." }, { "code": null, "e": 28564, "s": 28556, "text": "Python3" }, { "code": "# drawing a linepdf.line(30, 710, 550, 710) # creating a multiline text using# textline and for looptext = pdf.beginText(40, 680)text.setFont(\"Courier\", 18)text.setFillColor(colors.red) for line in textLines: text.textLine(line) pdf.drawText(text)", "e": 28819, "s": 28564, "text": null }, { "code": null, "e": 28827, "s": 28819, "text": "Step 7:" }, { "code": null, "e": 29240, "s": 28827, "text": "At last, we draw a picture on the pdf using the drawInlineImage function in which the parameters are the path of the image and the x and y coordinates of the image. In this case, the image was in the same directory as the py file, so according to the relative path, we need to write only the name of the file with the extension, if it was in some other directory, a relevant correct relative path should be used." }, { "code": null, "e": 29248, "s": 29240, "text": "Python3" }, { "code": "# drawing a image at the# specified (x.y) positionpdf.drawInlineImage(image, 130, 400) # saving the pdfpdf.save()", "e": 29362, "s": 29248, "text": null }, { "code": null, "e": 29394, "s": 29362, "text": " Below is the complete program:" }, { "code": null, "e": 29402, "s": 29394, "text": "Python3" }, { "code": "# importing modulesfrom reportlab.pdfgen import canvasfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetricsfrom reportlab.lib import colors # initializing variables with valuesfileName = 'sample.pdf'documentTitle = 'sample'title = 'Technology'subTitle = 'The largest thing now!!'textLines = [ 'Technology makes us aware of', 'the world around us.',]image = 'image.jpg' # creating a pdf objectpdf = canvas.Canvas(fileName) # setting the title of the documentpdf.setTitle(documentTitle) # registering a external font in pythonpdfmetrics.registerFont( TTFont('abc', 'SakBunderan.ttf')) # creating the title by setting it's font# and putting it on the canvaspdf.setFont('abc', 36)pdf.drawCentredString(300, 770, title) # creating the subtitle by setting it's font,# colour and putting it on the canvaspdf.setFillColorRGB(0, 0, 255)pdf.setFont(\"Courier-Bold\", 24)pdf.drawCentredString(290, 720, subTitle) # drawing a linepdf.line(30, 710, 550, 710) # creating a multiline text using# textline and for looptext = pdf.beginText(40, 680)text.setFont(\"Courier\", 18)text.setFillColor(colors.red)for line in textLines: text.textLine(line)pdf.drawText(text) # drawing a image at the# specified (x.y) positionpdf.drawInlineImage(image, 130, 400) # saving the pdfpdf.save()", "e": 30705, "s": 29402, "text": null }, { "code": null, "e": 30713, "s": 30705, "text": "Output:" }, { "code": null, "e": 30729, "s": 30713, "text": "simranarora5sos" }, { "code": null, "e": 30736, "s": 30729, "text": "Picked" }, { "code": null, "e": 30751, "s": 30736, "text": "python-utility" }, { "code": null, "e": 30758, "s": 30751, "text": "Python" }, { "code": null, "e": 30856, "s": 30758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30888, "s": 30856, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30930, "s": 30888, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30972, "s": 30930, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31028, "s": 30972, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31055, "s": 31028, "text": "Python Classes and Objects" }, { "code": null, "e": 31094, "s": 31055, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31125, "s": 31094, "text": "Python | os.path.join() method" }, { "code": null, "e": 31154, "s": 31125, "text": "Create a directory in Python" }, { "code": null, "e": 31176, "s": 31154, "text": "Defaultdict in Python" } ]
Print all possible joints of a Trie constructed from a given list of strings - GeeksforGeeks
21 Jun, 2021 Given a set of strings str, the task is to print all the joints of the Trie constructed from the given set of strings. Joints of a Trie is the nodes in a trie that have more than one child. Examples: Input: str = {"cat", "there", "caller", "their", "calling"} Output: l, a, e Explanation: root / \ c t | | a h / | | t l e | | \ l i r | \ | | e i r e | | r n | g Input: str = {"Candy", "cat", "Caller", "calling"} Output: l, a Explanation: root | c | a / | \ l n t | | l d | \ | e i y | | r n | g Approach: Follow the steps given below to solve the problem: Traverse the Trie, and take a currChild variable as zero. Increment the currChild by 1, when the current node has a child and while returning from current node check if currChild is greater than 1 or not. If so, print this character or joint. Otherwise, skip to next character. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print all the// joints of a Trie constructed// from a given set of strings #include <bits/stdc++.h>using namespace std;#define CHILDREN 26#define MAX 100 // Trie nodestruct trie { trie* child[CHILDREN]; bool endOfWord;}; // Function will return the// new node(initialized to NULLs)trie* createNode(){ trie* temp = new trie(); temp->endOfWord = false; for (int i = 0; i < CHILDREN; i++) { temp->child[i] = NULL; } return temp;} // Function will insert the// string in a trie recursivelyvoid insertRecursively(trie* itr, string str, int i){ if (i < str.length()) { int index = str[i] - 'a'; if (itr->child[index] == NULL) { // Create a new node itr->child[index] = createNode(); } // Recursive call for insertion // of string insertRecursively(itr->child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of string itr->endOfWord = true; }} // Function call to insert a stringvoid insert(trie* itr, string str){ // Function call with // necessary arguments insertRecursively(itr, str, 0);} // Function to check whether the// node is leaf or notbool isLeafNode(trie* root){ return root->endOfWord != false;} // Function to display the Joints of trievoid display(trie* root, trie* itr, char str[], int level){ // Count current child int currChild = 0; for (int i = 0; i < CHILDREN; i++) { // Check for NON NULL child is found // add parent key to str and // call the display function // recursively for child node if (itr->child[i]) { str[level] = i + 'a'; display(root, itr->child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { cout << str[level - 1] << endl; }} // Function call for displaying Jointvoid displayJoint(trie* root){ int level = 0; char str[MAX]; display(root, root, str, level);} // Driver codeint main(){ trie* root = createNode(); vector<string> s = { "geek", "geeky", "geeks", "gel" }; for (string str : s) { insert(root, str); } displayJoint(root); return 0;} // Java program to print all the// joints of a Trie constructed// from a given set of Stringsimport java.util.*; class GFG{static final int CHILDREN = 26;static final int MAX = 100; // Trie nodestatic class trie{ trie []child = new trie[CHILDREN]; boolean endOfWord;}; // Function will return the// new node(initialized to nulls)static trie createNode(){ trie temp = new trie(); temp.endOfWord = false; for (int i = 0; i < CHILDREN; i++) { temp.child[i] = null; } return temp;} // Function will insert the// String in a trie recursivelystatic void insertRecursively(trie itr, String str, int i){ if (i < str.length()) { int index = str.charAt(i) - 'a'; if (itr.child[index] == null) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion // of String insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of String itr.endOfWord = true; }} // Function call to insert a Stringstatic void insert(trie itr, String str){ // Function call with // necessary arguments insertRecursively(itr, str, 0);} // Function to check whether the// node is leaf or notstatic boolean isLeafNode(trie root){ return root.endOfWord != false;} // Function to display the Joints of triestatic void display(trie root, trie itr, char str[], int level){ // Count current child int currChild = 0; for (int i = 0; i < CHILDREN; i++) { // Check for NON null child is found // add parent key to str and // call the display function // recursively for child node if (itr.child[i] != null) { str[level] = (char) (i + 'a'); display(root, itr.child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { System.out.print(str[level - 1] + "\n"); }} // Function call for displaying Jointstatic void displayJoint(trie root){ int level = 0; char []str = new char[MAX]; display(root, root, str, level);} // Driver codepublic static void main(String[] args){ trie root = createNode(); String []s = { "geek", "geeky", "geeks", "gel" }; for (String str : s) { insert(root, str); } displayJoint(root);}} // This code is contributed by sapnasingh4991 # Python3 program to traverse in bottom up mannerCHILDREN = 26MAX = 100 # Trie nodeclass trie: def __init__(self): self.child = [None for i in range(CHILDREN)] # endOfWord is true if the node represents # end of a word self.endOfWord = False # Function will return the new node(initialized to NULLs)def createNode(): temp = trie() return temp # Function will inert the string in a trie recursivelydef insertRecursively(itr, str, i): if(i < len(str)): index = ord(str[i]) - ord('a') if(itr.child[index] == None ): #Create a new node itr.child[index] = createNode(); # Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); else: # Make the endOfWord true which represents # the end of string itr.endOfWord = True; # Function call to insert a stringdef insert(itr, str): # Function call with necessary arguments insertRecursively(itr, str, 0); # Function to check whether the node is leaf or notdef isLeafNode(root): return root.endOfWord != False; # Function to display the Joints of triedef display(root, itr, str, level): # Count current child currChild = 0; for i in range(CHILDREN): # Check for NON NULL child is found # add parent key to str and # call the display function # recursively for child node if (itr.child[i]): str[level] = chr(i + ord('a')); display(root, itr.child[i],str, level + 1); currChild += 1 # Print character if it has more # than 1 child if (currChild > 1 and itr != root): print(str[level - 1]) # Function call for displaying Jointdef displayJoint(root): level = 0; str = ['' for i in range(MAX)]; display(root, root, str, level); # Driver codeif __name__=='__main__': root = createNode() s = ["geek", "geeky", "geeks", "gel"] for str in s: insert(root, str); displayJoint(root) # This code is contributed by rutvik_56 // C# program to print all the// joints of a Trie constructed// from a given set of Stringsusing System; class GFG{ static readonly int CHILDREN = 26;static readonly int MAX = 100; // Trie nodeclass trie{ public trie []child = new trie[CHILDREN]; public bool endOfWord;}; // Function will return the// new node(initialized to nulls)static trie createNode(){ trie temp = new trie(); temp.endOfWord = false; for(int i = 0; i < CHILDREN; i++) { temp.child[i] = null; } return temp;} // Function will insert the// String in a trie recursivelystatic void insertRecursively(trie itr, String str, int i){ if (i < str.Length) { int index = str[i] - 'a'; if (itr.child[index] == null) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion // of String insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of String itr.endOfWord = true; }} // Function call to insert a Stringstatic void insert(trie itr, String str){ // Function call with // necessary arguments insertRecursively(itr, str, 0);} // Function to check whether the// node is leaf or notstatic bool isLeafNode(trie root){ return root.endOfWord != false;} // Function to display the Joints of triestatic void display(trie root, trie itr, char []str, int level){ // Count current child int currChild = 0; for(int i = 0; i < CHILDREN; i++) { // Check for NON null child is found // add parent key to str and // call the display function // recursively for child node if (itr.child[i] != null) { str[level] = (char)(i + 'a'); display(root, itr.child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { Console.Write(str[level - 1] + "\n"); }} // Function call for displaying Jointstatic void displayJoint(trie root){ int level = 0; char []str = new char[MAX]; display(root, root, str, level);} // Driver codepublic static void Main(String[] args){ trie root = createNode(); String []s = { "geek", "geeky", "geeks", "gel" }; foreach(String str in s) { insert(root, str); } displayJoint(root);}} // This code is contributed by Rajput-Ji <script> // Javascript program to print all the // joints of a Trie constructed // from a given set of Strings let CHILDREN = 26; let MAX = 100; // Trie node class trie { constructor() { } } // Function will return the // new node(initialized to nulls) function createNode(endOfWord) { let temp = new trie(); temp.child = new trie(CHILDREN); temp.endOfWord = endOfWord; for (let i = 0; i < CHILDREN; i++) { temp.child[i] = null; } return temp; } // Function will insert the // String in a trie recursively function insertRecursively(itr, str, i) { if (i < str.length) { let index = str[i].charCodeAt() - 'a'.charCodeAt(); if (itr.child[index] == null) { // Create a new node itr.child[index] = createNode(false); } // Recursive call for insertion // of String insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of String itr.endOfWord = true; } } // Function call to insert a String function insert(itr, str) { // Function call with // necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the // node is leaf or not function isLeafNode(root) { return root.endOfWord != false; } // Function to display the Joints of trie function display(root, itr, str, level) { // Count current child let currChild = 0; for (let i = 0; i < CHILDREN; i++) { // Check for NON null child is found // add parent key to str and // call the display function // recursively for child node if (itr.child[i] != null) { str[level] = String.fromCharCode(i + 'a'.charCodeAt()); display(root, itr.child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { document.write(str[level - 1] + "</br>"); } } // Function call for displaying Joint function displayJoint(root) { let level = 0; let str = new Array(MAX); display(root, root, str, level); } let root = createNode(false); let s = [ "geek", "geeky", "geeks", "gel" ]; for (let str = 0; str < s.length; str++) { insert(root, s[str]); } displayJoint(root); // This code is contributed by mukesh07.</script> k e sapnasingh4991 Rajput-Ji rutvik_56 mukesh07 Trie Advanced Data Structure Strings Tree Strings Tree Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Interval Tree Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25707, "s": 25679, "text": "\n21 Jun, 2021" }, { "code": null, "e": 25827, "s": 25707, "text": "Given a set of strings str, the task is to print all the joints of the Trie constructed from the given set of strings. " }, { "code": null, "e": 25900, "s": 25827, "text": "Joints of a Trie is the nodes in a trie that have more than one child. " }, { "code": null, "e": 25912, "s": 25900, "text": "Examples: " }, { "code": null, "e": 26550, "s": 25912, "text": "Input:\nstr = {\"cat\", \"there\", \"caller\",\n \"their\", \"calling\"}\nOutput: l, a, e\nExplanation:\n root\n / \\ \n c t \n | | \n a h \n / | | \n t l e\n | | \\\n l i r\n | \\ | |\n e i r e\n | |\n r n\n |\n g \n\nInput:\nstr = {\"Candy\", \"cat\",\n \"Caller\", \"calling\"}\nOutput: l, a\nExplanation:\n root\n | \n c \n | \n a \n / | \\ \n l n t \n | | \n l d \n | \\ | \n e i y \n | |\n r n\n |\n g" }, { "code": null, "e": 26615, "s": 26552, "text": "Approach: Follow the steps given below to solve the problem: " }, { "code": null, "e": 26673, "s": 26615, "text": "Traverse the Trie, and take a currChild variable as zero." }, { "code": null, "e": 26893, "s": 26673, "text": "Increment the currChild by 1, when the current node has a child and while returning from current node check if currChild is greater than 1 or not. If so, print this character or joint. Otherwise, skip to next character." }, { "code": null, "e": 26946, "s": 26893, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26950, "s": 26946, "text": "C++" }, { "code": null, "e": 26955, "s": 26950, "text": "Java" }, { "code": null, "e": 26963, "s": 26955, "text": "Python3" }, { "code": null, "e": 26966, "s": 26963, "text": "C#" }, { "code": null, "e": 26977, "s": 26966, "text": "Javascript" }, { "code": "// C++ program to print all the// joints of a Trie constructed// from a given set of strings #include <bits/stdc++.h>using namespace std;#define CHILDREN 26#define MAX 100 // Trie nodestruct trie { trie* child[CHILDREN]; bool endOfWord;}; // Function will return the// new node(initialized to NULLs)trie* createNode(){ trie* temp = new trie(); temp->endOfWord = false; for (int i = 0; i < CHILDREN; i++) { temp->child[i] = NULL; } return temp;} // Function will insert the// string in a trie recursivelyvoid insertRecursively(trie* itr, string str, int i){ if (i < str.length()) { int index = str[i] - 'a'; if (itr->child[index] == NULL) { // Create a new node itr->child[index] = createNode(); } // Recursive call for insertion // of string insertRecursively(itr->child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of string itr->endOfWord = true; }} // Function call to insert a stringvoid insert(trie* itr, string str){ // Function call with // necessary arguments insertRecursively(itr, str, 0);} // Function to check whether the// node is leaf or notbool isLeafNode(trie* root){ return root->endOfWord != false;} // Function to display the Joints of trievoid display(trie* root, trie* itr, char str[], int level){ // Count current child int currChild = 0; for (int i = 0; i < CHILDREN; i++) { // Check for NON NULL child is found // add parent key to str and // call the display function // recursively for child node if (itr->child[i]) { str[level] = i + 'a'; display(root, itr->child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { cout << str[level - 1] << endl; }} // Function call for displaying Jointvoid displayJoint(trie* root){ int level = 0; char str[MAX]; display(root, root, str, level);} // Driver codeint main(){ trie* root = createNode(); vector<string> s = { \"geek\", \"geeky\", \"geeks\", \"gel\" }; for (string str : s) { insert(root, str); } displayJoint(root); return 0;}", "e": 29383, "s": 26977, "text": null }, { "code": "// Java program to print all the// joints of a Trie constructed// from a given set of Stringsimport java.util.*; class GFG{static final int CHILDREN = 26;static final int MAX = 100; // Trie nodestatic class trie{ trie []child = new trie[CHILDREN]; boolean endOfWord;}; // Function will return the// new node(initialized to nulls)static trie createNode(){ trie temp = new trie(); temp.endOfWord = false; for (int i = 0; i < CHILDREN; i++) { temp.child[i] = null; } return temp;} // Function will insert the// String in a trie recursivelystatic void insertRecursively(trie itr, String str, int i){ if (i < str.length()) { int index = str.charAt(i) - 'a'; if (itr.child[index] == null) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion // of String insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of String itr.endOfWord = true; }} // Function call to insert a Stringstatic void insert(trie itr, String str){ // Function call with // necessary arguments insertRecursively(itr, str, 0);} // Function to check whether the// node is leaf or notstatic boolean isLeafNode(trie root){ return root.endOfWord != false;} // Function to display the Joints of triestatic void display(trie root, trie itr, char str[], int level){ // Count current child int currChild = 0; for (int i = 0; i < CHILDREN; i++) { // Check for NON null child is found // add parent key to str and // call the display function // recursively for child node if (itr.child[i] != null) { str[level] = (char) (i + 'a'); display(root, itr.child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { System.out.print(str[level - 1] + \"\\n\"); }} // Function call for displaying Jointstatic void displayJoint(trie root){ int level = 0; char []str = new char[MAX]; display(root, root, str, level);} // Driver codepublic static void main(String[] args){ trie root = createNode(); String []s = { \"geek\", \"geeky\", \"geeks\", \"gel\" }; for (String str : s) { insert(root, str); } displayJoint(root);}} // This code is contributed by sapnasingh4991", "e": 31981, "s": 29383, "text": null }, { "code": "# Python3 program to traverse in bottom up mannerCHILDREN = 26MAX = 100 # Trie nodeclass trie: def __init__(self): self.child = [None for i in range(CHILDREN)] # endOfWord is true if the node represents # end of a word self.endOfWord = False # Function will return the new node(initialized to NULLs)def createNode(): temp = trie() return temp # Function will inert the string in a trie recursivelydef insertRecursively(itr, str, i): if(i < len(str)): index = ord(str[i]) - ord('a') if(itr.child[index] == None ): #Create a new node itr.child[index] = createNode(); # Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); else: # Make the endOfWord true which represents # the end of string itr.endOfWord = True; # Function call to insert a stringdef insert(itr, str): # Function call with necessary arguments insertRecursively(itr, str, 0); # Function to check whether the node is leaf or notdef isLeafNode(root): return root.endOfWord != False; # Function to display the Joints of triedef display(root, itr, str, level): # Count current child currChild = 0; for i in range(CHILDREN): # Check for NON NULL child is found # add parent key to str and # call the display function # recursively for child node if (itr.child[i]): str[level] = chr(i + ord('a')); display(root, itr.child[i],str, level + 1); currChild += 1 # Print character if it has more # than 1 child if (currChild > 1 and itr != root): print(str[level - 1]) # Function call for displaying Jointdef displayJoint(root): level = 0; str = ['' for i in range(MAX)]; display(root, root, str, level); # Driver codeif __name__=='__main__': root = createNode() s = [\"geek\", \"geeky\", \"geeks\", \"gel\"] for str in s: insert(root, str); displayJoint(root) # This code is contributed by rutvik_56", "e": 34098, "s": 31981, "text": null }, { "code": "// C# program to print all the// joints of a Trie constructed// from a given set of Stringsusing System; class GFG{ static readonly int CHILDREN = 26;static readonly int MAX = 100; // Trie nodeclass trie{ public trie []child = new trie[CHILDREN]; public bool endOfWord;}; // Function will return the// new node(initialized to nulls)static trie createNode(){ trie temp = new trie(); temp.endOfWord = false; for(int i = 0; i < CHILDREN; i++) { temp.child[i] = null; } return temp;} // Function will insert the// String in a trie recursivelystatic void insertRecursively(trie itr, String str, int i){ if (i < str.Length) { int index = str[i] - 'a'; if (itr.child[index] == null) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion // of String insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of String itr.endOfWord = true; }} // Function call to insert a Stringstatic void insert(trie itr, String str){ // Function call with // necessary arguments insertRecursively(itr, str, 0);} // Function to check whether the// node is leaf or notstatic bool isLeafNode(trie root){ return root.endOfWord != false;} // Function to display the Joints of triestatic void display(trie root, trie itr, char []str, int level){ // Count current child int currChild = 0; for(int i = 0; i < CHILDREN; i++) { // Check for NON null child is found // add parent key to str and // call the display function // recursively for child node if (itr.child[i] != null) { str[level] = (char)(i + 'a'); display(root, itr.child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { Console.Write(str[level - 1] + \"\\n\"); }} // Function call for displaying Jointstatic void displayJoint(trie root){ int level = 0; char []str = new char[MAX]; display(root, root, str, level);} // Driver codepublic static void Main(String[] args){ trie root = createNode(); String []s = { \"geek\", \"geeky\", \"geeks\", \"gel\" }; foreach(String str in s) { insert(root, str); } displayJoint(root);}} // This code is contributed by Rajput-Ji", "e": 36719, "s": 34098, "text": null }, { "code": "<script> // Javascript program to print all the // joints of a Trie constructed // from a given set of Strings let CHILDREN = 26; let MAX = 100; // Trie node class trie { constructor() { } } // Function will return the // new node(initialized to nulls) function createNode(endOfWord) { let temp = new trie(); temp.child = new trie(CHILDREN); temp.endOfWord = endOfWord; for (let i = 0; i < CHILDREN; i++) { temp.child[i] = null; } return temp; } // Function will insert the // String in a trie recursively function insertRecursively(itr, str, i) { if (i < str.length) { let index = str[i].charCodeAt() - 'a'.charCodeAt(); if (itr.child[index] == null) { // Create a new node itr.child[index] = createNode(false); } // Recursive call for insertion // of String insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true // which represents // the end of String itr.endOfWord = true; } } // Function call to insert a String function insert(itr, str) { // Function call with // necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the // node is leaf or not function isLeafNode(root) { return root.endOfWord != false; } // Function to display the Joints of trie function display(root, itr, str, level) { // Count current child let currChild = 0; for (let i = 0; i < CHILDREN; i++) { // Check for NON null child is found // add parent key to str and // call the display function // recursively for child node if (itr.child[i] != null) { str[level] = String.fromCharCode(i + 'a'.charCodeAt()); display(root, itr.child[i], str, level + 1); currChild++; } } // Print character if it has more // than 1 child if (currChild > 1 && itr != root) { document.write(str[level - 1] + \"</br>\"); } } // Function call for displaying Joint function displayJoint(root) { let level = 0; let str = new Array(MAX); display(root, root, str, level); } let root = createNode(false); let s = [ \"geek\", \"geeky\", \"geeks\", \"gel\" ]; for (let str = 0; str < s.length; str++) { insert(root, s[str]); } displayJoint(root); // This code is contributed by mukesh07.</script>", "e": 39491, "s": 36719, "text": null }, { "code": null, "e": 39495, "s": 39491, "text": "k\ne" }, { "code": null, "e": 39512, "s": 39497, "text": "sapnasingh4991" }, { "code": null, "e": 39522, "s": 39512, "text": "Rajput-Ji" }, { "code": null, "e": 39532, "s": 39522, "text": "rutvik_56" }, { "code": null, "e": 39541, "s": 39532, "text": "mukesh07" }, { "code": null, "e": 39546, "s": 39541, "text": "Trie" }, { "code": null, "e": 39570, "s": 39546, "text": "Advanced Data Structure" }, { "code": null, "e": 39578, "s": 39570, "text": "Strings" }, { "code": null, "e": 39583, "s": 39578, "text": "Tree" }, { "code": null, "e": 39591, "s": 39583, "text": "Strings" }, { "code": null, "e": 39596, "s": 39591, "text": "Tree" }, { "code": null, "e": 39601, "s": 39596, "text": "Trie" }, { "code": null, "e": 39699, "s": 39601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39728, "s": 39699, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 39770, "s": 39728, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 39816, "s": 39770, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 39852, "s": 39816, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 39866, "s": 39852, "text": "Interval Tree" }, { "code": null, "e": 39912, "s": 39866, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 39937, "s": 39912, "text": "Reverse a string in Java" }, { "code": null, "e": 39997, "s": 39937, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 40012, "s": 39997, "text": "C++ Data Types" } ]
Python - Find starting index of all Nested Lists - GeeksforGeeks
31 May, 2021 In this article given a matrix, the task is to write a Python program to compute the starting index of all the nested lists. Example: Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] Output : [0, 1, 5, 7, 13] Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ], hence 5. as 3rd element in result list. Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [3, 4, 5]] Output : [0, 1, 5, 7] Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ], hence 5. as 3rd element in result list. Method #1 : Using loop + len() In this, length of each sublist is computed using len() and summed, cumulatively, and added as intermediate result. The initial index is derivative of lengths of sublists. Python3 # Python3 code to demonstrate working of# Initial element index in Matrix# Using loop # initializing listtest_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] # printing original listprint("The original list is : " + str(test_list)) res = []lens = 0for sub in test_list: # lengths of sublist computed res.append(lens) lens += len(sub) # printing resultprint("Initial element indices : " + str(res)) Output: The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] Initial element indices : [0, 1, 5, 7, 13] Method #2 : Using accumulate() + map() + len() In this, we perform task of getting summation using accumulate(), map() is used to get lengths of all the sublists computed using len(). Python3 # Python3 code to demonstrate working of# Initial element index in Matrix# Using accumulate() + map() + len()from itertools import accumulate # initializing listtest_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] # printing original listprint("The original list is : " + str(test_list)) # ignoring last index using "-1"# sum starting at 0res = [0, *accumulate(map(len, test_list[:-1]))] # printing resultprint("Initial element indices : " + str(res)) Output: The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] Initial element indices : [0, 1, 5, 7, 13] Method #3 : Using type() and loop and a if statement In this, we simply check the type of the element in the list if it’s another list we print its index otherwise not. This method will work regardless of the number of non-list type elements in the list Python3 # This will print all the starting indexes# of sublists inside this listlis = [[1,2,3],4,5,[6,7,8],9,0,[10]] for i in lis: if type(i) == list: print(lis.index(i), end=",") # This code is contributed by BABAji Output: 0,3,6, as904465 Python list-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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe 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": "\n31 May, 2021" }, { "code": null, "e": 25662, "s": 25537, "text": "In this article given a matrix, the task is to write a Python program to compute the starting index of all the nested lists." }, { "code": null, "e": 25671, "s": 25662, "text": "Example:" }, { "code": null, "e": 25750, "s": 25671, "text": "Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]" }, { "code": null, "e": 25776, "s": 25750, "text": "Output : [0, 1, 5, 7, 13]" }, { "code": null, "e": 25889, "s": 25776, "text": "Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ], " }, { "code": null, "e": 25929, "s": 25889, "text": "hence 5. as 3rd element in result list." }, { "code": null, "e": 25988, "s": 25929, "text": "Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [3, 4, 5]]" }, { "code": null, "e": 26010, "s": 25988, "text": "Output : [0, 1, 5, 7]" }, { "code": null, "e": 26122, "s": 26010, "text": "Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ]," }, { "code": null, "e": 26162, "s": 26122, "text": "hence 5. as 3rd element in result list." }, { "code": null, "e": 26193, "s": 26162, "text": "Method #1 : Using loop + len()" }, { "code": null, "e": 26365, "s": 26193, "text": "In this, length of each sublist is computed using len() and summed, cumulatively, and added as intermediate result. The initial index is derivative of lengths of sublists." }, { "code": null, "e": 26373, "s": 26365, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Initial element index in Matrix# Using loop # initializing listtest_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) res = []lens = 0for sub in test_list: # lengths of sublist computed res.append(lens) lens += len(sub) # printing resultprint(\"Initial element indices : \" + str(res))", "e": 26799, "s": 26373, "text": null }, { "code": null, "e": 26807, "s": 26799, "text": "Output:" }, { "code": null, "e": 26889, "s": 26807, "text": "The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]" }, { "code": null, "e": 26932, "s": 26889, "text": "Initial element indices : [0, 1, 5, 7, 13]" }, { "code": null, "e": 26979, "s": 26932, "text": "Method #2 : Using accumulate() + map() + len()" }, { "code": null, "e": 27117, "s": 26979, "text": "In this, we perform task of getting summation using accumulate(), map() is used to get lengths of all the sublists computed using len(). " }, { "code": null, "e": 27125, "s": 27117, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Initial element index in Matrix# Using accumulate() + map() + len()from itertools import accumulate # initializing listtest_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # ignoring last index using \"-1\"# sum starting at 0res = [0, *accumulate(map(len, test_list[:-1]))] # printing resultprint(\"Initial element indices : \" + str(res))", "e": 27595, "s": 27125, "text": null }, { "code": null, "e": 27603, "s": 27595, "text": "Output:" }, { "code": null, "e": 27685, "s": 27603, "text": "The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]" }, { "code": null, "e": 27728, "s": 27685, "text": "Initial element indices : [0, 1, 5, 7, 13]" }, { "code": null, "e": 27781, "s": 27728, "text": "Method #3 : Using type() and loop and a if statement" }, { "code": null, "e": 27982, "s": 27781, "text": "In this, we simply check the type of the element in the list if it’s another list we print its index otherwise not. This method will work regardless of the number of non-list type elements in the list" }, { "code": null, "e": 27990, "s": 27982, "text": "Python3" }, { "code": "# This will print all the starting indexes# of sublists inside this listlis = [[1,2,3],4,5,[6,7,8],9,0,[10]] for i in lis: if type(i) == list: print(lis.index(i), end=\",\") # This code is contributed by BABAji", "e": 28217, "s": 27990, "text": null }, { "code": null, "e": 28225, "s": 28217, "text": "Output:" }, { "code": null, "e": 28232, "s": 28225, "text": "0,3,6," }, { "code": null, "e": 28241, "s": 28232, "text": "as904465" }, { "code": null, "e": 28262, "s": 28241, "text": "Python list-programs" }, { "code": null, "e": 28269, "s": 28262, "text": "Python" }, { "code": null, "e": 28285, "s": 28269, "text": "Python Programs" }, { "code": null, "e": 28383, "s": 28285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28415, "s": 28383, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28457, "s": 28415, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28499, "s": 28457, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28526, "s": 28499, "text": "Python Classes and Objects" }, { "code": null, "e": 28582, "s": 28526, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28604, "s": 28582, "text": "Defaultdict in Python" }, { "code": null, "e": 28643, "s": 28604, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28689, "s": 28643, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28727, "s": 28689, "text": "Python | Convert a list to dictionary" } ]
Python | Tensorflow log() method - GeeksforGeeks
13 Dec, 2021 Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. The module tensorflow.math provides support for many basic mathematical operations. Function tf.log() [alias tf.math.log] provides support for the natural logarithmic function in Tensorflow. It expects the input in form of complex numbers as or floating point numbers. The input type is tensor and if the input contains more than one element, an element-wise logarithm is computed, . Syntax: tf.log(x, name=None) or tf.math.log(x, name=None)Parameters: x: A Tensor of type bfloat16, half, float32, float64, complex64 or complex128. name (optional): The name for the operation.Return type: A Tensor with the same size and type as that of x. Code #1: Python3 # Importing the Tensorflow libraryimport tensorflow as tf # A constant vector of size 5a = tf.constant([-0.5, -0.1, 0, 0.1, 0.5], dtype = tf.float32) # Applying the log function and# storing the result in 'b'b = tf.log(a, name ='log') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input type:', a) print('Input:', sess.run(a)) print('Return type:', b) print('Output:', sess.run(b)) Output: Input type: Tensor("Const:0", shape=(5, ), dtype=float32) Input: [-0.5 -0.1 0. 0.1 0.5] Return type: Tensor("log:0", shape=(5, ), dtype=float32) Output: [ nan nan -inf -2.3025851 -0.6931472] denotes that natural logarithm doesn’t exist for negative values and denotes that it approaches to negative infinity as the input approaches zero.Code #2: Visualization Python3 # Importing the Tensorflow libraryimport tensorflow as tf # Importing the NumPy libraryimport numpy as np # Importing the matplotlib.pyplot functionimport matplotlib.pyplot as plt # A vector of size 20 with values from 0 to 1 and 1 to 10a = np.append(np.linspace(0, 1, 10), np.linspace(1, 10, 10)) # Applying the logarithmic function and# storing the result in 'b'b = tf.log(a, name ='log') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input:', a) print('Output:', sess.run(b)) plt.plot(a, sess.run(b), color = 'red', marker = "o") plt.title("tensorflow.abs") plt.xlabel("X") plt.ylabel("Y") plt.grid() plt.show() Output: Input: [ 0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. ] Output: [ -inf -2.19722458 -1.5040774 -1.09861229 -0.81093022 -0.58778666 -0.40546511 -0.25131443 -0.11778304 0. 0. 0.69314718 1.09861229 1.38629436 1.60943791 1.79175947 1.94591015 2.07944154 2.19722458 2.30258509] sweetyty simmytarika5 Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 25999, "s": 25971, "text": "\n13 Dec, 2021" }, { "code": null, "e": 26518, "s": 25999, "text": "Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. The module tensorflow.math provides support for many basic mathematical operations. Function tf.log() [alias tf.math.log] provides support for the natural logarithmic function in Tensorflow. It expects the input in form of complex numbers as or floating point numbers. The input type is tensor and if the input contains more than one element, an element-wise logarithm is computed, ." }, { "code": null, "e": 26776, "s": 26518, "text": "Syntax: tf.log(x, name=None) or tf.math.log(x, name=None)Parameters: x: A Tensor of type bfloat16, half, float32, float64, complex64 or complex128. name (optional): The name for the operation.Return type: A Tensor with the same size and type as that of x. " }, { "code": null, "e": 26786, "s": 26776, "text": "Code #1: " }, { "code": null, "e": 26794, "s": 26786, "text": "Python3" }, { "code": "# Importing the Tensorflow libraryimport tensorflow as tf # A constant vector of size 5a = tf.constant([-0.5, -0.1, 0, 0.1, 0.5], dtype = tf.float32) # Applying the log function and# storing the result in 'b'b = tf.log(a, name ='log') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input type:', a) print('Input:', sess.run(a)) print('Return type:', b) print('Output:', sess.run(b))", "e": 27209, "s": 26794, "text": null }, { "code": null, "e": 27218, "s": 27209, "text": "Output: " }, { "code": null, "e": 27432, "s": 27218, "text": "Input type: Tensor(\"Const:0\", shape=(5, ), dtype=float32)\nInput: [-0.5 -0.1 0. 0.1 0.5]\nReturn type: Tensor(\"log:0\", shape=(5, ), dtype=float32)\nOutput: [ nan nan -inf -2.3025851 -0.6931472]" }, { "code": null, "e": 27602, "s": 27432, "text": "denotes that natural logarithm doesn’t exist for negative values and denotes that it approaches to negative infinity as the input approaches zero.Code #2: Visualization " }, { "code": null, "e": 27610, "s": 27602, "text": "Python3" }, { "code": "# Importing the Tensorflow libraryimport tensorflow as tf # Importing the NumPy libraryimport numpy as np # Importing the matplotlib.pyplot functionimport matplotlib.pyplot as plt # A vector of size 20 with values from 0 to 1 and 1 to 10a = np.append(np.linspace(0, 1, 10), np.linspace(1, 10, 10)) # Applying the logarithmic function and# storing the result in 'b'b = tf.log(a, name ='log') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input:', a) print('Output:', sess.run(b)) plt.plot(a, sess.run(b), color = 'red', marker = \"o\") plt.title(\"tensorflow.abs\") plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.grid() plt.show()", "e": 28271, "s": 27610, "text": null }, { "code": null, "e": 28281, "s": 28271, "text": "Output: " }, { "code": null, "e": 28770, "s": 28281, "text": "Input: [ 0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556\n 0.66666667 0.77777778 0.88888889 1. 1. 2.\n 3. 4. 5. 6. 7. 8.\n 9. 10. ]\nOutput: [ -inf -2.19722458 -1.5040774 -1.09861229 -0.81093022 -0.58778666\n -0.40546511 -0.25131443 -0.11778304 0. 0. 0.69314718\n 1.09861229 1.38629436 1.60943791 1.79175947 1.94591015 2.07944154\n 2.19722458 2.30258509]" }, { "code": null, "e": 28783, "s": 28774, "text": "sweetyty" }, { "code": null, "e": 28796, "s": 28783, "text": "simmytarika5" }, { "code": null, "e": 28807, "s": 28796, "text": "Tensorflow" }, { "code": null, "e": 28814, "s": 28807, "text": "Python" }, { "code": null, "e": 28912, "s": 28814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28930, "s": 28912, "text": "Python Dictionary" }, { "code": null, "e": 28965, "s": 28930, "text": "Read a file line by line in Python" }, { "code": null, "e": 28987, "s": 28965, "text": "Enumerate() in Python" }, { "code": null, "e": 29029, "s": 28987, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29059, "s": 29029, "text": "Iterate over a list in Python" }, { "code": null, "e": 29085, "s": 29059, "text": "Python String | replace()" }, { "code": null, "e": 29114, "s": 29085, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29158, "s": 29114, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29195, "s": 29158, "text": "Create a Pandas DataFrame from Lists" } ]
How to hide a div when the user clicks outside of it using jQuery? - GeeksforGeeks
03 Aug, 2021 An element can be hidden or shown based on if the mouse is clicked outside the element using two methods. Method 1: Using the closest method: A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The closest() method is called on the target click. This method returns the first ancestor of the selected element in the DOM tree. The length property is then used on the result to find out the number of ancestors. If there are no ancestors, it means that the click was outside the element.if ($(e.target).closest(".container").length === 0) { // rest code here}The element is hidden using the hide() method.$(".container").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { if ($(e.target).closest(".container").length === 0) { $(".container").hide(); } }); </script></body> </html> Output:Clicking inside the div:Clicking outside the div:Method 2: Checking the element if it contains the click target:A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}The element is hidden using the hide() method.$(".container").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { var container = $(".container"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes arrow_drop_upSave A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here} $(document).mouseup(function (e) { // rest code here} The closest() method is called on the target click. This method returns the first ancestor of the selected element in the DOM tree. The length property is then used on the result to find out the number of ancestors. If there are no ancestors, it means that the click was outside the element.if ($(e.target).closest(".container").length === 0) { // rest code here} if ($(e.target).closest(".container").length === 0) { // rest code here} The element is hidden using the hide() method.$(".container").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { if ($(e.target).closest(".container").length === 0) { $(".container").hide(); } }); </script></body> </html> Output:Clicking inside the div:Clicking outside the div:Method 2: Checking the element if it contains the click target:A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}The element is hidden using the hide() method.$(".container").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { var container = $(".container"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes arrow_drop_upSave $(".container").hide(); Example: <!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { if ($(e.target).closest(".container").length === 0) { $(".container").hide(); } }); </script></body> </html> Output: Clicking inside the div: Clicking outside the div: Method 2: Checking the element if it contains the click target: A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}The element is hidden using the hide() method.$(".container").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { var container = $(".container"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes arrow_drop_upSave A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here} $(document).mouseup(function (e) { // rest code here} The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here} The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element. The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element. if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here} The element is hidden using the hide() method.$(".container").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { var container = $(".container"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes arrow_drop_upSave $(".container").hide(); Example: <!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= "https://code.jquery.com/jquery-3.4.0.min.js"> </script></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class="container" style="color:green"></div> <script type="text/javascript"> $(document).mouseup(function (e) { var container = $(".container"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html> Output: Clicking inside the div: Clicking outside the div: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples How to Show and Hide div elements using radio buttons? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26705, "s": 26677, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26811, "s": 26705, "text": "An element can be hidden or shown based on if the mouse is clicked outside the element using two methods." }, { "code": null, "e": 26847, "s": 26811, "text": "Method 1: Using the closest method:" }, { "code": null, "e": 30775, "s": 26847, "text": "A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The closest() method is called on the target click. This method returns the first ancestor of the selected element in the DOM tree. The length property is then used on the result to find out the number of ancestors. If there are no ancestors, it means that the click was outside the element.if ($(e.target).closest(\".container\").length === 0) { // rest code here}The element is hidden using the hide() method.$(\".container\").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { if ($(e.target).closest(\".container\").length === 0) { $(\".container\").hide(); } }); </script></body> </html> Output:Clicking inside the div:Clicking outside the div:Method 2: Checking the element if it contains the click target:A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}The element is hidden using the hide() method.$(\".container\").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { var container = $(\".container\"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30885, "s": 30775, "text": "A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}" }, { "code": "$(document).mouseup(function (e) { // rest code here}", "e": 30942, "s": 30885, "text": null }, { "code": null, "e": 31309, "s": 30942, "text": "The closest() method is called on the target click. This method returns the first ancestor of the selected element in the DOM tree. The length property is then used on the result to find out the number of ancestors. If there are no ancestors, it means that the click was outside the element.if ($(e.target).closest(\".container\").length === 0) { // rest code here}" }, { "code": "if ($(e.target).closest(\".container\").length === 0) { // rest code here}", "e": 31385, "s": 31309, "text": null }, { "code": null, "e": 34838, "s": 31385, "text": "The element is hidden using the hide() method.$(\".container\").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { if ($(e.target).closest(\".container\").length === 0) { $(\".container\").hide(); } }); </script></body> </html> Output:Clicking inside the div:Clicking outside the div:Method 2: Checking the element if it contains the click target:A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}The element is hidden using the hide() method.$(\".container\").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { var container = $(\".container\"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes\narrow_drop_upSave" }, { "code": "$(\".container\").hide();", "e": 34862, "s": 34838, "text": null }, { "code": null, "e": 34871, "s": 34862, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { if ($(e.target).closest(\".container\").length === 0) { $(\".container\").hide(); } }); </script></body> </html> ", "e": 35849, "s": 34871, "text": null }, { "code": null, "e": 35857, "s": 35849, "text": "Output:" }, { "code": null, "e": 35882, "s": 35857, "text": "Clicking inside the div:" }, { "code": null, "e": 35908, "s": 35882, "text": "Clicking outside the div:" }, { "code": null, "e": 35972, "s": 35908, "text": "Method 2: Checking the element if it contains the click target:" }, { "code": null, "e": 38252, "s": 35972, "text": "A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}The element is hidden using the hide() method.$(\".container\").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { var container = $(\".container\"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 38362, "s": 38252, "text": "A mouseup event is to first checked upon the document$(document).mouseup(function (e) { // rest code here}" }, { "code": "$(document).mouseup(function (e) { // rest code here}", "e": 38419, "s": 38362, "text": null }, { "code": null, "e": 39152, "s": 38419, "text": "The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}" }, { "code": null, "e": 39358, "s": 39152, "text": "The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element." }, { "code": null, "e": 39644, "s": 39358, "text": "The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element." }, { "code": "if(!container.is(e.target) && container.has(e.target).length === 0) { // rest code here}", "e": 39736, "s": 39644, "text": null }, { "code": null, "e": 41175, "s": 39736, "text": "The element is hidden using the hide() method.$(\".container\").hide();Example:<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { var container = $(\".container\"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>Output:Clicking inside the div:Clicking outside the div:jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.My Personal Notes\narrow_drop_upSave" }, { "code": "$(\".container\").hide();", "e": 41199, "s": 41175, "text": null }, { "code": null, "e": 41208, "s": 41199, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to hide a div when the user clicks outside of it using jQuery? </title> <style> .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </style> <script src= \"https://code.jquery.com/jquery-3.4.0.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to hide a div when the user clicks outside of it using jQuery? </b> <p>Click outside the green div to hide it</p> <div class=\"container\" style=\"color:green\"></div> <script type=\"text/javascript\"> $(document).mouseup(function (e) { var container = $(\".container\"); if(!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script></body> </html>", "e": 42212, "s": 41208, "text": null }, { "code": null, "e": 42220, "s": 42212, "text": "Output:" }, { "code": null, "e": 42245, "s": 42220, "text": "Clicking inside the div:" }, { "code": null, "e": 42271, "s": 42245, "text": "Clicking outside the div:" }, { "code": null, "e": 42539, "s": 42271, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 42551, "s": 42539, "text": "jQuery-Misc" }, { "code": null, "e": 42558, "s": 42551, "text": "Picked" }, { "code": null, "e": 42565, "s": 42558, "text": "JQuery" }, { "code": null, "e": 42582, "s": 42565, "text": "Web Technologies" }, { "code": null, "e": 42609, "s": 42582, "text": "Web technologies Questions" }, { "code": null, "e": 42707, "s": 42609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42736, "s": 42707, "text": "Form validation using jQuery" }, { "code": null, "e": 42792, "s": 42736, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 42846, "s": 42792, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 42880, "s": 42846, "text": "jQuery | children() with Examples" }, { "code": null, "e": 42935, "s": 42880, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 42975, "s": 42935, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 43008, "s": 42975, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 43053, "s": 43008, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 43096, "s": 43053, "text": "How to fetch data from an API in ReactJS ?" } ]